javaweb项目:部门管理系统

效果:

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

项目结构:

在这里插入图片描述

登录界面index.jsp:

<%@page contentType="text/html,charset=UTF-8"%>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8"/>
		<title>欢迎使用crud系统</title>
	</head>
	<body>
		<%--<a href="<%=request.getContextPath()%>/dept/list">查看部门列表</a>--%>
		<h1>用户登录</h1>
		<hr/>
		<form action="${pageContext.request.contextPath}/user/login" method="post">
			用户名<input type="text" name="username"/>
			密码<input type="password" name="password"/>
				<input type="checkbox" name="f" value="1"/>十天内免登录<br/>
				<input type="submit" name="login"/>
		</form>
	</body>
</html>

首页list.jsp:

<%@page contentType="text/html,charset=UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8"/>
		<title>部门列表页面</title>
	</head>
	<body>
		<h1 align="center">部门列表</h1>
		<hr/>
		<table border="1px" align="center" width="50%">
			<tr>
				<th>序号</th>
				<th>部门编号</th>
				<th>部门名称</th>
				<th>操作</th>
			</tr>
				<c:forEach items="${dept}" var="s" varStatus="ss">
				<tr>
					<td>${ss.count}</td>
					<td>${s.deptno}</td><%--通过类的get方法得到对象中封装的数据,放到td标签中--%>
					<td>${s.dname}</td>
					<td>
						<a href="${pageContext.request.contextPath}/dept/delete?deptno=${s.deptno}">删除</a>
						<a href="${pageContext.request.contextPath}/dept/edit?deptno=${s.deptno}">修改</a>
						<a href="${pageContext.request.contextPath}/dept/detail?deptno=${s.deptno}">详情</a>
					</td>
				</tr>
			</c:forEach>
		</table>
		<a href="${pageContext.request.contextPath}/add.jsp">新增</a>
        <a href="${pageContext.request.contextPath}/user/logout">[退出登录]</a>
	</body>
</html>

登陆失败界面error.jsp:

<%@ page contentType="text/html;charset=UTF-8"%>
<html>
<head>
    <title>登陆失败</title>
</head>
<body>
    <h1>用户名或密码错误</h1>
    <hr/>
    <a href="${pageContext.request.contextPath}/index.jsp">重新登陆</a>
</body>
</html>

详情页面detail.jsp:

<%@page contentType="text/html,charset=UTF-8"%>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8"/>
		<title>部门详情页面</title>
	</head>
	<body>
		<h1>部门详情</h1>
		<hr />
		部门编号:${dept[0].deptno}<br />
		部门名称:${dept[0].dname}<br />
		部门详情:${dept[0].loc}<br />
		<input type="button" value="后退" onclick="window.history.back()" />
	</body>
</html>

修改页面edit.jsp:

<%@page contentType="text/html,charset=UTF-8"%>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8"/>
		<title>修改部门页面</title>
	</head>
	<body>
		<h1 align="center">修改部门</h1>
		<hr />
		<form action="${pageContext.request.contextPath}/dept/editNow" method="post">
				部门编号<input type="text" name="deptno" value="${dept[0].deptno}" readonly="readonly"/><br />
				部门名称<input type="text" name="dname" value="${dept[0].dname}"/><br />
				部门位置<input type="text" name="loc" value="${dept[0].loc}"/><br />
				<input type="submit" value="提交" />
		</form>
	</body>
</html>

增加页面add.jsp:

<%@page contentType="text/html,charset=UTF-8"%>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8"/>
		<title>新增部门页面</title>
	</head>
	<body>
		<h1 align="center">新增部门</h1>
		<hr />
		<form action="${pageContext.request.contextPath}/dept/add" method="post">
				部门编号<input type="text" name="deptno" /><br />
				部门名称<input type="text" name="dname" /><br />
				部门位置<input type="text" name="loc" /><br />
				<input type="submit" value="保存" />
		</form>
	</body>
</html>

Dept.java bean类:

package bean;
//封装类
public class Dept {
    private int deptno;
    private String dname;
    private String loc;

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

    public Dept() {
    }

    public int getDeptno() {
        return deptno;
    }

    public void setDeptno(int 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;
    }
}

过滤器CheckFilter:

