欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Session实战权限认证

程序员文章站 2022-05-18 23:27:28
1...

创建管理员表

create table manager(
		username varchar(20) primary key,
        password varchar(20) not null
)charset=utf8;

向manager表添加数据

insert into manager(username,password)values('tom','123');

Manager.java

package com.newer.servletProject.entity;

public class Manager {
    private String username;
    private String password;

    public Manager() {
    }

    public Manager(String username, String password) {
        this.username = username;
        this.password = password;
    }

    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;
    }

    @Override
    public String toString() {
        return "Manager{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

ManagerDao.java

package com.newer.servletProject.dao;

import com.newer.servletProject.entity.Manager;

public interface ManagerDao {
    public Manager select(String username);
}

ManagerDaoImpl.java

package com.newer.servletProject.dao.impl;

import com.newer.servletProject.dao.ManagerDao;
import com.newer.servletProject.entity.Manager;
import com.newer.servletProject.utils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

public class ManagerDaoImpl implements ManagerDao {
    private QueryRunner queryRunner = new QueryRunner();

    @Override
    public Manager select(String username) {
        try {
            Manager manager = queryRunner.query(DbUtils.getConnection(), "select * from manager where username=?", new BeanHandler<Manager>(Manager.class), username);
            return manager;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return  null;
    }
}

ManagerService.java

package com.newer.servletProject.service;

import com.newer.servletProject.entity.Manager;

public interface ManagerService {
    public Manager login(String username,String password);
}

ManagerServiceImpl.java

package com.newer.servletProject.service.impl;

import com.newer.servletProject.dao.ManagerDao;
import com.newer.servletProject.dao.impl.ManagerDaoImpl;
import com.newer.servletProject.entity.Manager;
import com.newer.servletProject.service.ManagerService;
import com.newer.servletProject.utils.DbUtils;

public class ManagerServiceImpl implements ManagerService {
    //创建ManagerDao对象
    private ManagerDao managerDao=new ManagerDaoImpl();
    @Override
    public Manager login(String username, String password) {
        Manager manager=null;
        try {
            DbUtils.begin();
            Manager temp=managerDao.select(username);
            if(temp!=null){
                if(temp.getPassword().equals(password)){
                    manager=temp;
                }
            }
            DbUtils.commit();
        } catch (Exception e) {
            DbUtils.rollback();
            e.printStackTrace();
        }
        return manager;
    }
}

DbUtils.java

package com.newer.servletProject.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DbUtils {
    private static DruidDataSource ds;  //数据库连接池
    private static final ThreadLocal<Connection> THREAD_LOCAL = new ThreadLocal<>();  //控制事务,用Connection存储

    static {
        Properties properties = new Properties(); //properties集合
        InputStream inputStream = DbUtils.class.getResourceAsStream("/database.properties");
      /*  System.out.println(inputStream+"11111");*/
        try {
            properties.load(inputStream);  //通过properties把文件加载进来
           /* System.out.println(properties+"222222");*/
            ds = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);   //创建数据库连接池并强制转换

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //提供一个方法
    public static Connection getConnection() {
        Connection connection = THREAD_LOCAL.get();   //通过THREAD_LOCAL去拿连接
        try {
            if (connection == null) {
                connection = ds.getConnection();  //如果connection为空,就去连接池里拿
                THREAD_LOCAL.set(connection);   //然后通过THREAD_LOCAL存进去
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    //定义开启事务的方法
    public static void begin() {
        Connection connection = null;
        try {
            connection = getConnection(); //调用getConnection方法获取连接
            connection.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //事务提交的方法
    public static void commit() {
        Connection connection = null;
        try {
            connection = getConnection();
            connection.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll(connection, null, null); //连接释放
        }
    }

    public static void rollback() {
        Connection connection = null;
        try {
            connection = getConnection();
            connection.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll(connection, null, null); //连接释放
        }
    }

    public static void closeAll(Connection connection, Statement statement, ResultSet resultSet) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
                THREAD_LOCAL.remove();  //从连接池中移除
            }


        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

LoginMgrController.java

package com.newer.servletProject.servlet.controller;

import com.newer.servletProject.entity.Manager;
import com.newer.servletProject.service.ManagerService;
import com.newer.servletProject.service.impl.ManagerServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "LoginMgrController",value = "/loginMgr")
public class LoginMgrController extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1.处理乱码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");

        //2.收参
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        String inputVcode=request.getParameter("inputVcode");

        //从request对象中获取codes
        String codes=(String)request.getSession().getAttribute("codes");
        //判断验证码
        if(!inputVcode.isEmpty()&&inputVcode.equalsIgnoreCase(codes)){
            //3.调用业务方法
            ManagerService managerService=new ManagerServiceImpl();
            Manager mgr=managerService.login(username,password);

            //4.处理结果,流程跳转
            if(mgr!=null){
                //登录成功

                //将管理员信息存储在session中
                HttpSession session=request.getSession();
                session.setAttribute("mgr",mgr);

                //跳转,目标,方式
                response.sendRedirect("/day01web1_war_exploded/showallController");

            }else {
                //登录失败
                response.sendRedirect("/day01web1_war_exploded/loginMgr.html");
            }
        }else {
            response.sendRedirect("/day01web1_war_exploded/loginMgr.html");
        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}

ShowAllAdminController.java

package com.newer.servletProject.servlet.controller;

import com.newer.servletProject.entity.Admin;
import com.newer.servletProject.entity.Manager;
import com.newer.servletProject.service.AdminService;
import com.newer.servletProject.service.impl.AdminServiceImpl;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
@WebServlet(value = "/showallController")
public class ShowAllAdminController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //通过HttpSession完成权限控制
      /*  HttpSession session= req.getSession();
        Manager mgr=(Manager)session.getAttribute("mgr");*/
       /* if (mgr!=null){*/
            //只负责调用业务逻辑
            AdminService adminService = new AdminServiceImpl();
            List<Admin> adminList = adminService.showAllAdmin();    //调用业务逻辑层

            //request作用域
            req.setAttribute("admins",adminList);
            //通过转发,跳转到显示结果servlet
            req.getRequestDispatcher("/showalljsp").forward(req,resp);
       /* }else {
            resp.sendRedirect("/day01web1_war_exploded/loginMgr.html");
        }*/




    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}

loginMgr.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>管理员登录</title>
</head>
<body>
    <form action="/day01web1_war_exploded/loginMgr" method="post">
        用户名:<input type="text" name="username"/><br/>
        密码:<input type="password" name="password"/><br/>
        验证码:<input type="text" name="inputVcode"/><img src="/day01web1_war_exploded/createCode"/><br/>
        <input type="submit" value="登录"/>

    </form>
</body>
</html>

ShowAllAdminJSP.java

package com.newer.servletProject.servlet.jsp;

import com.newer.servletProject.entity.Admin;
import com.newer.servletProject.entity.Manager;
import com.newer.servletProject.service.AdminService;
import com.newer.servletProject.service.impl.AdminServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(value = "/showalljsp")
public class ShowAllAdminJSP extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        HttpSession session=req.getSession();
        Manager mgr=(Manager)session.getAttribute("mgr") ;

        //将拿到的值强转为List类型
        List<Admin> adminList = (List) req.getAttribute("admins");
        PrintWriter printWriter = resp.getWriter();
        if (adminList != null) {
            printWriter.println("<html>");
            printWriter.println("<head>");
            printWriter.println("<meta charset='UTF-8'>");
            printWriter.println("<title>显示所有</title>");
            printWriter.println("</head>");
            printWriter.println("<body>");
            printWriter.println("<h1>欢迎你:"+mgr.getUsername()+"</h1>");
            printWriter.println("<table border='1'>");
            printWriter.println("   <tr>");
            printWriter.println("       <td>username</td>");
            printWriter.println("       <td>password</td>");
            printWriter.println("       <td>phone</td>");
            printWriter.println("       <td>address</td>");
            printWriter.println("   </tr>");
            for (Admin admin : adminList) {
                printWriter.println("   <tr>");
                printWriter.println("       <td>" + admin.getUsername() + "</td>");
                printWriter.println("       <td>" + admin.getPassword() + "</td>");
                printWriter.println("       <td>" + admin.getPhone() + "</td>");
                printWriter.println("       <td>" + admin.getAddress() + "</td>");
                printWriter.println("   </tr>");
            }
            printWriter.println("</table>");
            printWriter.println("</body>");
            printWriter.println("</html>");
        } else {
            printWriter.println("<html>");
            printWriter.println("<head>");
            printWriter.println("<meta charset='utf-8'>");
            printWriter.println("<title>结果页面</title>");
            printWriter.println("</head>");
            printWriter.println("<body>");
            printWriter.println("<h3>当前没有用户数据</h3>");
            printWriter.println("</body>");
            printWriter.println("</html>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

用户没有登录正确,浏览器会自动跳转到登录界面。

直接访问展示界面,也会跳转到登录界面。

本文地址:https://blog.csdn.net/weixin_44364444/article/details/109551510

相关标签: Servlet