javaweb(3.1)登录权限控制实战

  • • 发表于 7年前
  • • 作者 大妖怪
  • • 3199 人浏览
  • • 7 条评论
  • • 最后编辑时间 7年前
  • • 来自 [技 术]

原创声明:本文为作者原创,未经允许不得转载,经授权转载需注明作者和出处

上一章的demo中,我们不管是数据传输,业务处理还是持久化数据(操作数据库)都是在servlet文件中完成的,这样做,可能会显得比较乱,因此在实际开发过程中,我们会根据不同的功能将项目分为几个层级:

  • servlet层:处理页面转跳和数据传输。
  • service层:处理主要的业务逻辑。
  • dao层:数据持久化。
  • bean层:数据模型。

今天用分层的方式带大家做一个实战小项目处理用网页的登录权限:实现用户登录之后进入主页并且显示用户姓名,并且一定时间内直接输入主页的地址还是可以访问,超过时间了再输入主页地址就需要重新登录的功能:
项目结构是这样的:

  • login.jsp:登录页面,主要实现表单提交和接收错误信息
    <%@ page language="java" contentType="text/html; charset=utf-8"
      pageEncoding="utf-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>登录</title>
    </head>
    <body>
      <form action="login" method="post">
          <div style="color: red;">${requestScope.error }</div><!-- 获取错误信息 -->
          用户名:<input type="text" name="userName" /><br />
          密码:<input type="password" name="password" /><br />
          <input type="submit" value="登录" />
      </form>
    </body>
    </html>
    
  • index.jsp: 主页,主要实现从session中获取用户信息并显示
    <%@ page language="java" contentType="text/html; charset=UTF-8"
      pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>主页</title>
    </head>
    <body>
      用户编号:${sessionScope.user.id }<br /><!-- 从session中获取用户参数 -->
      用户名:${sessionScope.user.userName }
    </body>
    </html>
    
  • LoginServlet doPost方法:主要实现页面转跳,参数传递
    @Override
      protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
          //接收到的账号密码
          String userName = req.getParameter("userName");
          String password = req.getParameter("password");
          LoginService loginService = new LoginService();
          boolean result = loginService.login(userName,password,req, resp);
          if(result){
              resp.sendRedirect(req.getContextPath()+"/index.jsp");//重定向到主页
          }else{
              req.setAttribute("error", "用户名或密码输入错误");
              req.getRequestDispatcher( "/login.jsp").forward(req,resp); //请求转发到主页
          }
      }
    
  • LoginService login方法:主要处理业务逻辑(判断用户是否存在)
    public boolean login(String userName, String password, HttpServletRequest req, HttpServletResponse resp) {
          LoginDao loginDao = new LoginDao();
          User user = loginDao.login(userName, password);
          if(user!=null){//用户不为空
              // 手动设置session的有效期为60秒
              HttpSession session = req.getSession();
              String sessionId = session.getId();
              Cookie cookie = new Cookie("sessionId", sessionId);
              cookie.setPath(req.getContextPath());
              resp.addCookie(cookie);
              session.setAttribute("user", user);
              session.setMaxInactiveInterval(60);
              return true;
          }else{
              return false;
          }
      }
    
  • LoginDao:主要实现持久化功能(和数据库打交道)

    public class LoginDao {
      // JDBC 驱动
      private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
      //数据库地址 格式是 jdbc:mysql://数据库地址(可以是ip地址):端口号(默认是3306)/数据库名
      private static final String URL = "jdbc:mysql://localhost:3306/loginDemo";
    
      // 数据库的用户名与密码,需要根据自己的设置
      private static final String USER = "root";
      private static final String PASS = "root"; 
    
      /**
      * @Title: login
      * @Description: TODO(登陆)
      * @param @param userName
      * @param @param password
      * @param @return    设定文件
      * @return User    返回类型
      * @throws
       */
      public User login(String userName, String password) {
          Connection conn = null;
          Statement stmt = null;
          User user = null;
          try{
              // 注册 JDBC 驱动器
              Class.forName(JDBC_DRIVER);
    
              // 打开一个连接
              conn = DriverManager.getConnection(URL,USER,PASS);
    
              //拼接查询的SQL语句
              StringBuffer sql = new StringBuffer("SELECT * FROM USER WHERE userName = '");
              sql.append(userName);
              sql.append("' and password = '").append(password).append("'");
              System.out.println(sql.toString());
              // 执行 SQL 语句
              stmt = conn.createStatement();
              ResultSet rs = stmt.executeQuery(sql.toString());
    
              // 展开结果集数据
              if(rs.next()){
                  //获取查出来的字段
                  int id  = rs.getInt("id");
                  userName = rs.getString("userName");
    
                  user = new User(id, userName);
              }else{
                  user = null;
              }
          } catch(Exception se) {
              // 处理 异常
              se.printStackTrace();
          }finally{
              //关闭资源
              try{
                  if(stmt!=null)
                  stmt.close();
              }catch(SQLException se2){
              }
              try{
                  if(conn!=null)
                  conn.close();
              }catch(SQLException se){
                  se.printStackTrace();
              }
          }
    
          return user;
      }
    
  • user: 实体类(参数封装)

    public class User {
    
      private int id;//主键
    
      private String userName;//用户名
    
      private String password;//密码
    
      /**
       * 构造函数
      * <p>Title: </p>
      * <p>Description: </p>
      * @param id
      * @param userName
       */
      public User(int id, String userName) {
          super();
          this.id = id;
          this.userName = userName;
      }
    
      public int getId() {
          return id;
      }
    
      public void setId(int id) {
          this.id = id;
      }
    
      public String getUserName() {
          return userName;
      }
    
      public void setUserName(String userName) {
          this.userName = userName;
      }
    
      public String getPassword() {
          return password;
      }
    
      public void setPassword(String password) {
          this.password = password;
      }
    }
    

    ok,以上就是本次实战的主要代码了,项目的逻辑:

    那么当我们访问的时候,首先输入错误密码:

    输入正确密码:

    登录之后60(因为程序里设置的session过期时间为60秒)秒不操作或者没有登录的情况直接访问主页地址:

    登录过后60秒之内直接访问主页地址:

    最后附上项目源码和Sql文件:
    sql文件:https://pan.baidu.com/s/1bpIkgTx
    项目源码:http://pan.baidu.com/s/1bpF3xZD

分享到:
评论区(共7条评论)
7条评论
Ctrl+Enter
作者

大妖怪

大妖怪

APP:1 帖子:76 回复:200 积分:7517

已加入社区[2591]天

梦里巷口,可有你倚门回首

作者详情》
Top