0


SSM实现学生管理系统(spring+springMVC+MyBatis)

SSM实现学生管理系统(spring+springMVC+MyBatis)

一、项目介绍

该项目是基于SSM框架实现的学生管理系统,能够对学生信息进行增删改查,分页查询,以及实现管理员的注册、登录
数据库:MySQL
开发工具:idea
开发环境:jdk 1.8 + tomcat

二、项目结构

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

三、创建数据库(studentManager)

在studentManger数据库中,创建登录注册表login和学生信息表student
请参考JavaWeb实现学生管理系统

四、相关配置文件

1.配置maven环境,在pom.xml配置文件中导入对应的依赖包

<dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.1.11.RELEASE</version></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.9.6</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.1.11.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>5.1.11.RELEASE</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>4.0.1</version><scope>provided</scope></dependency><dependency><groupId>javax.servlet.jsp</groupId><artifactId>javax.servlet.jsp-api</artifactId><version>2.3.3</version><scope>provided</scope></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.12.0</version></dependency><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.2</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.6</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.19</version></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.12</version></dependency><dependency><groupId>com.mchange</groupId><artifactId>c3p0</artifactId><version>0.9.5.5</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>2.0.6</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>5.1.11.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.1.11.RELEASE</version></dependency>

2.配置数据库连接池datasource,SqlSessionFactory、mapperScanner、事务对象(spring-context.xml)

<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"><context:component-scanbase-package="com.stu"></context:component-scan><beanid="dataSource"class="com.mchange.v2.c3p0.ComboPooledDataSource"><propertyname="driverClass"value="com.mysql.cj.jdbc.Driver"></property><propertyname="jdbcUrl"value="jdbc:mysql://localhost:3306/studentManager?userSSL=false&amp;serverTimezone=Asia/Shanghai"></property><propertyname="user"value="root"></property><propertyname="password"value="123456"></property><propertyname="maxPoolSize"value="10"></property><propertyname="initialPoolSize"value="5"></property><propertyname="minPoolSize"value="5"></property></bean><beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean"><propertyname="dataSource"ref="dataSource"></property><!-- 设置别名包 --><propertyname="typeAliasesPackage"value="com.stu.pojo"></property><propertyname="mapperLocations"value="classpath:mapper/*.xml"></property><propertyname="configLocation"value="classpath:mybatis-config.xml"></property></bean><!-- mapper扫描器 --><beanid="mapperScanner"class="org.mybatis.spring.mapper.MapperScannerConfigurer"><propertyname="basePackage"value="com.stu.dao"></property></bean><!-- 配置事务管理器 --><beanid="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><propertyname="dataSource"ref="dataSource"></property></bean><!-- 配置基于注解的声明式事务 --><tx:annotation-driventransaction-manager="transactionManager"></tx:annotation-driven></beans>

3.配置springmvc.xml

<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"><!-- 配置创建 spring 容器要扫描的包 --><context:component-scanbase-package="com.stu.controller"></context:component-scan><!--Spring MVC用来提供Controller请求转发,json自动转换等功能。,默认会帮我们注册默认处理请求,参数和返回值的类。会自动注册RequestMappingHandlerMapping与RequestMappingHandlerAdapter两个Bean,这是Spring MVC为@Controller分发请求所必需的,并且提供了数据绑定支持,@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持读写XML的支持(JAXB)和读写JSON的支持(默认Jackson)等功能--><mvc:annotation-driven/><!-- 配置视图解析器 --><beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"><propertyname="prefix"value="/WEB-INF/pages/"></property><propertyname="suffix"value=".jsp"></property></bean></beans>

4.配置mybatis-congfig.xml

<!DOCTYPEconfigurationPUBLIC"-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><settings><!-- 日志 --><settingname="logImpl"value="LOG4J"/><!-- 下划线自动转成驼峰式 --><settingname="mapUnderscoreToCamelCase"value="true"/></settings></configuration>

5.配置web.xml,读取bean.xml

