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

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

一、项目介绍

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

二、项目结构

SSM实现学生管理系统(spring+springMVC+MyBatis)_第1张图片
SSM实现学生管理系统(spring+springMVC+MyBatis)_第2张图片

三、创建数据库(studentManager)

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

四、相关配置文件

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

<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-contextartifactId>
    <version>5.1.11.RELEASEversion>
dependency>
<dependency>
    <groupId>org.aspectjgroupId>
    <artifactId>aspectjweaverartifactId>
    <version>1.9.6version>
dependency>
<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-webmvcartifactId>
    <version>5.1.11.RELEASEversion>
dependency>
<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-webartifactId>
    <version>5.1.11.RELEASEversion>
dependency>
<dependency>
    <groupId>javax.servletgroupId>
    <artifactId>javax.servlet-apiartifactId>
    <version>4.0.1version>
    <scope>providedscope>
dependency>
<dependency>
    <groupId>javax.servlet.jspgroupId>
    <artifactId>javax.servlet.jsp-apiartifactId>
    <version>2.3.3version>
    <scope>providedscope>
dependency>
<dependency>
    <groupId>com.fasterxml.jackson.coregroupId>
    <artifactId>jackson-databindartifactId>
    <version>2.12.0version>
dependency>
<dependency>
    <groupId>commons-fileuploadgroupId>
    <artifactId>commons-fileuploadartifactId>
    <version>1.3.2version>
dependency>
<dependency>
    <groupId>org.mybatisgroupId>
    <artifactId>mybatisartifactId>
    <version>3.4.6version>
dependency>
<dependency>
    <groupId>mysqlgroupId>
    <artifactId>mysql-connector-javaartifactId>
    <version>8.0.19version>
dependency>
<dependency>
    <groupId>log4jgroupId>
    <artifactId>log4jartifactId>
    <version>1.2.12version>
dependency>
<dependency>
    <groupId>com.mchangegroupId>
    <artifactId>c3p0artifactId>
    <version>0.9.5.5version>
dependency>
<dependency>
    <groupId>org.mybatisgroupId>
    <artifactId>mybatis-springartifactId>
    <version>2.0.6version>
dependency>
<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-txartifactId>
    <version>5.1.11.RELEASEversion>
dependency>
<dependency>
  <groupId>org.springframeworkgroupId>
  <artifactId>spring-jdbcartifactId>
  <version>5.1.11.RELEASEversion>
dependency>

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


<beans xmlns="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-scan base-package="com.stu">context:component-scan>

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.cj.jdbc.Driver">property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/studentManager?userSSL=false&serverTimezone=Asia/Shanghai">property>
        <property name="user" value="root">property>
        <property name="password" value="123456">property>
        <property name="maxPoolSize" value="10">property>
        <property name="initialPoolSize" value="5">property>
        <property name="minPoolSize" value="5">property>
    bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource">property>
        
        <property name="typeAliasesPackage" value="com.stu.pojo">property>
        <property name="mapperLocations" value="classpath:mapper/*.xml">property>
        <property name="configLocation" value="classpath:mybatis-config.xml">property>
    bean>

    
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.stu.dao">property>
    bean>

    
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource">property>
    bean>
    
    <tx:annotation-driven transaction-manager="transactionManager">tx:annotation-driven>
beans>

3.配置springmvc.xml


<beans xmlns="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">

    
    <context:component-scan base-package="com.stu.controller">context:component-scan>
    
    <mvc:annotation-driven/>
    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/">property>
        <property name="suffix" value=".jsp">property>
    bean>

beans>

4.配置mybatis-congfig.xml

DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <settings>
        
        <setting name="logImpl" value="LOG4J"/>
        
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    settings>

configuration>

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

DOCTYPE web-app PUBLIC
        "-//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 Applicationdisplay-name>
  <context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:spring-context.xmlparam-value>
  context-param>

  
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
  listener>

  
  <servlet>
    <servlet-name>SpringMVCDispatcherServletservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    
    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:springmvc.xmlparam-value>
    init-param>
    
    <load-on-startup>1load-on-startup>
  servlet>
  
  <servlet-mapping>
    <servlet-name>SpringMVCDispatcherServletservlet-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"%>
DOCTYPE html>
<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>

<div class="mainDiv">
    <div class="titleDiv">学生信息管理平台div>

    <form action="userLogin" method="post">
        <div class="loginDiv">
            <div class="name">
                用户登录 <a href="toRegister">立即注册a>
            div>

            <div class=item>
                <input type="text" name="uid" placeholder="用户名"/>
            div>
            <div class=item>
                <input type="password" name="pwd" placeholder="密码"/>
            div>
            <input type="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)

package com.stu.pojo;

public class Student {

    private Integer sno;
    private String sname;
    private String sex;
    private Integer age;
    private String phone;

    public Student(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;
    }

    public Student() {

    }

    public Integer getSno() {
        return sno;
    }

    public void setSno(Integer sno) {
        this.sno = sno;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public String getSex() {
        return sex;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getPhone() {
        return phone;
    }

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


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

package com.stu.pojo;

import java.util.List;

//分页帮助类
public class Page {
    private Integer currentPage;  //当前页面
    private Integer pageSize;     //一页有多少条数据
    private Integer totalCount;   //一共有多少条数据
    private Integer totalPage;    //一共有多少页
    private List<Student> student;

    public Page() {

    }

    public Page(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;
    }

    public Integer getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(Integer currentPage) {
        this.currentPage = currentPage;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public Integer getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(Integer totalCount) {
        this.totalCount = totalCount;
    }

    public Integer getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(Integer totalPage) {
        this.totalPage = totalPage;
    }

    public List<Student> getStudent() {
        return student;
    }

    public void setStudent(List<Student> student) {
        this.student = student;
    }


}

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

package com.stu.pojo;

public class User {

    private Integer uid;

    private String pwd;

    public User(Integer uid, String pwd) {
        this.uid = uid;
        this.pwd = pwd;
    }

    public Integer getUid() {
        return uid;
    }

    public void setUid(Integer uid) {
        this.uid = uid;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
}

3.业务逻辑实现

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

(1)配置studentMapper.xml


DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.stu.dao.IStudentDao">

    <select id="login" resultType="User">
        select *
        from login
        where uid = #{uid}
          and pwd = #{pwd}
    select>

    <insert id="register" parameterType="User">
        insert into login value (#{uid}, #{pwd})
    insert>

    <insert id="addStudent" parameterType="Student">
        insert into student value (#{sno}, #{sname}, #{sex}, #{age}, #{phone})
    insert>

    <select id="getAllStudents" resultType="Student">
        select *
        from student
    select>

    <select id="queryStudentByPage" resultType="Student">
        select *
        from student limit #{startPosition}, #{pageSize}
    select>

    <delete id="deleteStudent" parameterType="Student">
        delete
        from student
        where sno = #{sno}
    delete>

    <select id="queryStudentBySno" resultType="Student">
        select *
        from student
        where sno = #{sno}
    select>

    <update id="updateStudentBySno" parameterType="Student">
        update student
        set sname = #{sname},
            sex   = #{sex},
            age   = #{age},
            phone = #{phone}
        where sno = #{sno}
    update>

    <select id="getTotalCount" resultType="java.lang.Integer">
        select count(*)
        from student
    select>
    
mapper>

(2)dao层(IStudentDao.java)

package com.stu.dao;
import com.stu.pojo.User;
import com.stu.pojo.Student;
import org.apache.ibatis.annotations.Param;

import java.util.List;
import java.util.Map;


public interface IStudentDao {

    public User login(@Param("uid") Integer uid, @Param("pwd") String pwd);

    public int register(User user);

    public int addStudent(Student student);

    public List<Student> getAllStudents();

    public int getTotalCount();

    public List<Student> queryStudentByPage(Map<String,Integer> map);

    public int deleteStudent(Integer sno);

    public Student queryStudentBySno(Integer sno);

    public int updateStudentBySno(Student student);


}

(3)service层(StudentService.java)

package com.stu.service;

import com.stu.dao.IStudentDao;
import com.stu.pojo.Student;
import com.stu.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class StudentService {

    @Autowired
    private IStudentDao dao;

    public User login(Integer uid, String pwd){

        return dao.login(uid, pwd);

    }

    @Transactional(rollbackFor = Exception.class)
    public int register(User user){

        return dao.register(user);
    }

    @Transactional(rollbackFor = Exception.class)
    public int addStudent(Student student){

        return dao.addStudent(student);
    }

    public List<Student> getAllStudents(){

        return dao.getAllStudents();
    }

    public int getTotalCount(){

        return dao.getTotalCount();
    }

    public List<Student> queryStudentsByPage(Integer currentPage, Integer pageSize){

        Map<String,Integer> map = new HashMap<String, Integer>();

        int startPosition = (currentPage - 1) * pageSize;
        map.put("startPosition", startPosition);
        map.put("pageSize",pageSize);

        return dao.queryStudentByPage(map);
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteStudent(Integer sno){

        dao.deleteStudent(sno);
    }

    public Student queryStudentBySno(Integer sno){

        return dao.queryStudentBySno(sno);
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateStudentBySno(Student stu) {

        dao.updateStudentBySno(stu);
    }

}

(4)controller层

① UserController.java
package com.stu.controller;

import com.stu.pojo.User;
import com.stu.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


@Controller
public class UserController {
    @Autowired
    private StudentService service;

    @GetMapping("/login")
    public String login( ) {
        return "login";
    }

    @PostMapping("/userLogin")
    public String userLogin(@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")
    public String toRegister(){
        return "register";
    }

    @PostMapping("/userRegister")
    public String userRegister(User user, HttpServletRequest request){
        int result = service.register(user);

        if(result > 0) {
            request.setAttribute("register", "reg");
            return "login";
        }else {
            return "register";
        }

    }

    @GetMapping("/backLogin")
    public String back(){
        return "login";
    }

}


② StudentController.java
package com.stu.controller;

import com.stu.pojo.Page;
import com.stu.pojo.Student;
import com.stu.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class StudentController {

    @Autowired
    private StudentService service;

    @GetMapping("/toAddStudent")
    public String toAddStudent(){
        return "addStudent";
    }

    @GetMapping("/AddStudent")
    public String AddStudent(Student student){
        int result = service.addStudent(student);
        if(result > 0){
            return "main";

        }else {
            return "addStudent";
        }
    }

    @GetMapping("/toShowStudentsByPage")
    public String ShowStudentsByPage(Integer currentPage, HttpServletRequest request){

        Page page = new Page();
        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")
    public String ShowAllStudents(HttpSession session){
        List<Student> allStudents = service.getAllStudents();
        session.setAttribute("allStudents", allStudents);
        return "showAllStudents";
    }

    @GetMapping("/back")
    public String back(){
        return "main";
    }

    @GetMapping("/quit")
    public String quit(){
        return "redirect:/login";
    }

    @GetMapping("/toDeleteStudent")
    public String deleteStudent(Integer sno,HttpServletRequest request){
        service.deleteStudent(sno);
        return "forward:/toShowAllStudents";
    }

    @GetMapping("/toUpdateStudent")
    public String queryStudentBySno(Integer sno, HttpServletRequest request){
        Student student = service.queryStudentBySno(sno);
        request.setAttribute("student", student);
        return "updateStudent";
    }

    @GetMapping("/updateStudent")
    public String updateStudent(Student s){
        service.updateStudentBySno(s);
        return "forward:/toShowAllStudents";
    }


}

你可能感兴趣的:(java,java-ee,spring)