当前位置: 首页>编程语言>正文

JAVA-EE基于JSP和Servlet实现的部门OA管理系统后端Servlet部分------Java-Web项目

工具类封装JDBC

package com.bjpowernode.oa.utils;

import java.sql.*;
import java.util.ResourceBundle;

public class DBUtil
{
    private static ResourceBundle bundle = ResourceBundle.getBundle("resources.jdbc");
    private static String driver = bundle.getString("driver");
    private static String url = bundle.getString("url");
    private static String user = bundle.getString("user");
    private static String password = bundle.getString("password");
    //JDBC工具类
    static
    {
        //注册驱动
        try
        {
//            Class.forName("com.mysql.jdbc.Driver");//避免写死
            Class.forName(driver);
        }
        catch (ClassNotFoundException e)
        {
            throw new RuntimeException(e);
        }
    }
    public static Connection getConnection() throws SQLException {
        //获取链接
        return DriverManager.getConnection(url,user,password);
    }
    //释放资源
    public static void close(Connection connection, Statement statement, ResultSet resultSet)
    {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

封装用户信息的POJO类ORM对象

package com.bjpowernode.oa.Pojo;

import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpSessionBindingEvent;
import jakarta.servlet.http.HttpSessionBindingListener;

public class User implements HttpSessionBindingListener
{
    private String username;
    private String password;

    public User() {
    }

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

    @Override
    public void valueBound(HttpSessionBindingEvent event) {
        ServletContext application = event.getSession().getServletContext();
        Long onlineCount = (Long)application.getAttribute("onlineCount");
        if(onlineCount == null)
        {
            application.setAttribute("onlineCount",1L);
        }
        else
        {
            onlineCount++;
            application.setAttribute("onlineCount",onlineCount);
        }
    }

    @Override
    public void valueUnbound(HttpSessionBindingEvent event) {
        //因为是推出登录,所以必定不会是null空值
        ServletContext application = event.getSession().getServletContext();
        Long onlineCount = (Long)application.getAttribute("onlineCount");
        onlineCount--;
        application.setAttribute("onlineCount",onlineCount);
    }

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

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

封装部门信息的ORM对象

package com.bjpowernode.oa.Pojo;

import java.util.Objects;

public class Dept
{
    private String deptno;
    private String dname;
    private String loc;

    @Override
    public String toString() {
        return "Dept{" +
                "deptno='" + deptno + '\'' +
                ", dname='" + dname + '\'' +
                ", loc='" + loc + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Dept dept = (Dept) o;
        return Objects.equals(deptno, dept.deptno) && Objects.equals(dname, dept.dname) && Objects.equals(loc, dept.loc);
    }

    @Override
    public int hashCode() {
        return Objects.hash(deptno, dname, loc);
    }

    public String getDeptno() {
        return deptno;
    }

    public void setDeptno(String deptno) {
        this.deptno = deptno;
    }

    public String getDname() {
        return dname;
    }

    public void setDname(String dname) {
        this.dname = dname;
    }

    public String getLoc() {
        return loc;
    }

    public void setLoc(String loc) {
        this.loc = loc;
    }

    public Dept() {
    }

    public Dept(String deptno, String dname, String loc) {
        this.deptno = deptno;
        this.dname = dname;
        this.loc = loc;
    }
}

对没有登录的对象进行拦截的filter

package com.bjpowernode.oa.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException
    {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)res;
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        HttpSession session = request.getSession(false);
        if(session != null && session.getAttribute("user") != null)
        {
            chain.doFilter(request,response);
        }
        else
        {
            response.sendRedirect(request.getContextPath() + "/index.jsp");
        }
    }
}

默认欢迎页,主要用来实现Cookie自动登录效果

package com.bjpowernode.oa.action;

import com.bjpowernode.oa.Pojo.User;
import com.bjpowernode.oa.utils.DBUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/Welcome")
public class Welcome extends HttpServlet
{
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        Cookie[] cookies = request.getCookies();
        String username = null;
        String password = null;
        if (cookies != null)
        {
            for(int i = 0; i < cookies.length; i++)
            {
                if("username".equals(cookies[i].getName()))
                {
                    username = cookies[i].getValue();
                }
                if("password".equals(cookies[i].getName()))
                {
                    password = cookies[i].getValue();
                }
            }
        }
        if(username != null && password != null)
        {
            Connection connection = null;
            PreparedStatement statement = null;
            ResultSet resultSet = null;
            boolean flag = false;
            try
            {
                connection = DBUtil.getConnection();
                String sql = "select * from t_user where username = ? and pssword = ?";
                statement = connection.prepareStatement(sql);
                statement.setString(1,username);
                statement.setString(2,password);
                resultSet = statement.executeQuery();
                if(resultSet.next())
                {
                    flag = true;
                }
            }
            catch (SQLException e)
            {
                throw new RuntimeException(e);
            }
            finally
            {
                DBUtil.close(connection,statement,resultSet);
            }
            if(flag)
            {
                HttpSession session = request.getSession();
                session.setAttribute("user",new User(username,password));
                response.sendRedirect(request.getContextPath() + "/dept/list");
            }
            else
            {
                response.sendRedirect(request.getContextPath() + "/index.jsp");
            }
        }
        else
        {
            response.sendRedirect(request.getContextPath() + "/index.jsp");
        }
    }
}