<!DOCTYPEweb-appPUBLIC"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN""http://java.sun.com/dtd/web-app_2_3.dtd"><web-app><display-name>Archetype Created Web Application</display-name><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-context.xml</param-value></context-param><!-- 读取Spring上下文的监听器 --><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!-- 配置spring mvc的核心控制器 --><servlet><servlet-name>SpringMVCDispatcherServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><!-- 配置初始化参数,用于读取SpringMVC的配置文件 --><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:springmvc.xml</param-value></init-param><!-- 配置servlet的对象创建的时间点:应用加载时创建。
    如果该元素的值为负数或者没有设置,则容器会当servlet被请求的时候加载。
    如果值为正整数时或者0时,表示容器在应用启动时就加载并初始化这个servlet,值越小,servlet的优先级越高,越先被加载--><load-on-startup>1</load-on-startup></servlet><!-- 所有的请求都会执行对应的这个方法 --><servlet-mapping><servlet-name>SpringMVCDispatcherServlet</servlet-name><url-pattern>/</url-pattern></servlet-mapping></web-app>

五、代码实现

1.JSP界面实现

登录界面(login.jsp)

<%@ page language="java" contentType="text/html; charset=utf-8"  pageEncoding="utf-8"%>
<!DOCTYPEhtml><html><head><title>学生信息管理平台</title><style>.titleDiv{height: 85px;color:white;padding-top: 30px;font-size: 50px;padding-left: 30px;font-family: 隶书;}.mainDiv{width: 899px;height: 500px;border: 4px rgb(237, 237, 237) solid;border-radius: 5px;background-image:url(""); <!-- 图片链接 -->
            margin: auto;margin-top: 50px;}.loginDiv{height: 220px;width: 260px;padding:50px;background-color:rgba(255,255,255,0.9);border-radius:25px;border:1px #bdbdbd solid;opacity:0.9;float: right;margin-right: 100px
        }.name{font-size: 25px;}a{font-size:15px;color:#59c2c5;padding-left:20px;}.item{height:60px;}.item input{line-height:40px;width:245px;border:none;border-bottom: 1px solid #59c2c5;margin-bottom: 20px;margin-top: 10px;}.login-btn{display:block;width:255px;height:50px;color:#fff;background:#59c2c5;font-size:16px;line-height:30px;text-align:center;border-radius:10px;border:none;margin-bottom: 20px;margin-top: 10px;}</style></head><body><divclass="mainDiv"><divclass="titleDiv">学生信息管理平台</div><formaction="userLogin"method="post"><divclass="loginDiv"><divclass="name">
                用户登录 <ahref="toRegister">立即注册</a></div><divclass=item><inputtype="text"name="uid"placeholder="用户名"/></div><divclass=item><inputtype="password"name="pwd"placeholder="密码"/></div><inputtype="submit"class="login-btn"value="登 录"/>
            <%
                String loginError = (String) request.getAttribute("loginError");
                if(loginError != null){
                    if(loginError.equals("logErr")){
                        out.println("登录失败,请检查用户名和密码!");
                    }
                }
            %>
            <%
                String register = (String) request.getAttribute("register");
                if (register!= null) {
                    if (register.equals("reg")) {
                        out.println("注册成功, 请登录!");
                    }
                }
            %>
        </div></form></div></body></html>

其他界面,请参考JavaWeb实现学生管理系统

2.JavaBean实体类封装数据

(1)学生信息类 (Student.java)

packagecom.stu.pojo;publicclassStudent{privateInteger sno;privateString sname;privateString sex;privateInteger age;privateString phone;publicStudent(Integer sno,String sname,String sex,Integer age,String phone){this.sno = sno;this.sname = sname;this.sex = sex;this.age = age;this.phone = phone;}publicStudent(){}publicIntegergetSno(){return sno;}publicvoidsetSno(Integer sno){this.sno = sno;}publicStringgetSname(){return sname;}publicvoidsetSname(String sname){this.sname = sname;}publicStringgetSex(){return sex;}publicvoidsetSex(String sex){this.sex = sex;}publicIntegergetAge(){return age;}publicvoidsetAge(Integer age){this.age = age;}publicStringgetPhone(){return phone;}publicvoidsetPhone(String phone){this.phone = phone;}}

(2)分页帮助类 (Page.java)

packagecom.stu.pojo;importjava.util.List;//分页帮助类publicclassPage{privateInteger currentPage;//当前页面privateInteger pageSize;//一页有多少条数据privateInteger totalCount;//一共有多少条数据privateInteger totalPage;//一共有多少页privateList<Student> student;publicPage(){}publicPage(Integer currentPage,Integer pageSize,Integer totalCount,Integer totalPage,List<Student> student){this.currentPage = currentPage;this.pageSize = pageSize;this.totalCount = totalCount;this.totalPage = totalPage;this.student = student;}publicIntegergetCurrentPage(){return currentPage;}publicvoidsetCurrentPage(Integer currentPage){this.currentPage = currentPage;}publicIntegergetPageSize(){return pageSize;}publicvoidsetPageSize(Integer pageSize){this.pageSize = pageSize;}publicIntegergetTotalCount(){return totalCount;}publicvoidsetTotalCount(Integer totalCount){this.totalCount = totalCount;}publicIntegergetTotalPage(){return totalPage;}publicvoidsetTotalPage(Integer totalPage){this.totalPage = totalPage;}publicList<Student>getStudent(){return student;}publicvoidsetStudent(List<Student> student){this.student = student;}}

(3)用户信息类 (User.java)

packagecom.stu.pojo;publicclassUser{privateInteger uid;privateString pwd;publicUser(Integer uid,String pwd){this.uid = uid;this.pwd = pwd;}publicIntegergetUid(){return uid;}publicvoidsetUid(Integer uid){this.uid = uid;}publicStringgetPwd(){return pwd;}publicvoidsetPwd(String pwd){this.pwd = pwd;}}

3.业务逻辑实现

controller(解析参数,封装service所需要的参数、校验参数) --> service(业务逻辑处理,加上事务) --> dao(执行sql,从数据库中查询数据)

(1)配置studentMapper.xml

<?xml version="1.0" encoding="utf-8" ?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.stu.dao.IStudentDao"><selectid="login"resultType="User">
        select *
        from login
        where uid = #{uid}
          and pwd = #{pwd}
    </select><insertid="register"parameterType="User">
        insert into login value (#{uid}, #{pwd})
    </insert><insertid="addStudent"parameterType="Student">
        insert into student value (#{sno}, #{sname}, #{sex}, #{age}, #{phone})
    </insert><selectid="getAllStudents"resultType="Student">
        select *
        from student
    </select><selectid="queryStudentByPage"resultType="Student">
        select *
        from student limit #{startPosition}, #{pageSize}
    </select><deleteid="deleteStudent"parameterType="Student">
        delete
        from student
        where sno = #{sno}
    </delete><selectid="queryStudentBySno"resultType="Student">
        select *
        from student
        where sno = #{sno}
    </select><updateid="updateStudentBySno"parameterType="Student">
        update student
        set sname = #{sname},
            sex   = #{sex},
            age   = #{age},
            phone = #{phone}
        where sno = #{sno}
    </update><selectid="getTotalCount"resultType="java.lang.Integer">
        select count(*)
        from student
    </select></mapper>

(2)dao层(IStudentDao.java)

packagecom.stu.dao;importcom.stu.pojo.User;importcom.stu.pojo.Student;importorg.apache.ibatis.annotations.Param;importjava.util.List;importjava.util.Map;publicinterfaceIStudentDao{publicUserlogin(@Param("uid")Integer uid,@Param("pwd")String pwd);publicintregister(User user);publicintaddStudent(Student student);publicList<Student>getAllStudents();publicintgetTotalCount();publicList<Student>queryStudentByPage(Map<String,Integer> map);publicintdeleteStudent(Integer sno);publicStudentqueryStudentBySno(Integer sno);publicintupdateStudentBySno(Student student);}

(3)service层(StudentService.java)

packagecom.stu.service;importcom.stu.dao.IStudentDao;importcom.stu.pojo.Student;importcom.stu.pojo.User;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;importorg.springframework.transaction.annotation.Transactional;importjava.util.HashMap;importjava.util.List;importjava.util.Map;@ServicepublicclassStudentService{@AutowiredprivateIStudentDao dao;publicUserlogin(Integer uid,String pwd){return dao.login(uid, pwd);}@Transactional(rollbackFor =Exception.class)publicintregister(User user){return dao.register(user);}@Transactional(rollbackFor =Exception.class)publicintaddStudent(Student student){return dao.addStudent(student);}publicList<Student>getAllStudents(){return dao.getAllStudents();}publicintgetTotalCount(){return dao.getTotalCount();}publicList<Student>queryStudentsByPage(Integer currentPage,Integer pageSize){Map<String,Integer> map =newHashMap<String,Integer>();int startPosition =(currentPage -1)* pageSize;
        map.put("startPosition", startPosition);
        map.put("pageSize",pageSize);return dao.queryStudentByPage(map);}@Transactional(rollbackFor =Exception.class)publicvoiddeleteStudent(Integer sno){

        dao.deleteStudent(sno);}publicStudentqueryStudentBySno(Integer sno){return dao.queryStudentBySno(sno);}@Transactional(rollbackFor =Exception.class)publicvoidupdateStudentBySno(Student stu){

        dao.updateStudentBySno(stu);}}

(4)controller层

① UserController.java
packagecom.stu.controller;importcom.stu.pojo.User;importcom.stu.service.StudentService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.PostMapping;importorg.springframework.web.bind.annotation.RequestParam;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpSession;@ControllerpublicclassUserController{@AutowiredprivateStudentService service;@GetMapping("/login")publicStringlogin(){return"login";}@PostMapping("/userLogin")publicStringuserLogin(@RequestParam(value ="uid",required =false)Integer uid,@RequestParam(value ="pwd",required =false)String pwd,HttpServletRequest request){User loginUser = service.login(uid, pwd);if(loginUser !=null){return"main";}else{
            request.setAttribute("loginError","logErr");return"login";}}@GetMapping("/toRegister")publicStringtoRegister(){return"register";}@PostMapping("/userRegister")publicStringuserRegister(User user,HttpServletRequest request){int result = service.register(user);if(result >0){
            request.setAttribute("register","reg");return"login";}else{return"register";}}@GetMapping("/backLogin")publicStringback(){return"login";}}
② StudentController.java
packagecom.stu.controller;importcom.stu.pojo.Page;importcom.stu.pojo.Student;importcom.stu.service.StudentService;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.GetMapping;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpSession;importjava.util.List;@ControllerpublicclassStudentController{@AutowiredprivateStudentService service;@GetMapping("/toAddStudent")publicStringtoAddStudent(){return"addStudent";}@GetMapping("/AddStudent")publicStringAddStudent(Student student){int result = service.addStudent(student);if(result >0){return"main";}else{return"addStudent";}}@GetMapping("/toShowStudentsByPage")publicStringShowStudentsByPage(Integer currentPage,HttpServletRequest request){Page page =newPage();if(currentPage ==null){
            currentPage =1;}
        page.setCurrentPage(currentPage);int totalCount = service.getTotalCount();
        page.setTotalCount(totalCount);int pageSize =5;Integer totalPage =(totalCount / pageSize)+1;
        page.setTotalPage(totalPage);
        page.setPageSize(pageSize);List<Student> student = service.queryStudentsByPage(currentPage, pageSize);
        page.setStudent(student);
        request.setAttribute("page1", page);return"showAllStudentsByPage";}@GetMapping("/toShowAllStudents")publicStringShowAllStudents(HttpSession session){List<Student> allStudents = service.getAllStudents();
        session.setAttribute("allStudents", allStudents);return"showAllStudents";}@GetMapping("/back")publicStringback(){return"main";}@GetMapping("/quit")publicStringquit(){return"redirect:/login";}@GetMapping("/toDeleteStudent")publicStringdeleteStudent(Integer sno,HttpServletRequest request){
        service.deleteStudent(sno);return"forward:/toShowAllStudents";}@GetMapping("/toUpdateStudent")publicStringqueryStudentBySno(Integer sno,HttpServletRequest request){Student student = service.queryStudentBySno(sno);
        request.setAttribute("student", student);return"updateStudent";}@GetMapping("/updateStudent")publicStringupdateStudent(Student s){
        service.updateStudentBySno(s);return"forward:/toShowAllStudents";}}
标签: java java-ee spring

本文转载自: https://blog.csdn.net/weixin_52849365/article/details/127586112
版权归原作者 小菜鸟想逆袭 所有, 如有侵权,请联系我们删除。

“SSM实现学生管理系统(spring+springMVC+MyBatis)”的评论:

还没有评论