Javaweb teaching system project practical student management module


mission target

  • Business goal:
    Realize the addition, deletion, modification and checking of student information in the student management module

  • Skill objectives:
    Consolidate and practice the knowledge system of JAVAWEB, MYSQL, HTML, and JAVASE through projects


Involving knowledge points

1. SQL language and basic operations

2. JDBC (Java Database Connection)

3. Use of custom tool classes and properties configuration files

4. JDBC connection pool

5. Enumeration class definition

6. Servlet processes requests ( Servlet working principle , Servlet request and response )

7. JSTL tag library + EL expression

8、JSP

9. AJAX learning

10、HTMLCSS


Task process

  1. Familiar with project requirements and project structure
  2. Create a database according to your needs
  3. Tips for implementing user login and logout
    : Judgment of user permissions, user operations are not allowed to be accessed without login.
  4. Tips for implementing addition, deletion, modification and check of student information
    : non-repetitive verification of student ID number

Ideas and code implementation

☆Front-end page creation

Create a new html page according to your needs
Insert image description here

Login interface login.jsp

Insert image description here

System main interface index.jsp after login

Insert image description here

student management module

Insert image description here


☆Database creation

Create a database and create the grade information table grage , student information table student , and login user information table users
Insert image description here

grade

Insert image description here

student

Insert image description here

users

Insert image description here


☆Backend

1. Toolkit utils

Create a utils package, create a new class DBUtils, and create a new configuration file db.properties

properties configuration file

Use ResourceBundle to access local resources and read the values ​​we need from them

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
username=root
password=123456

DBUtils