JSessionID=??这个键值对数据就是cookie保存的信息

对于session关联的cookie来说,这个cookie是保存在浏览器的运行内存中的

用户再次发送请求的时候,会自动把运行内存中的cookie放到请求头内一并发送

服务器就是根据这个值找到对应的对象

session存储在服务器上的,cookie是储存在电脑机器上的

cookie可以存在浏览器运行内存中,也可以放在硬盘内保存

cookie和session都是为了保存会话的状态

这两个机制存在的目的就是为了解决我们的http协议的无状态无连接协议的问题

(无状态无连接)没有请求和响应时,双方不知道对方是否还在

将购物车中的商品编号放到cookie当中,cookie保存到硬盘

下一次再打开,自动读取本地cookie,就还会显示这些商品

购物网站未登录不允许查看商品和保存购物车的原理是,为了记录数据,什么用户喜欢什么样的东西

和针对不同用户给出不同的优惠力度(大数据杀熟),并且可以防止爬虫,和减轻服务器压力(没有购买欲望的客户不让你看)

十天免登录的实现原理如下,保存一个记录了用户名和密码的cookie到本地

当十天内再次访问该网站时,会自动在请求头内发送这个账号用户名和密码到服务器,服务器接收到这个cookie

解密后实现登录

cookie和session都是Http协议的一部分,因为Http协议是无状态和无连接的协议

Http协议规定,任何一个cookie都是由name和value组成的

java的servlet中,对cookie提供了那些支持?

jakarta.servlet.http.HttpCookie

Cookie是带有路径的,不同的cookie会带不同的路径,方便对应的提交信息和用于握手机制的实现

我们java的cookie主要是在response中将信息作为回传给浏览器的,在服务器中只是做一个信息的处理

在Http协议中规定如下,在浏览器发送请求时,会自动携带该路径下的cookie在请求头中给服务器

cookie的name和value都是字符串,cookie的name和value都是字符串

package com.bjpowernode.oa.action;

import com.bjpowernode.oa.Pojo.User;
import com.bjpowernode.oa.utils.DBUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet({"/user/login","/user/exit"})
public class UserServlet extends HttpServlet
{
    //JSessionID=??这个键值对数据就是cookie保存的信息
    //对于session关联的cookie来说,这个cookie是保存在浏览器的运行内存中的
    //用户再次发送请求的时候,会自动把运行内存中的cookie放到请求头内一并发送
    //服务器就是根据这个值找到对应的对象
    //session存储在服务器上的,cookie是储存在电脑机器上的
    //cookie可以存在浏览器运行内存中,也可以放在硬盘内保存
    //cookie和session都是为了保存会话的状态
    //这两个机制存在的目的就是为了解决我们的http协议的无状态无连接协议的问题
    //(无状态无连接)没有请求和响应时,双方不知道对方是否还在
    @Override
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String servletPath = request.getServletPath();
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        if("/user/login".equals(servletPath))
        {
            doLogin(request,response);
        }
        else if("/user/exit".equals(servletPath))
        {
            doExit(request,response);
        }
    }
    //将购物车中的商品编号放到cookie当中,cookie保存到硬盘
    //下一次再打开,自动读取本地cookie,就还会显示这些商品
    //购物网站未登录不允许查看商品和保存购物车的原理是,为了记录数据,什么用户喜欢什么样的东西
    //和针对不同用户给出不同的优惠力度(大数据杀熟),并且可以防止爬虫,和减轻服务器压力(没有购买欲望的客户不让你看)
    //十天免登录的实现原理如下,保存一个记录了用户名和密码的cookie到本地
    //当十天内再次访问该网站时,会自动在请求头内发送这个账号用户名和密码到服务器,服务器接收到这个cookie
    //解密后实现登录
    //cookie和session都是Http协议的一部分,因为Http协议是无状态和无连接的协议
    //Http协议规定,任何一个cookie都是由name和value组成的
    //在java的servlet中,对cookie提供了那些支持?
    //jakarta.servlet.http.HttpCookie
    //Cookie是带有路径的,不同的cookie会带不同的路径,方便对应的提交信息和用于握手机制的实现
    //我们java的cookie主要是在response中将信息作为回传给浏览器的,在服务器中只是做一个信息的处理
    //在Http协议中规定如下,在浏览器发送请求时,会自动携带该路径下的cookie在请求头中给服务器
    //cookie的name和value都是字符串,cookie的name和value都是字符串
    private void doExit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        HttpSession session = request.getSession(false);
        if(session != null && session.getAttribute("user") != null)
        {
            //从session域中移除对象
            session.removeAttribute("user");
            //销毁session的方法,session.invalidate()
            session.invalidate();
            Cookie[] cookies = request.getCookies();
            for (Cookie cookie : cookies)
            {
                cookie.setMaxAge(0);
                cookie.setPath(request.getContextPath());
                response.addCookie(cookie);
            }
            response.sendRedirect(request.getContextPath());
        }
    }
    protected void doLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String loginSet = request.getParameter("flag");
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        boolean flag = false;
        try
        {
            connection = DBUtil.getConnection();
            String sql = "select * from t_user where username = ? and pssword = ?";
            statement = connection.prepareStatement(sql);
            statement.setString(1,username);
            statement.setString(2,password);
            resultSet = statement.executeQuery();
            if(resultSet.next())
            {
                flag = true;
            }

        }
        catch (SQLException e)
        {
            throw new RuntimeException(e);
        }
        finally
        {
            DBUtil.close(connection,statement,resultSet);
        }
        if(flag)
        {
            HttpSession session = request.getSession();
            session.setAttribute("user",new User(username,password));
            if(loginSet != null && "1".equals(loginSet))
            {
                //存储登录名
                Cookie name = new Cookie("username",username);
                //存储密码
                Cookie LoginPassword = new Cookie("password",password);
                //生命周期都设为1小时,实验够了
                name.setMaxAge(60 * 60);
                LoginPassword.setMaxAge(60 * 60);
                //保存到浏览器中
                name.setPath(request.getContextPath());
                LoginPassword.setPath(request.getContextPath());
                //添加到响应中去
                response.addCookie(name);
                response.addCookie(LoginPassword);
            }
            response.sendRedirect(request.getContextPath() + "/dept/list");
        }
        else
        {
            response.sendRedirect(request.getContextPath() + "/Error.jsp");
        }
    }
}

部门相关操作

package com.bjpowernode.oa.action;