package filter;

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

import java.io.IOException;

//因为配置文件中配置的是/*,所以本站的所有URL在访问时都会被拦截,并执行该过滤器if的条件判断检查是否可以进入本站,
//放行条件:浏览器有session有信息(用户已登录)||访问/welcome||访问/error.jsp||访问/index.jsp||访问/dept/login
public class CheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession(false);//获取session,没有不会新建
        String servletPath = request.getServletPath();//获取请求路径
        if((session != null && session.getAttribute("username") != null)||"/welcome".equals(servletPath)||
                "/error.jsp".equals(servletPath)||"/index.jsp".equals(servletPath)||"/user/login".equals(servletPath)){//放行条件
                chain.doFilter(request,response);
        }else{//会话域没有信息,即登陆失败,重新登陆
            //作用:为了防止有些用户不登录而是直接输入URL就能跳转到相关网页的情况发生
            //强制用户必须先登录,且登陆成功,否则无法访问该webapp下的其他网页
            response.sendRedirect(request.getContextPath()+"/welcome");//注意执行该语句代表不放行,但是执行该语句跳转到/welcome时也会执行该过滤器
        }
    }
}

DButil数据库工具类:

package mypackage;

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

public class DButil {
    private static ResourceBundle bundle = ResourceBundle.getBundle("resources.jdbc");
    static {
        try {
            Class.forName(bundle.getString("driver"));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接对象
     * @return 连接对象
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(bundle.getString("url"),bundle.getString("username"),bundle.getString("password"));
    }

    /**
     * 释放资源
     * @param connection
     * @param preparedstatement
     * @param resultSet
     */
    public static void close(Connection connection,PreparedStatement preparedstatement,ResultSet resultSet){
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (preparedstatement != null) {
            try {
                preparedstatement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}

WelcomeServlet:

package mypackage;

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;
//用于用户刚打开浏览器想访问本webapp,检查cookie
//判断用户浏览器内存中是否存有cookie,cookie中的用户名密码是否正确,正确跳/dept/list,错误跳error.jsp,未存cookie跳登录页面index.jsp登录
@WebServlet("/welcome")
public class WelcomeServlet 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) {//判断浏览器的请求行的cookie字段是否有信息
            for (Cookie cookie : cookies) {
                if ("username".equals(cookie.getName())){//获取cookie中的用户名
                    username = cookie.getValue();
                }
                if("password".equals(cookie.getName())){//获取cookie中的密码
                    password = cookie.getValue();
                }
            }
        }
        if(username!=null && password!=null){//用户之前登陆成功且设置了免登录,浏览器保存了cookie
            //验证用户名密码是否正确:为了防止用户点击免登录后改密码
            Connection connection = null;
            PreparedStatement preparedStatement = null;
            ResultSet resultSet = null;
            boolean flag = false;
            try {
                connection = DButil.getConnection();
                preparedStatement = connection.prepareStatement("select username,password from t_user where username=? and password=?");
                preparedStatement.setString(1, username);
                preparedStatement.setString(2, password);
                resultSet = preparedStatement.executeQuery();
                if (resultSet.next()) {//cookie中的用户名和密码正确
                    flag = true;
                    //获取session,没有则新建
                    HttpSession session = request.getSession();
                    //将用户登录成功的信息存到会话域
                    session.setAttribute("username",username);
                    //重定向,登陆成功后转到list连接数据库获取信息,然后转到list.jsp页面展示
                    response.sendRedirect(request.getContextPath()+"/dept/list");
                }
                if (flag == false) {//cookie中的用户名和密码错误
                    //重定向,密码错误后转到失败页面
                    response.sendRedirect(request.getContextPath()+"/error.jsp");
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            } finally {
                DButil.close(connection, preparedStatement, resultSet);
            }
        }else{//用户之前没有登录过,表示该用户第一次访问网站
            //重定向,跳转到登录页面
            response.sendRedirect(request.getContextPath()+"/index.jsp");
        }

    }
}

LoginAndOutServlet:

package mypackage;

import com.mysql.cj.Session;
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;

/**
 * list.jsp改成用户登录界面,为了防止非法用户访问数据库
 */
@WebServlet({"/user/login","/user/logout"})
public class LoginAndOutServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String servletPath = request.getServletPath();
        if("/user/login".equals(servletPath)){
            doLogin(request,response);
        }else if("/user/logout".equals(servletPath)){
            doLogout(request,response);
        }
    }

    /**
     * 登录
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void doLogin(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        boolean flag = false;
        try {
            connection = DButil.getConnection();
            preparedStatement = connection.prepareStatement("select username,password from t_user where username=?");
            preparedStatement.setString(1, request.getParameter("username"));
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                if (request.getParameter("password").equals(resultSet.getString("password"))) {
                    flag = true;
                    if(("1").equals(request.getParameter("f"))){//如果登录成功且用户选择了十天内免登录
                        Cookie cookie1 = new Cookie("username",request.getParameter("username"));//创建cookie
                        Cookie cookie2 = new Cookie("password",request.getParameter("password"));
                        cookie1.setMaxAge(60*60*24*10);//设置cookie失效时间
                        cookie2.setMaxAge(60*60*24*10);
                        cookie1.setPath(request.getContextPath());//设置响应路径
                        cookie2.setPath(request.getContextPath());
                        response.addCookie(cookie1);//cookie通过HTTP响应报文传给浏览器保存
                        response.addCookie(cookie2);
                    }
                    //获取session,没有则新建
                    HttpSession session = request.getSession();
                    //将用户登录成功的信息存到会话域
                    session.setAttribute("username",request.getParameter("username"));
                    //重定向,登陆成功后转到list连接数据库获取信息,然后转到list.jsp页面展示
                    response.sendRedirect(request.getContextPath()+"/dept/list");
                }
            }
            if (flag == false) {
                //重定向,登陆失败后转到失败页面
                response.sendRedirect(request.getContextPath()+"/error.jsp");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DButil.close(connection, preparedStatement, resultSet);
        }
    }

    /**
     * 退出登录,销毁session
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void doLogout(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
        HttpSession session = request.getSession(false);
        if (session != null){
            session.invalidate();//手动销毁session
            //手动销毁cookie
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    cookie.setPath(request.getContextPath());//要删除根路径下的cookie,只删除子路径下的cookie没用
                    cookie.setMaxAge(0);
                    response.addCookie(cookie);
                }
            }
            //重定向到登录页面
            response.sendRedirect(request.getContextPath());
        }
    }
}

CrudsServlet:

package mypackage;
/**
 * 数据库增删改查类
 * 实现思路:首先根据web客户端传过来的URI执行service方法,选择执行哪个servlet。
 * (1)查看所有部门信息实现思路:index.jsp主页点击后会传一个/dept/list的URI,所哟会执行下面的doList方法,目的是为了从数据库获取部门信息,所有部门信息封装到
 *                      请求域中传给展示页面list.jsp,list.jsp获取到请求域中的信息,输出到网页上。
 * (2)查看某个部门详细信息思路:点击list.jsp页面的详细信息超链接,web网页(客户端)会发送一个/dept/detail的URI,执行doDetail方法目的是为了从数据库得到详细信息,
 *                      doDetail方法是怎么知道用户点击的是哪个部门?换句话怎么知道用户查看的是哪个部门的详细信息?是因为我们在get方法的URL的尾部加入了?key=value
 *                      添加了一个标记,这个标记表示了用户点击的是哪个部门,然后doDetail方法通过调用方法能获得这个标记,从而能知道该从数据库查询哪个部门的信息。
 *                      将信息封装到请求域中传给展示页面detail.jsp,list.jsp获取到请求域中的信息,输出到网页上。
 * (3)添加部门实现思路:点击list.jsp页面的添加部门超链接,会跳转到add.jsp网页,用户输入信息后点击提交按钮,web网页(客户端)会发送一个/dept/add的URI,执行doAdds方法目的是为了向数据库写用户输入的信息信息,
 *                doAdds方法是怎么知道用户输入的信息的?是因为post方法的内容区保存了一个个key=value键值对,用户在文本框中输入的信息被封装成了键值对,
 *                其中key是文本框的name属性的值,value是用户在文本框输入的信息,所以doAdds方法通过调用方法能得到这些信息,从而将这些信息通过sql语句保存到数据库。
 *                然后会重定向到/dept/list,目的是为了更新数据,然后跳转到list.jsp,查看所有部门信息。
 * (4)删除部门原理类似(2)
 * (5)重新编辑部门信息原理是:分两步,先从数据库中查找该部门的信息,类似(2),然后修改部门信息,类似(3).
 * 总结:六个方法都是为了与数据库交互,在数据库上增删改查。JSP是为了展示页面
 */

import bean.Dept;
import jakarta.servlet.RequestDispatcher;
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 jakarta.servlet.http.HttpSession;

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({"/dept/list","/dept/edit","/dept/editNow","/dept/detail","/dept/delete","/dept/add"})
public class CrudsServlet extends HttpServlet {
    @Override
    /**
     * 判断传过来的路径,根据路径转到对应方法
     * 重写的是service方法,现在只需要写一个类,解决了类爆炸问题
     */
    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/edit".equals(servletPath)){
            doEdit(request,response);
        }else if("/dept/editNow".equals(servletPath)){
            doEditNow(request,response);
        }else if("/dept/detail".equals(servletPath)){
            doDetail(request,response);
        }else if("/dept/delete".equals(servletPath)){
            doDeletes(request,response);
        }else if("/dept/add".equals(servletPath)){
            doAdds(request,response);
        }
    }

    /**
     * 用户在add网页上输入信息后,点击提交重定向到list页面,添加成功,展示数据库信息
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void doAdds(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            //获取连接
            connection = DButil.getConnection();
            //获取数据库操作对象,预编译
            preparedStatement = connection.prepareStatement("insert into dept values(?,?,?)");
            //给?传参数
            //request.getParameter方法得到网页上用户输入的参数,因为用户输入的参数是key=value集合,其中key是输入文本框的name属性,value是用户输入的参数
            preparedStatement.setString(1,request.getParameter("deptno"));
            preparedStatement.setString(2,request.getParameter("dname"));
            preparedStatement.setString(3,request.getParameter("loc"));
            //执行语句
            int result = preparedStatement.executeUpdate();
            if (result == 1){
                //重定向,用户点击提交按钮后回到list页面
                response.sendRedirect(request.getContextPath()+"/dept/list");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            //关闭资源
            DButil.close(connection, preparedStatement, null);
        }
    }

    /**
     * 点击删除按钮,点击提交重定向到list页面,删除成功,展示数据库信息
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void doDeletes(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            //获取连接
            connection = DButil.getConnection();
            //获取数据库操作对象,预编译
            preparedStatement = connection.prepareStatement("delete from dept where deptno=?");
            //给?传参数
            //request.getParameter方法得到网页上用户点击的是哪一行数据,因为我们在路径中加入了key=value集合,其中key是输入文本框的name属性,value是点击的行标记
            preparedStatement.setString(1,request.getParameter("deptno"));
            //执行语句
            int result = preparedStatement.executeUpdate();
            if (result == 1){
                //重定向,用户点击提交按钮后回到list页面,目的是更新页面
                response.sendRedirect(request.getContextPath()+"/dept/list");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            //关闭资源
            DButil.close(connection, preparedStatement, null);
        }
    }

    /**
     * 点击详情按钮,可查看详情,按返回按钮可回到list页面
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void doDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        List<Dept> list = new ArrayList<>();
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        //request.getParameter方法得到网页上用户点击的是哪一行数据,因为我们在路径中加入了key=value集合,其中key是输入文本框的name属性,value是点击的行标记
        String bdeptno = request.getParameter("deptno");
        try {
            //获取连接
            connection = DButil.getConnection();
            //获取数据库操作对象,预编译
            preparedStatement = connection.prepareStatement("select * from dept where deptno=?");
            //给?传参数
            preparedStatement.setString(1,bdeptno);
            //执行语句,获得结果集
            resultSet = preparedStatement.executeQuery();
            //注意一定要有if
            if(resultSet.next()) {
                //得到结果集中的数据
                int deptno = resultSet.getInt("deptno");
                String dname = resultSet.getString("dname");
                String loc = resultSet.getString("loc");
                //结果集封装到类中
                Dept dept = new Dept(deptno, dname, loc);
                //将类添加到集合中
                list.add(dept);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            //释放资源
            DButil.close(connection,preparedStatement,resultSet);
        }
        //使用请求域共享数据,将list集合添加到请求域中,并跳转到展示页面detail.jsp
        request.setAttribute("dept",list);
        RequestDispatcher dispatcher = request.getRequestDispatcher("/detail.jsp");
        dispatcher.forward(request,response);
    }

    /**
     * 用户输入修改信息,点击提交后修改成功,返回预览页list
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void doEditNow(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            //获取连接
            connection = DButil.getConnection();
            //获取数据库操作对象,预编译
            preparedStatement = connection.prepareStatement("update dept set dname=? ,loc=? where deptno=?");
            //给?传参数
            //request.getParameter方法得到网页上用户输入的参数,因为用户输入的参数是key=value集合,其中key是输入文本框的name属性,value是用户输入的参数
            preparedStatement.setString(1,request.getParameter("dname"));
            preparedStatement.setString(2,request.getParameter("loc"));
            preparedStatement.setString(3,request.getParameter("deptno"));
            //执行语句
            int result = preparedStatement.executeUpdate();
            if (result == 1){
                //重定向到list,再由list转发到list界面
                response.sendRedirect(request.getContextPath()+"/dept/list");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            //释放资源
            DButil.close(connection, preparedStatement, null);
        }
    }

    /**
     * 连接数据库,将信息在edit界面显示出来
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void doEdit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Dept> list = new ArrayList<>();
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        //request.getParameter方法得到网页上用户点击的是哪一行数据,因为我们在路径中加入了key=value集合,其中key是输入文本框的name属性,value是点击的行标记
        String bdeptno = request.getParameter("deptno");
        try {
            //获取连接
            connection = DButil.getConnection();
            //获取数据库操作对象,预编译
            preparedStatement = connection.prepareStatement("select * from dept where deptno=?");
            //给?传参数
            preparedStatement.setString(1,bdeptno);
            //执行语句,获得结果集
            resultSet = preparedStatement.executeQuery();
            //注意一定要加if
            if(resultSet.next()) {
                //获取数据库结果集中的数据
                int deptno = resultSet.getInt("deptno");
                String dname = resultSet.getString("dname");
                String loc = resultSet.getString("loc");
                //数据封装到类
                Dept dept = new Dept(deptno, dname, loc);
                //对象加到集合中
                list.add(dept);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            //释放资源
            DButil.close(connection,preparedStatement,resultSet);
        }
        //使用请求域共享数据,将list集合添加到请求域中,并跳转到展示页面edit.jsp,用户可以编辑数据
        request.setAttribute("dept",list);
        RequestDispatcher dispatcher = request.getRequestDispatcher("/edit.jsp");
        dispatcher.forward(request,response);
    }

    /**
     * 连接数据库,查询所有部门信息,然后跳转到JSP做页面展示
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void doList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException  {
        List<Dept> list = new ArrayList<>();
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            //获取连接
            connection = DButil.getConnection();
            //获取数据库操作对象,预编译
            preparedStatement = connection.prepareStatement("select * from dept");
            //执行sql,获得结果集
            resultSet = preparedStatement.executeQuery();
            //遍历数据库中的结果集
            while(resultSet.next()){
                int deptno = resultSet.getInt("deptno");
                String dname = resultSet.getString("dname");
                String loc = resultSet.getString("loc");
                //每个结果封装到类中
                Dept dept = new Dept(deptno,dname,loc);
                //所有封装后的类添加到集合中
                list.add(dept);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            //释放资源
            DButil.close(connection,preparedStatement,resultSet);
        }
        //使用请求域共享数据,将list集合添加到请求域中,并跳转到展示页面list.jsp
        request.setAttribute("dept",list);
        RequestDispatcher dispatcher = request.getRequestDispatcher("/list.jsp");
        dispatcher.forward(request,response);
    }
}

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
        <!--设置欢迎页主页-->
        <welcome-file-list>
            <welcome-file>welcome</welcome-file>
        </welcome-file-list>
        <!--过滤器-->
        <filter>
            <filter-name>logfilter</filter-name>
            <filter-class>filter.CheckFilter</filter-class>
        </filter>
        <filter-mapping>
            <filter-name>logfilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
</web-app>
  • 4
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

姓蔡小朋友

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值