JDBC tool class encapsulates methods for operating sql, so static methods are recommended.

  • Variable definitions
	//定义需要的工具类对象(变量定义)
    protected static Connection connection = null;
    protected static PreparedStatement pps = null;//后续都是用预状态通道来实现
    protected static ResultSet rs = null;//结果集
    protected static int count = 0;//受影响的行数
    //登录的用户名和密码
    private static String username;
    private static String password;
    private static String url;
    private static String driverName;
    //Druid连接池
    private static DruidDataSource druidDataSource = new DruidDataSource();
  • Load driver
	//加载驱动
    static {
    
    
        //Druid
        ResourceBundle bundle = ResourceBundle.getBundle("db");//参数只写属性文件名,不需要写后缀
        //加载属性文件
        driverName = bundle.getString("driver");
        url = bundle.getString("url");
        username = bundle.getString("username");
        password = bundle.getString("password");

        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        druidDataSource.setUrl(url);
        druidDataSource.setDriverClassName(driverName);
    }
  • get link
    protected static Connection getConnection() {
    
    
        try {
    
    
            connection = druidDataSource.getConnection();
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
        return connection;
    }
  • Get the pre-state channel and bind parameters
	//得到预状态通道
    protected static PreparedStatement getPps(String sql) {
    
    
        try {
    
    
            getConnection();
            pps = connection.prepareStatement(sql);
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
        return pps;
    }
    
    //绑定参数,给占位符赋值,list中保存的是给占位符所赋的值
    private static void setParams(List list) {
    
    
        try {
    
    
            if (list != null && list.size() > 0) {
    
    //集合中有内容
                for (int i = 0; i < list.size(); i++) {
    
    
                    pps.setObject(i + 1, list.get(i));//赋值,位置从1开始所以为i+1
                }
            }
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
    }
  • addition, deletion, modification
    protected static int update(String sql, List list) {
    
    
        try {
    
    
            getPps(sql);//得到预状态通道
            setParams(list);//绑定参数
            count = pps.executeUpdate();//pps.executeUpdate()执行sql语句,返回受影响的行数
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
        return count;//返回受影响的行数
    }
  • data query
	protected static ResultSet query(String sql, List list) {
    
    
        try {
    
    
            getPps(sql);//得到预状态通道
            setParams(list);//绑定参数
            rs = pps.executeQuery();//pps.executeUpdate()执行sql语句,返回结果集
            return rs;//返回结果集
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
        return null;
    }
  • Close resource
    protected static void closeAll() {
    
    
        try {
    
    
            if (rs != null) {
    
    
                rs.close();
            }
            if (pps != null) {
    
    
                pps.close();
            }
            if (connection != null) {
    
    
                connection.close();
            }
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
    }

2. Definition of entity classes and creation of bean packages

Create the corresponding class based on the created sql.
Class name = table name, attribute name = column name.

Grade

  • Define properties
	private Integer gradeId;
    private String gradeName;
    //一对多关系
    private List<Student> studentList;
  • Setting and getting values ​​with setters and getters
    public Integer getGradeId() {
    
    
        return gradeId;
    }

    public void setGradeId(Integer gradeId) {
    
    
        this.gradeId = gradeId;
    }

    public String getGradeName() {
    
    
        return gradeName;
    }

    public void setGradeName(String gradeName) {
    
    
        this.gradeName = gradeName;
    }

    public List<Student> getStudentList() {
    
    
        return studentList;
    }

    public void setStudentList(List<Student> studentList) {
    
    
        this.studentList = studentList;
    }

Student

  • Define properties
	private Integer stuId;
    private String stuName;
    private String stuNo;
    private Integer sex;
    private String phone;
    private String email;
    private String registered;
    private String address;
    private String profession;
    private String idNumber;
    private String politics;
    private Date regDate;
    private Integer state;
    private String introduction;
    private Integer gId;

    //多对一
    private Grade grade;
  • Setting and getting values ​​with setters and getters
	public Integer getStuId() {
    
    
        return stuId;
    }

    public void setStuId(Integer stuId) {
    
    
        this.stuId = stuId;
    }

    public String getStuName() {
    
    
        return stuName;
    }

    public void setStuName(String stuName) {
    
    
        this.stuName = stuName;
    }

    public String getStuNo() {
    
    
        return stuNo;
    }

    public void setStuNo(String stuNo) {
    
    
        this.stuNo = stuNo;
    }

    public Integer getSex() {
    
    
        return sex;
    }

    public void setSex(Integer sex) {
    
    
        this.sex = sex;
    }

    public String getPhone() {
    
    
        return phone;
    }

    public void setPhone(String phone) {
    
    
        this.phone = phone;
    }

    public String getEmail() {
    
    
        return email;
    }

    public void setEmail(String email) {
    
    
        this.email = email;
    }

    public String getRegistered() {
    
    
        return registered;
    }

    public void setRegistered(String registered) {
    
    
        this.registered = registered;
    }

    public String getAddress() {
    
    
        return address;
    }

    public void setAddress(String address) {
    
    
        this.address = address;
    }

    public String getProfession() {
    
    
        return profession;
    }

    public void setProfession(String profession) {
    
    
        this.profession = profession;
    }

    public String getIdNumber() {
    
    
        return idNumber;
    }

    public void setIdNumber(String idNumber) {
    
    
        this.idNumber = idNumber;
    }

    public String getPolitics() {
    
    
        return politics;
    }

    public void setPolitics(String politics) {
    
    
        this.politics = politics;
    }

    public Date getRegDate() {
    
    
        return regDate;
    }

    public void setRegDate(Date regDate) {
    
    
        this.regDate = regDate;
    }

    public Integer getState() {
    
    
        return state;
    }

    public void setState(Integer state) {
    
    
        this.state = state;
    }

    public String getIntroduction() {
    
    
        return introduction;
    }

    public void setIntroduction(String introduction) {
    
    
        this.introduction = introduction;
    }

    public Integer getgId() {
    
    
        return gId;
    }

    public void setgId(Integer gId) {
    
    
        this.gId = gId;
    }

    public Grade getGrade() {
    
    
        return grade;
    }

    public void setGrade(Grade grade) {
    
    
        this.grade = grade;
    }

Users

  • Define properties
    private Integer userId;
    private String loginName;
    private String password;
    private String realName;
  • Setting and getting values ​​with setters and getters
    public Integer getUserId() {
    
    
        return userId;
    }

    public void setUserId(Integer userId) {
    
    
        this.userId = userId;
    }

    public String getLoginName() {
    
    
        return loginName;
    }

    public void setLoginName(String loginName) {
    
    
        this.loginName = loginName;
    }

    public String getPassword() {
    
    
        return password;
    }

    public void setPassword(String password) {
    
    
        this.password = password;
    }

    public String getRealName() {
    
    
        return realName;
    }

    public void setRealName(String realName) {
    
    
        this.realName = realName;
    }

3. Implementation of module functions

Various operations of student management are defined in the service package
Insert image description here

The dao layer defines the specific implementation of the service layer operation
Insert image description here
and defines the servlet in the we package.
Insert image description here


※ User

Implement user login and exit

service

UsersService interface

public interface UsersService {
    
    
    /**
     * 登录方法
     */
    public Users login(String username,String password);
}

UsersService interface implementation class UsersServiceImpl

public class UsersServiceImpl implements UsersService {
    
    
    /**
     * 创建dao层对象
     */
    private UsersDao usersDao = new UsersDaoImpl();

    /**
     * 登录方法
     */
    @Override
    public Users login(String username, String password) {
    
    
        return usersDao.login(username, password);
    }
}
dao

UsersDao interface

public interface UsersDao {
    
    
    /**
     * 登录方法
     */
    public Users login(String username, String password);
}

UsersDao interface implementation class UsersDaoImpl

Since you need to connect to the database for operations, you need to inherit the DBUtils method

public class UsersDaoImpl extends DBUtils implements UsersDao {
    
    
    /**
     * 登录方法
     */
    @Override
    public Users login(String username, String password) {
    
    
        Users users = null;
        try {
    
    
            String sql = "select * from users where loginname = ? and password = ?";
            ArrayList arrayList = new ArrayList();
            arrayList.add(username);
            arrayList.add(password);
            resultSet = query(sql, arrayList);//查询之后返回结果集
            //包装结果集数据
            users = null;
            if(resultSet == null){
    
    
                return null;
            }
            while (resultSet.next()){
    
    
                users = new Users();
                users.setLoginName(username);
                users.setRealName(resultSet.getString("realname"));
                users.setUserId(resultSet.getInt("userid"));
            }
        } catch (SQLException throwables) {
    
    
            throwables.printStackTrace();
        } finally {
    
    
            closeAll();
        }
        return users;
    }
}

servlet

In the LoginServlet class
login.jsp page, enter username and password and click the login button to submit the form.action=“login” method=“post”

@WebServlet(urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    
    
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        //1.接收参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //2.调取service
        UsersService usersService = new UsersServiceImpl();
        Users users = usersService.login(username, password);
        //3.跳转页面
        if(users == null){
    
    
            //以弹窗方式提示用户,登录失败
            resp.setContentType("text/html;charset=utf-8");//防止返回数据乱码
            PrintWriter writer = resp.getWriter();
            writer.println("<script>location.href='login.jsp';alert('用户名或密码不正确');</script>");
        }else{
    
    
            //保存用户信息,重定向跳转到主页面
            //session,整个会话期间
            req.getSession().setAttribute("u1",users);
            resp.sendRedirect("index.jsp");
        }
    }
}

※ Grade

When performing data operations on students, it is necessary to obtain a grade list

service
public interface GradeService {
    
    
    /**
     * 查询年级列表
     */
    public List<Grade> getList();
}
public class GradeServiceImpl implements GradeService {
    
    
    private GradeDao dao = new GradeDaoImpl();

    @Override
    public List<Grade> getList() {
    
    
        return dao.getList();
    }
}
dao
public interface GradeDao{
    
    
    /**
     * 查询年级列表
     */
    public List<Grade> getList();
}
public class GradeDaoImpl extends DBUtils implements GradeDao {
    
    
    @Override
    public List<Grade> getList() {
    
    
        List gs = new ArrayList();
        try {
    
    
            String sql = "select * from grade";
            resultSet = query(sql, null);
            while (resultSet.next()){
    
    
                Grade grade = new Grade();
                grade.setGradeId(resultSet.getInt("gradeid"));
                grade.setGradeName(resultSet.getString("gradename"));
                gs.add(grade);
            }
        } catch (SQLException throwables) {
    
    
            throwables.printStackTrace();
        } finally {
    
    
            closeAll();
        }
        return gs;
    }
}
servlet
@WebServlet(urlPatterns = "/Educational/student/getGradeList")
public class GradeListServlet extends HttpServlet {
    
    
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        //1接收参数
        //2调取service方法
        //3跳转页面
        //查询年级列表的方法
        GradeService service = new GradeServiceImpl();
        List<Grade> list = service.getList();
        req.setAttribute("glist",list);
        req.getRequestDispatcher("add.jsp").forward(req,resp);
    }
}

※Students

Use the same service, dao, and servlet to write different methods for addition, deletion, modification, and query.

StudentServlet class

The page sends different method requests for additions, deletions, modifications and queries, and different methods are defined in the servlet for processing respectively.

@WebServlet(urlPatterns = "/Educational/student/studentServlet")
public class StudentServlet extends HttpServlet {
    
    
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        String method = req.getParameter("method");
        if("insert".equals(method)){
    
    
            insert(req, resp);
        }else if("update".equals(method)){
    
    
            update(req, resp);
        }else if("findbyid".equals(method)){
    
    
            findbyid(req, resp);
        }else if("delete".equals(method)){
    
    
            deleteStu(req, resp);
        }else {
    
    
            findlist(req, resp);
        }
    }
}    

List display (paged display)

/Educational/student/studentServlet

service
    /**
     * 获取所有学生信息列表
     * pageIndex  页码值
     * pageSize  每页显示的条数
     */
    public List<Student> getStudents(String name,String stuno,int sex,int pageIndex,int pageSize);
    @Override
    public List<Student> getStudents(String name,String stuno,int sex,int pageIndex,int pageSize) {
    
    
        return dao.getStudents(name, stuno, sex,pageIndex,pageSize);
    }
dao
    /**
     * 获取所有学生信息列表
     */
    public List<Student> getStudents(String name,String stuno,int sex,int pageIndex,int pageSize);
    @Override
    public List<Student> getStudents(String name,String stuno,int sex,int pageIndex,int pageSize) {
    
    
        List list = new ArrayList<Student>();
        List params = new ArrayList();
        try {
    
    
            StringBuffer sqlbuf = new StringBuffer("select * from student where 1=1 and state!=4 ");//单表查询
            if(name != null && name.length()>0){
    
    
                sqlbuf.append(" and stuname like ? ");
                params.add("%"+name+"%");//模糊查找
            }
            if(stuno != null && stuno.length()>0){
    
    
                sqlbuf.append(" and stuno=? ");
                params.add(stuno);
            }
            if(sex != -1){
    
    
                sqlbuf.append(" and sex=? ");
                params.add(sex);
            }
            /**
             * 分页条件
             * 第一个问号,开始位置( 第一页,每一页五条,则limit 0,5 )
             * limit (pageIndex-1)*pageSize,pageSize
             */
            sqlbuf.append(" limit ?,? ");
            params.add((pageIndex-1)*pageSize);
            params.add(pageSize);


            resultSet = query(sqlbuf.toString(),params);
            //resultSet = query(sql, null);//无参数,null
            while (resultSet.next()){
    
    
                Student student = new Student();
                student.setStuId(resultSet.getInt("stuid"));
                student.setStuNo(resultSet.getString("stuno"));
                student.setStuName(resultSet.getString("stuname"));
                student.setSex(resultSet.getInt("sex"));
                student.setPhone(resultSet.getString("phone"));
                student.setProfession(resultSet.getString("profession"));
                student.setRegDate(resultSet.getDate("regdate"));
                //建议补全所有的列
                list.add(student);//添加数据
            }
        } catch (SQLException throwables) {
    
    
            throwables.printStackTrace();
        } finally {
    
    
            closeAll();
        }
        return list;
    }
servlet
	/**
     * 查询列表
     */
    protected void findlist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        //1获取参数(两部分,第一部分:模糊从查找的条件  第二部分:分页数据)

        //1.1模糊查找条件
        String stuname = req.getParameter("stuname");
        String stuno = req.getParameter("stuno");
        String sex = req.getParameter("sex");

        //1.2分页数据(limit 开始位置,显示条数)
        //页码值
        String pageIndex = req.getParameter("pageIndex");//当前页码值
        //如果页面没有传入pageIndex的值,则默认查询第一页
        int index = pageIndex==null?1:Integer.parseInt(pageIndex);

        //2调取service方法
        PageUtil pageUtil = new PageUtil();
        StudentService service = new StudentServiceImpl();
        int usex = (sex==null||sex.length()==0?-1:Integer.parseInt(sex));
        List<Student> students =
                service.getStudents(stuname,stuno,usex,index,pageUtil.getPageSize());//得到学生集合,需要跳转到前台
        /**
         * 获取总页数
         * 总页数=总条数%每页显示的条数>0?总条数/每页显示的条数+1:总条数/每页显示的条数
         */
        int total = service.total(stuname, stuno, usex);//总条数
        pageUtil.setTotal(total);

        //3跳转页面
        //如果后台想给前台传数据,一定要在后台存值
        //req.setAttribute("stulist",students);
        pageUtil.setDataList(students);
        pageUtil.setPageIndex(index);


        //点击查询之后,在列出查询信息使保留上面的搜索内容(存储模糊查找的条件)
        req.setAttribute("stuname",stuname);
        req.setAttribute("stuno",stuno);
        req.setAttribute("sex",sex);

        //存储页码值
        req.setAttribute("p1",pageUtil);
//        req.setAttribute("index",index);
//        //存储分页数据
//        req.setAttribute("size",5);
//        req.setAttribute("total",total);//总条数
//        req.setAttribute("totalpages",totalPages);//总页数

        //list前面如果加/表示从根目录下进行寻找
        req.getRequestDispatcher("list.jsp").forward(req,resp);//转发的方式,跳转到list.jsp
    }

Fuzzy query implementation (based on student list display)
service
    /**
     * 获得总条数
     * 基于模糊查询
     */
    public int total(String name,String stuno,int sex);
    @Override
    public int total(String name, String stuno, int sex) {
    
    
        return dao.total(name, stuno, sex);
    }
dao
    /**
     * 获得总条数
     * 基于模糊查询
     */
    public int total(String name,String stuno,int sex);
    @Override
    public int total(String name, String stuno, int sex) {
    
    
        int total = 0;
        try {
    
    
            List params = new ArrayList();
            StringBuffer sqlbuf = new StringBuffer("select count(*) from student where 1=1 and state!=4 ");//单表查询
            if(name != null && name.length()>0){
    
    
                sqlbuf.append(" and stuname like ? ");
                params.add("%"+name+"%");//模糊查找
            }
            if(stuno != null && stuno.length()>0){
    
    
                sqlbuf.append(" and stuno=? ");
                params.add(stuno);
            }
            if(sex != -1){
    
    
                sqlbuf.append(" and sex=? ");
                params.add(sex);
            }
            resultSet = query(sqlbuf.toString(), params);
            while (resultSet.next()){
    
    
                total=resultSet.getInt(1);//取出结果集第一列的值,即count
            }
        } catch (SQLException throwables) {
    
    
            throwables.printStackTrace();
        } finally {
    
    
            closeAll();
        }
        return total;
    }
servlet

The essence of fuzzy query is a special case of student list display, that is, student list display under certain conditions


Add new students

href="/Educational/student/getGradeList"

First get the student's grade list information, and then jump to add.jsp to input the information.

service
    /**
     * 新增学生
     */
    public int insertStu(Student student);
    @Override
    public int insertStu(Student student) {
    
    
        return dao.insertStu(student);
    }
dao
    /**
     * 新增学生
     */
    public int insertStu(Student student);
    @Override
    public int insertStu(Student student) {
    
    
        int i = 0; 
        if(existId(student.getStuNo(),student.getStuName()) == 1){
    
    
            System.out.println("该学号已经存在!");
            return -1;
        }
        try {
    
    
            String sql = "insert into student values(null,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
            List params = new ArrayList();
            params.add(student.getStuName());
            params.add(student.getStuNo());
            params.add(student.getSex());
            params.add(student.getPhone());
            params.add(student.getEmail());
            params.add(student.getRegistered());
            params.add(student.getAddress());
            params.add(student.getProfession());
            params.add(student.getIdNumber());
            params.add(student.getPolitics());
            params.add(new Date());
            params.add(StudentEnum.READING.type);//1表示在读 2表示休学 3表示退学 4表示删除
            params.add(student.getIntroduction());
            params.add(student.getgId());
            i = update(sql, params);//i表示受影响的行数
        } catch (Exception e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            closeAll();
        }
        return i;
    }



    /**
     *根据学号判断该学生是否存在
     */
    public int existId(String stuno,String stuName){
    
     
        int f = -1;
        System.out.println("判断学号是否存在");
        Student student = findByName(stuName); 
        if(stuno.equals(student.getStuNo())){
    
    //虽然学号已存在,但是是自己原来的学号
            return -1;
        }
        try {
    
    
            String sql = "select * from student where stuno = ?";
            List params = new ArrayList();
            params.add(stuno);
            resultSet = query(sql, params);
            if(resultSet.next()) {
    
    
                f = 1;
            }
        } catch (SQLException throwables) {
    
    
            throwables.printStackTrace();
        } finally {
    
    
            closeAll();
        }
        return f;
    }


    /**
     * 通过姓名查找学生是否存在
     */
    public Student findByName(String stuname) {
    
    
        Student student = new Student();
        try {
    
    
            String sql = "select * from student where stuname = ?";
            List params = new ArrayList();
            params.add(stuname);
            resultSet = query(sql, params);
            while (resultSet.next()){
    
    
                student.setStuId(resultSet.getInt("stuid"));
                student.setStuNo(resultSet.getString("stuno"));
                student.setStuName(resultSet.getString("stuname"));
                student.setSex(resultSet.getInt("sex"));
                student.setPhone(resultSet.getString("phone"));
                student.setProfession(resultSet.getString("profession"));
                student.setRegDate(resultSet.getDate("regdate"));
                student.setEmail(resultSet.getString("email"));
                student.setIntroduction(resultSet.getString("introduction"));
                student.setgId(resultSet.getInt("gid"));
                student.setRegistered(resultSet.getString("registered"));
                student.setIdNumber(resultSet.getString("idnumber"));
                student.setPolitics(resultSet.getString("politics"));
            }
        } catch (SQLException throwables) {
    
    
            throwables.printStackTrace();
        } finally {
    
    
            closeAll();
        }
        return student;
    }
servlet

action="/Educational/student/studentServlet?method=insert" method=“post”

    /**
     * 新增学员
     */
    protected void insert(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        //处理乱码
        //req.setCharacterEncoding("utf-8");
        //接收参数
        String stuNo = req.getParameter("stuNo");
        String stuName = req.getParameter("stuName");
        String gid = req.getParameter("gid");
        String sex = req.getParameter("sex");
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        String registered = req.getParameter("registered");
        String address = req.getParameter("address");
        String politics = req.getParameter("politics");
        String idNumber = req.getParameter("idNumber");
        String profession = req.getParameter("profession");
        String introduction = req.getParameter("introduction");
        //调取service方法
        StudentService service = new StudentServiceImpl();

        //将参数封装到学生对象中
        Student student = new Student();
        student.setStuNo(stuNo);
        student.setStuName(stuName);
        student.setgId(Integer.parseInt(gid));//接收的类型为字符串,但是后台数据为int类型
        student.setSex(Integer.parseInt(sex));
        student.setEmail(email);
        student.setPhone(phone);
        student.setRegistered(registered);
        student.setAddress(address);
        student.setPolitics(politics);
        student.setIdNumber(idNumber);
        student.setProfession(profession);
        student.setIntroduction(introduction);


        int i = service.insertStu(student);//受影响的行数
        System.out.println("insertStu受影响的行数"+i);
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();

        if(i>0){
    
    //新增成功
            writer.println("<script>alert('新增成功');location.href='/Educational/student/studentServlet'</script>");
        }else if(i == -1){
    
    
            writer.println("<script>alert('该学号已存在,新增失败');location.href='/Educational/student/getGradeList'</script>");
        }else{
    
    //新增失败
            writer.println("<script>alert('新增失败,请检查输入信息');location.href='/Educational/student/getGradeList'</script>");
        }
    }


Primary key query
service
    /**
     * 主键查询(返回一个对象)
     * 处理查询
     */
    public Student findById(int sid);
    @Override
    public Student findById(int sid) {
    
    
        return dao.findById(sid);
    }
dao
    /**
     * 主键查询(返回一个对象)
     * 处理查询
     */
    public Student findById(int sid);
    @Override
    public Student findById(int sid) {
    
    
        Student student = new Student();
        try {
    
    
            String sql = "select * from student where stuid = ?";
            List params = new ArrayList();
            params.add(sid);

            resultSet = query(sql, params);
            while (resultSet.next()){
    
    
                student.setStuId(resultSet.getInt("stuid"));
                student.setStuNo(resultSet.getString("stuno"));
                student.setStuName(resultSet.getString("stuname"));
                student.setSex(resultSet.getInt("sex"));
                student.setPhone(resultSet.getString("phone"));
                student.setProfession(resultSet.getString("profession"));
                student.setRegDate(resultSet.getDate("regdate"));
                student.setEmail(resultSet.getString("email"));
                student.setIntroduction(resultSet.getString("introduction"));
                student.setgId(resultSet.getInt("gid"));
                student.setRegistered(resultSet.getString("registered"));
                student.setIdNumber(resultSet.getString("idnumber"));
                student.setPolitics(resultSet.getString("politics"));
            }
        } catch (SQLException throwables) {
    
    
            throwables.printStackTrace();
        } finally {
    
    
            closeAll();
        }
        return student;
    }
servlet
    /**
     * 主键查询
     */
    protected void findbyid(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        //1接收参数
        String sid = req.getParameter("sid");
        //2处理查询方法,根据主键查询学生信息
        StudentService service = new StudentServiceImpl();
        Student student = service.findById(Integer.parseInt(sid));

        //查询年级列表
        GradeService gradeService = new GradeServiceImpl();
        List<Grade> list = gradeService.getList();

        req.setAttribute("glist",list);
        req.setAttribute("stu",student);
        req.getRequestDispatcher("edit.jsp").forward(req,resp);
    }

Update student information
service
    /**
     * 修改学生
     */
    public int updateStu(Student student);
    @Override
    public int updateStu(Student student) {
    
    
        return dao.updateStu(student);
    }
dao
    /**
     * 修改学生
     */
    public int updateStu(Student student);
    @Override
    public int updateStu(Student student) {
    
    
        int update = 0;
        System.out.println("执行updateStu");
        if(existId(student.getStuNo(),student.getStuName()) == 1){
    
    //已存在
            return -1;
        }
        try {
    
    
            String sql = "update student set stuname=?,stuno=?,sex=?,phone=?,email=?,registered=?,address=?,profession=?,idnumber=?,politics=?,introduction=?,gid=? where stuid = ?";
            List params = new ArrayList();

            params.add(student.getStuName());
            params.add(student.getStuNo());
            params.add(student.getSex());
            params.add(student.getPhone());
            params.add(student.getEmail());
            params.add(student.getRegistered());
            params.add(student.getAddress());
            params.add(student.getProfession());
            params.add(student.getIdNumber());
            params.add(student.getPolitics());
            params.add(student.getIntroduction());
            params.add(student.getgId());
            params.add(student.getStuId());
            update = update(sql, params);
        } catch (Exception e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            closeAll();
        }
        return update;
    }
servlet

href="/Educational/student/studentServlet?method=findbyid&sid=${stu.stuId}"

    /**
     * 修改学员
     */
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        //处理乱码
        //req.setCharacterEncoding("utf-8");


        //接收id
        String sid = req.getParameter("sid");
        //接收其它参数
        String stuNo = req.getParameter("stuNo");
        String stuName = req.getParameter("stuName");
        String gid = req.getParameter("gid");
        String sex = req.getParameter("sex");
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        String registered = req.getParameter("registered");
        String address = req.getParameter("address");
        String politics = req.getParameter("politics");
        String idNumber = req.getParameter("idNumber");
        String profession = req.getParameter("profession");
        String introduction = req.getParameter("introduction");

        //
        Student stu = new Student();

        stu.setStuId(Integer.parseInt(sid));

        stu.setStuNo(stuNo);
        stu.setStuName(stuName);
        stu.setgId(Integer.parseInt(gid));
        stu.setSex(Integer.parseInt(sex));
        stu.setEmail(email);
        stu.setPhone(phone);
        stu.setRegistered(registered);
        stu.setAddress(address);
        stu.setPolitics(politics);
        stu.setIdNumber(idNumber);
        stu.setProfession(profession);
        stu.setIntroduction(introduction);


        StudentService service = new StudentServiceImpl();
        int i = service.updateStu(stu);
        System.out.println("i的值为:"+i);

        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();

        if(i>0){
    
    //更新成功
            writer.println("<script>alert('更新成功');location.href='/Educational/student/studentServlet'</script>");
        }else if(i == -1){
    
    
            writer.println("<script>alert('该学号已存在,更新失败!');location.href='/Educational/student/studentServlet?method=findbyid&sid="+sid+"'</script>");
        }else{
    
    //更新失败
            writer.println("<script>alert('更新失败');location.href='/Educational/student/studentServlet?method=findbyid&sid="+sid+"'</script>");
        }
    }

Delete students
service
    /**
     * 删除学生
     */
    public int delStu(String sid);
    @Override
    public int delStu(String sid) {
    
    
        return dao.delStu(sid);
    }
dao
    /**
     * 删除学生
     */
    public int delStu(String sid);

Deletion here refers to not displaying the list when querying it, so just change the status code.

    @Override
    public int delStu(String sid) {
    
    
        int update = 0;
        try {
    
    
            String sql = "update student set state = ? where stuid = ?";
            List params = new ArrayList();
            params.add(StudentEnum.DELETE.type);
            params.add(sid);
            update = update(sql, params);
        } catch (Exception e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            closeAll();
        }
        return update;
    }
servlet

href="/Educational/student/studentServlet?method=delete&sid=${stu.stuId}

    /**
     * 删除学员
     */
    protected void deleteStu(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        //1接收参数
        String sid = req.getParameter("sid");
        //2处理查询方法,根据主键查询学生信息
        StudentService service = new StudentServiceImpl();
        int i = service.delStu(sid);//返回受影响行数

        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();

        if(i>0){
    
    //删除成功
            writer.println("<script>alert('删除成功');location.href='/Educational/student/studentServlet'</script>");
        }else{
    
    //删除失败
            writer.println("<script>alert('删除失败');location.href='/Educational/student/studentServlet'</script>");
        }
    }

※ optimization

Add filters to optimize
Insert image description here

Deal with garbled characters

EncodingFilter class

public class EncodingFilter implements Filter {
    
    

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    
    

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    
    
        //强制类型转换
        HttpServletRequest request =(HttpServletRequest)servletRequest;
        request.setCharacterEncoding("utf-8");

        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
    
    

    }
}

XML configuration

    <filter>
        <filter-name>aa</filter-name>
        <filter-class>
            com.company.filter.EncodingFilter
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>aa</filter-name>
        <url-pattern>/*</url-pattern><!--当前所有信息都应该进行乱码处理-->
    </filter-mapping>

Permission judgment

Only users who are logged in can enter the main page to perform add, delete, modify and check operations.

CheckLoginFilterClass

public class CheckLoginFilter implements Filter {
    
    
    private List<String> unUrlList = new ArrayList<>();

    //登录不成功返回的路径
    private String loginUrl = "login.jsp";

    //用户存放在session中的名称
    private String LoginSessionName;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    
    
        //拿到在web.xml配置好的需要放行的路径字符串login.jsp login
        String unUrl = filterConfig.getInitParameter("unUrl");
        String[] unUrlArr =  unUrl.split(",");//将字符串通过分号,分割成一个数组
        //把数组转换成一个集合
        unUrlList = Arrays.asList(unUrlArr);

        //拿到登录页面路径
        loginUrl = filterConfig.getInitParameter("loginUrl");

        //拿到用户存放在session中的名称
        LoginSessionName = filterConfig.getInitParameter("loginSessionName");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    
    

        //从session中拿到登录用,如果当前用户不存在,跳转回登录页面  如果存在,直接放行
        HttpServletRequest req = (HttpServletRequest)servletRequest;
        HttpServletResponse resp = (HttpServletResponse)servletResponse;

        //拿到访问的路径    req.getRequestURI() 拿到的结果是:/login.jsp
        String uri = req.getRequestURI().substring(1);//结果是:login.jsp

        //如果这个List中没有包含uri中的路径才进行权限判断
        if(!unUrlList.contains(uri)){
    
    
            Object user = req.getSession().getAttribute(LoginSessionName);
            if(user==null){
    
    //判断用户是否为空
                resp.sendRedirect(loginUrl);
                return;
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
    
    

    }
}

XML configuration

    <!--   为做权限判断而配置的过滤器 -->
    <filter>
        <filter-name>checkLogin</filter-name>
        <filter-class>
            com.company.filter.CheckLoginFilter
        </filter-class>
        <!--  配置不要进行权限判断的路径(不过滤的路径) -->
        <init-param>
            <param-name>unUrl</param-name>
            <param-value>login.jsp,login</param-value>
        </init-param>
        <!--  配置登录页面路径 -->
        <init-param>
            <param-name>loginSessionName</param-name>
            <param-value>u1</param-value>
        </init-param>
        <!--  用户存在session中的名称 -->
        <init-param>
            <param-name>loginUrl</param-name>
            <param-value>/login.jsp</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>checkLogin</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

The source code has been uploaded to the resource


Guess you like

Origin blog.csdn.net/m0_50609545/article/details/121363487