import com.bjpowernode.oa.utils.DBUtil;
import com.bjpowernode.oa.Pojo.Dept;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(urlPatterns = {"/dept/list","/dept/detail","/dept/delete","/dept/save","/dept/edit"})
public class DeptServlet extends HttpServlet
{
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        String servletPath = request.getServletPath();
        if("/dept/list".equals(servletPath))
        {
            doList(request,response);
        }
        else if("/dept/detail".equals(servletPath))
        {
            doDetail(request,response);
        }
        else if("/dept/delete".equals(servletPath))
        {
            doDel(request,response);
        }
        else if("/dept/save".equals(servletPath))
        {
            doSave(request,response);
        }
        else if("/dept/edit".equals(servletPath))
        {
            doModify(request,response);
        }
    }

    private void doModify(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        Integer deptno = Integer.parseInt(request.getParameter("deptno"));
        String dname = request.getParameter("dname");
        String loc = request.getParameter("loc");
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        int count = 0;
        try
        {
            connection = DBUtil.getConnection();
            connection.setAutoCommit(false);
            String sql = "update dept set dname = ?,loc = ? where deptno = ?";
            statement = connection.prepareStatement(sql);
            statement.setString(1,dname);
            statement.setString(2,loc);
            statement.setInt(3,deptno);
            count = statement.executeUpdate();
            connection.commit();
        }
        catch (SQLException e)
        {
            if (connection != null)
            {
                try
                {
                    connection.rollback();
                }
                catch (SQLException ex)
                {
                    throw new RuntimeException(ex);
                }
            }
            throw new RuntimeException(e);
        }
        finally
        {
            DBUtil.close(connection,statement,resultSet);
        }
        if(count == 1)
        {
            response.sendRedirect(request.getContextPath() +  "/dept/list");
        }
        else
        {
            response.sendRedirect(request.getContextPath() + "/Error.jsp");
        }
    }

    private void doSave(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        Integer deptno = Integer.parseInt(request.getParameter("deptno"));
        String dname = request.getParameter("dname");
        String loc = request.getParameter("loc");
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        int count = 0;
        try
        {
            connection = DBUtil.getConnection();
            connection.setAutoCommit(false);
            String sql = "insert into dept(deptno,dname,loc) values(?,?,?)";
            statement = connection.prepareStatement(sql);
            statement.setInt(1,deptno);
            statement.setString(2,dname);
            statement.setString(3,loc);
            count = statement.executeUpdate();
            connection.commit();

        }
        catch (SQLException e)
        {
            if (connection != null)
            {
                try
                {
                    connection.rollback();
                }
                catch (SQLException ex)
                {
                    throw new RuntimeException(ex);
                }
            }
            throw new RuntimeException(e);
        }
        finally
        {
            DBUtil.close(connection,statement,resultSet);
        }
        if(count == 1)
        {
            response.sendRedirect(request.getContextPath() +  "/dept/list");
        }
        else
        {
            response.sendRedirect(request.getContextPath() + "/Error.jsp");
        }
    }

    private void doDel(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        String deptno = request.getParameter("deptno");
        int count = 0;
        try
        {
            connection = DBUtil.getConnection();
            connection.setAutoCommit(false);
            String sql = "delete from dept where deptno = ?";
            statement = connection.prepareStatement(sql);
            statement.setString(1,deptno);
            count = statement.executeUpdate();
            connection.commit();
        }
        catch (SQLException e)
        {
            if (connection != null)
            {
                try
                {
                    connection.rollback();
                }
                catch (SQLException ex)
                {
                    throw new RuntimeException(ex);
                }
            }
            throw new RuntimeException(e);
        }
        finally
        {
            DBUtil.close(connection,statement,resultSet);
        }
        if(count == 1)
        {
            response.sendRedirect(request.getContextPath() + "/dept/list");
        }
        else
        {
            response.sendRedirect(request.getContextPath() + "/Error.jsp");
        }
    }

    private void doDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        String deptno = request.getParameter("deptno");
        try
        {
            connection = DBUtil.getConnection();
            String sql = "select * from dept where deptno = ?";
            statement = connection.prepareStatement(sql);
            statement.setString(1,deptno);
            resultSet = statement.executeQuery();
            if(resultSet.next())
            {
                String dname = resultSet.getString("dname");
                String loc = resultSet.getString("loc");
                Dept dept = new Dept(deptno,dname,loc);
                request.setAttribute("dept",dept);
            }
        }
        catch (SQLException e)
        {
            throw new RuntimeException(e);
        }
        finally
        {
            DBUtil.close(connection,statement,resultSet);
        }
        String flag = request.getParameter("f");
        if("d".equals(flag))
        {
            request.getRequestDispatcher("/detail.jsp").forward(request,response);
        }
        if("m".equals(flag))
        {
            request.getRequestDispatcher("/edit.jsp").forward(request,response);
        }
    }

    private void doList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        //连接数据库,查询所有部门信息
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        List<Dept> list = new ArrayList<Dept>();
        try
        {
            connection = DBUtil.getConnection();
            String sql = "select * from dept";
            statement = connection.prepareStatement(sql);
            resultSet = statement.executeQuery();
            while(resultSet.next())
            {
                String deptno = resultSet.getString("deptno");
                String dname = resultSet.getString("dname");
                String loc = resultSet.getString("loc");
                Dept dept = new Dept(deptno,dname,loc);
                list.add(dept);
            }
            request.setAttribute("depts",list);
            request.getRequestDispatcher("/list.jsp").forward(request,response);
        }
        catch (SQLException e)
        {
            throw new RuntimeException(e);
        }
        finally
        {
            DBUtil.close(connection,statement,resultSet);
        }
    }
}

https://www.xamrdz.com/lan/55k1967523.html

相关文章: