注意:
- 项目地址:
- 连接中的项目到登录模块位置,其他功能还没有完成
- 跟模块有关的文件login.java以及login.html 4.用到的jar包:druid数据库连接池以及DbUtils
整体想法
有了前面的注册模块做铺垫,这个模块做起来就简单多了,整体的想法就是
- 获取post请求中的用户名和密码
- 看看数据库中能否查到有对应用户名密码的用户
- 如果存在提示登录成功跳转主页
- 如果没有提示用户名或密码错误,重新跳转回登录页面
模块代码如下
import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import com.zzy.domain.User; import com.zzy.util.JdbcUtil; /** * Servlet implementation class LoginSevlet */ @WebServlet("/LoginServlet") public class LoginSevlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取请求参数 String username=request.getParameter("username"); String password=request.getParameter("password"); //查询用户是否存在 String sql="select* from user where username=? and password=?"; QueryRunner qr=new QueryRunner(JdbcUtil.getDataSource()); User u=null; try { u=qr.query(sql,new BeanHandler<User>(User.class),username,password); } catch(SQLException sqle) { sqle.printStackTrace(); } response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); PrintWriter writer = response.getWriter(); if(u==null) { //提示错误,返回登录页面 writer.write("用户名或密码错误"); response.setHeader("refresh", "2;url=/store/login.html"); }else { //提示正确,跳转到首页 writer.write("登录成功"); response.setHeader("refresh", "2;url=/store/index.html"); } } }