练习的JavaWeb小案例。用的是JdbcTemplate.
这是servlet:
@WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
//接收参数并封装对象
Map<String, String[]> parameterMap = request.getParameterMap();
Admin loginadmin = new Admin();
String verifycode = request.getParameter("verifycode");
try {
BeanUtils.populate(loginadmin,parameterMap);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//判断验证码
HttpSession session = request.getSession();
String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
if (checkcode_server.equalsIgnoreCase(verifycode)){
//验证码正确
//调用service层
AdminLoginService adminLoginService = new AdminLoginServiceImpl();
Admin admin_log = adminLoginService.login(loginadmin);
if (admin_log != null){
//登录成功
response.sendRedirect("/index.jsp");
}
else {
//登录失败
request.setAttribute("login_error","用户名或密码错误");
request.getRequestDispatcher("/login.jsp").forward(request,response);
}
}else {
//验证码错误
request.setAttribute("cc_error","验证码错误");
request.getRequestDispatcher("/login.jsp").forward(request,response);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
这是Dao层:
public class AdminLoginDaoImpl implements AdminLoginDao {
JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());
@Override
public Admin login(Admin loginAdmin) {
//查询管理员数据库
try{
String sql = "select * from t_admin where admin_name = ? and admin_password = ?";
Admin admin = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Admin>(Admin.class), loginAdmin.getAdmin_name(), loginAdmin.getAdmin_password());
return admin;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
}
单元测试显示可以查询到数据:
public class test {
@Test
public void testAdminLogin(){
Admin admin = new Admin();
admin.setAdmin_name("admin");
admin.setAdmin_password("123456");
AdminLoginService adminLoginService = new AdminLoginServiceImpl();
Admin admin1 = adminLoginService.login(admin);
System.out.println(admin1);
}
"test.test,testAdminLogin
二月 11, 2021 12:04:36 上午 com.alibaba.druid.pool.DruidDataSource info
信息: {dataSource-1} inited
Admin{id=1, admin_name='admin', admin_password='123456'}
Process finished with exit code 0
报错信息: