目录
引言
对java本身不是很熟悉,想着到期末了,也要学点有用的东西,就选择了SSM框架。如果有错,还请指教。
(功能进一步完善,主要是数据处理的异常。代码也上传到github。-----2019/6/19)
题目要求
教师登录后可以录入自己任课课程的学生的成绩,可以修改、查看、成绩.查看学生成绩时,要求用到分页技术
学生登录后可以选课,选课后不可更改。可以查看自己所上课程的成绩
教务人员登录后可以录入教师任课信息,可以修改学生选课信息。
设计阶段
数据库设计
Controller层设计
运行效果图:
SSM框架搭建:
基础配置
选择创建project,然后就跳到这个页面,选择Maven,然后打勾,然后选择下面蓝色的选项,然后next
groupId一般是域名的反写,也作为项目中类的包名(在java目录下下面会提到),artifactId是工程名
记得添加蓝色的这一行,不然后面可能会报错
然后的等创建结束后,生成的目录如下:(创建的过程很慢的,一定要等创建完,中间可能会出现没有main文件夹(遇到这个问题百度),这个目录一定是自动生成的)
然后创建其他文件夹,如下图,然后对照着下面有颜色的文件夹,分别右击,选择Mark Directory As,分别标记(test目录的两个文件夹分别标记为test source root和test resource root; main目录下的java和resource分别标记为source root和resource root),不标记的话后面的会在配置文件中报错的:
配置Maven
配置pox.xml, 这个文件夹就5和6行(groupId和artifactId)是不同的,就是上面说的创建项目要填的,直接把整个复制过去,然后在IDEA的右下角会出现一个“import....”,点击然后就会自己下载相关配置文件了。我出现过的问题都有记录在配置文件中说明情况和解决方法,可以仔细看下。(这个文件有一处,在最后面)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.springmvc</groupId>
<artifactId>STUDENT</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>STUDENT Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<!-- spring版本号 -->
<spring.version>4.2.5.RELEASE</spring.version>
<!-- mybatis版本号 -->
<mybatis.version>3.2.4</mybatis.version>
<!-- log4j日志文件管理包版本 -->
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
</properties>
<dependencies>
<!-- spring核心包 -->
<!-- springframe start -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- springframe end -->
<!-- mybatis核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- mybatis/spring包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<!-- mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.29</version>
</dependency>
<!-- junit测试包 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2.1-b03</version>
<scope>provided</scope>
</dependency>
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!-- json数据 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.7.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.7.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.1</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<!-- commons -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.5.6</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.8.3</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>net.sf.ezmorph</groupId>
<artifactId>ezmorph</artifactId>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- 日志文件管理包 -->
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!--上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!-- log end -->
</dependencies>
<build>
<finalName>STUDENT</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
<!--这个配置文件是配置maven中的mybatis插件的这个必须放在和pluginManagement同一个目录下
不然在maven中找不到插件-->
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<!--允许移动生成的文件-->
<verbose>true</verbose>
<!--允许覆盖生成的文件-->
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
</build>
</project>
generator.properties配置数据库(不用这个也是可以的,只是要改generatorConfig.xml里面的配置内容),只需要修改引号标注的内容(引号千万别留着,下面也是一样)
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/"数据库名"?useUnicode=true&characterEncoding=utf-8
username="mysql登录名"
password=“密码”
#entity 包名和 java目录
modelPackage=com.springmvc.entity
modelProject=src/main/java
#sqlmap包名 和resources目录
sqlPackage=sqlmap
sqlProject=src/main/resources
#mapper包名和 java目录
mapperPackage=com.springmvc.dao
mapperProject=src/main/java
#table=“表名”
generatorConfig.xml配置文件:(classPathEntry需要改成你相应的jar,在External Libraries下找到mysql的包,然后右击copy path,这个包也是会自己下载的,所以在External Libraries下可以找到)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!--导入属性配置 -->
<properties resource="generator.properties"/>
<classPathEntry
location="/home/zeng/.m2/repository/mysql/mysql-connector-java/5.1.29/mysql-connector-java-5.1.29.jar" />
<context id="context1">
<!-- 注释 -->
<commentGenerator>
<property name="suppressAllComments" value="true" /><!-- 是否取消注释 -->
<property name="suppressDate" value="true" /> <!-- 是否生成注释代时间戳 -->
</commentGenerator>
<jdbcConnection driverClass="${driver}"
connectionURL="${url}"
userId="${username}"
password="${password}" />
<!-- 类型转换 -->
<javaTypeResolver>
<!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<javaModelGenerator targetPackage="${modelPackage}"
targetProject="${modelProject}" />
<sqlMapGenerator targetPackage="${sqlPackage}" targetProject="${sqlProject}" />
<javaClientGenerator targetPackage="${mapperPackage}"
targetProject="${mapperProject}" type="XMLMAPPER" />
<!-- 如果需要通配所有表 直接用sql的通配符 %即可 -->
<table schema="" tableName="%" enableCountByExample="false"
enableUpdateByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" selectByExampleQueryId="false"/>
</context>
</generatorConfiguration>
jdbc.properties配置
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/“数据库名”?useUnicode=true&characterEncoding=utf-8
username=“登录名”
#下面输入自己数据库的密码
password=“密码”
#定义初始连接数
initialSize=0
#定义最大连接数
maxActive=20
#定义最大空闲
maxIdle=20
#定义最小空闲
minIdle=1
#定义最长等待时间
maxWait=60000
log4j.properties配置(log4j.appender.D.File =/JAVA/Code/STUDENT/error.log,这个是日志输出的路径)
### set log levels ###
log4j.rootLogger = INFO,D
###输出到控制台###
log4j.logger.toConsole=debug,stdout
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern =%d{yyyy-MM-dd HH\:mm\:ss} [%5p] - %c -%F(%L) -%m%n
### 输出到日志文件 ###
## 其中File 可以采用绝对路径 亦可以采用相对路径 catalina.home 是tomcat目录 如果没有logs文件夹 将会报错 ##
## 更加倾向于将日志文件放在 tomcat的日志目录下${catalina.home}/logs/salesmanb2bError.log ##
## 绝对路径如:e:/salesmanb2bError.log ##
log4j.logger.daily=INFO,D
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
#log4j.appender.D.File = ${catalina.home}/
log4j.appender.D.File =/JAVA/Code/STUDENT/error.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = INFO
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern =%d{yyyy-MM-dd HH\:mm\:ss} [%5p] - %c -%F(%L) -%m%n
##log4j.logger.org.apache.ibatis=debug,stdout
##log4j.logger.java.sql=debug,stdout
上面的文件配置完成后,就双击下图蓝色部分(双击一次就好了,多了可能会在*Mapper.xml文件中生成相同的代码,这时候就需要到*Mapper.xml文件中删除重复的部分) (这个会在sqlmap文件加生成xml文件)
配置tomcat
配置的话到这边就结束了,启动tomcat可以显示hello word。
测试:
在StudentMapper中添加@Repository,然后点击StudentMapper这个接口名,然后按alt+enter,选择create test,就会出现如下第二图,然后选择要测试的接口,按next就可以。
接着在test文件夹下就会多出一个java文件然后修改如成如下代码,接着按34行的那个绿色按钮就会进行测试,看是否链接数据库(我这是之前做测试的,测试的是别的函数,根据自己创建好的@Test那个函数测试自己想测试的)其他部分基本一样。
package com.springmvc.dao;
import com.springmvc.entity.Student;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
import static org.junit.Assert.*;
public class StudentMapperTest {
private ApplicationContext applicationContext;
@Autowired
private StudentMapper studentMapper;
@Before
public void setUp() throws Exception{
//加载spring配置文件
applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
//导入需要测试的
studentMapper = applicationContext.getBean(StudentMapper.class);
}
@After
public void tearDown() throws Exception{
}
@Test
public void s_getTotal(){
Student student=studentMapper.selectByPrimaryKey(1);
System.out.println(student.getName());
System.out.println(studentMapper.getTotal());
List<Student> list;
list=studentMapper.list(1,1);
System.out.println(list.get(0).getName());
}
}
这是我点击绿色按钮执行的结果:
学生管理系统的编码阶段:
(我这边只说student的部分内容,只提重要的部分,代码就到下面的github上看,然后关于student相关的代码我会整理出来,在最后面会附带上去,就是那种可以运行的)
dao层与*Mapper.xml映射关系
如下图,这几个文件是自动生成的。DAO层是与数据库相应的mapper.xml相对应的。
如下面两图,dao层和xml相映射的,在xml文件中添加select,里面的id和Mapper里面的函数名称要是一模一样的。然后xml中的#{param1}是就是Mapper中函数的参数。然后在entity中的Student也要添加相应的函数和变量(在entity中添加的目的是为了到时候从数据库中取出来的数据能够有地方存放,建议是把这两个设置为static,因为都是共同的东西,或者干脆就不要在Student类中添加,等需要的时候再new个对象或着List来存放,其实我把这两个添加进去也没有用到过这两个函数)
Service层和dao层的关系:
service层是把dao层(即数据库那一层)给封装好,用于controller层的调用,那么contorller就不用接触到数据库层的相关代码,相当与,就是体现了模块的独立性吧
service层的接口设计:接口名称自己定义,接口的实现在Impl目录下的StudentServiceImpl
请看下面蓝色部分。@Autowired StudentMapper studentMapper;这个是用于调用Mapper接口,因为StudentMapper不是类,而是接口,所以一定要有@Autowired,不然会报错。接着就像下面的是——deleteByPrimaryKey函数一样,调用接口函数。
controller层与Service层的关系:
Service封装好了数据库部分,controller就可以正常调用Service层的接口了,记住,是调用接口而不是调用Impl里的那个类。@RequestMapping("")是用于和jsp页面进行数据交互用的,后面会说。
jsp和Controller前后端进行数据交互
这边举例一个函数(listStudent)这个是使用ModelAndView(上面的addStudent使用另一种方法,jsp和后台传值的方法有很多,可以自己百度看看):
RequestMapping中的value的值和listStudent.jsp文件中的(就是第二张图的蓝色部分的值)对应,意思就是说,在jsp页面这个按钮按下后,后台要处理的函数在那个java函数中(就是第一张图的listStudent函数),然后new ModelAndView("listStudent")这个意思是加载视图页面是哪个(就是MVC的概念),这边是函数处理后要跳转的页面(listStudent.jsp)。然后request.getParameter("page.count")是获取jsp文件中参数名为page.count的参数,mav.addObject("page", page);就是将处理好的参数传递给jsp页面,如下第三图的蓝色部分,这个就是和mav.addObject("page", page)中的"page"一样的参数。(意思就是说在jsp页面可以直接使用java中的变量)
分页技术的实现:
在util(一般是用来存放工具的)
中创建Page.java,然后在listStudent函数中使用。
这边的代码是用来分页的,就是分页中显示下面的那个数字,这个和上图相对应,这个只要理解varStatus标签就很好理解下面的代码了。
page.java代码:
package com.springmvc.util;
public class Page {
int start; // 开始数据
int count; // 每一页的数量
int total; // 总共的数据量
public Page(int start, int count) {
super();
this.start = start;
this.count = count;
}
public boolean isHasPreviouse(){
if(start==0)
return false;
return true;
}
public boolean isHasNext(){
if(start==getLast())
return false;
return true;
}
public int getTotalPage(){
int totalPage;
// 假设总数是50,是能够被5整除的,那么就有10页
if (0 == total % count)
totalPage = total /count;
// 假设总数是51,不能够被5整除的,那么就有11页
else
totalPage = total / count + 1;
if(0==totalPage)
totalPage = 1;
return totalPage;
}
public int getLast(){
int last;
// 假设总数是50,是能够被5整除的,那么最后一页的开始就是40
if (0 == total % count)
last = total - count;
// 假设总数是51,不能够被5整除的,那么最后一页的开始就是50
else
last = total - total % count;
last = last<0?0:last;
return last;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
}
Student相关的代码:
messageController.jsp
这个是登录页面
package com.springmvc.controller;
import com.springmvc.entity.Student;
import com.springmvc.entity.Teacher;
import com.springmvc.service.Impl.StudentServiceImlp;
import com.springmvc.service.Impl.TeacherServiceImpl;
import com.springmvc.service.StudentService;
import com.springmvc.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping("")
public class messageController {
@Autowired
private StudentService studentService;
@Autowired
private TeacherService teacherService;
@RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView login1(String uname, String pwd, HttpServletRequest request){
ModelAndView mav = new ModelAndView();
String type;
uname = request.getParameter("loginName");
pwd = request.getParameter("passWord");
type = request.getParameter("loginType");
if(type.equals("管理员")){
if(uname != null && pwd != null && uname.equals("zeng") && pwd.equals("123")){
mav.setViewName("basePage");
return mav;
}
}else if(type.equals("教师")){
int ind=Integer.parseInt(uname);
Teacher teacher = teacherService.t_selectByPrimaryKey(ind);
if(teacher.getPassword().equals(pwd)){
mav.setViewName("basePageTeacher");
mav.addObject("teacher_id",uname);
return mav;
}
}else if(type.equals("学生")){
int ind=Integer.parseInt(uname);
Student student = studentService.s_selectByPrimaryKey(ind);
if(student.getPassword().equals(Integer.parseInt(pwd))){
mav.setViewName("basePageStudent");
mav.addObject("stu_id",uname);
return mav;
}
}else{
mav.setViewName("test");
return mav;
}
return null;
}
@RequestMapping(value = "/login/page")
public String loginPage(String uname, String pwd, HttpServletRequest request){
return "login";
}
@RequestMapping(value = "/register/page")
public String registerPage(){
return "register";
}
@RequestMapping(value = "/test")
public String test(){
return "basePage";
}
}
basePageStudent.jsp
(这个是学生登录后的主页面)
<%--
Created by IntelliJ IDEA.
User: zeng
Date: 19-6-2
Time: 上午10:06
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta charset="UTF-8">
<title>学生管理系统--学生</title>
<link href="css/basePageStyle.css" rel="stylesheet">
</head>
<body>
<div id="header">
<h2>学生管理系统</h2>
<a style="float: right; margin-top: -10px;">欢迎:${stu_id} 身份:学生<a href="login/page"> 首页</a></a>
</div>
<div id="left">
<ul id="nav">
<li><a href="${pageContext.request.contextPath}/StudentInfoPage?student_id=${stu_id}" target="content">个人信息</a></li>
<li><a href="${pageContext.request.contextPath}/StudentScorePage?pagestart=0" target="content">成绩管理</a></li>
<li><a href="${pageContext.request.contextPath}/StudentCoursePage?student_id=${stu_id}" target="content">课程管理</a></li>
<li><a href="${pageContext.request.contextPath}/StudentAddCoursePage?student_id=${stu_id}" target="content">选课管理</a></li>
</ul>
</div>
<div id="right">
<iframe id="iframe" name="content" src="" width="100%" height="700px"></iframe>
</div>
</body>
</html>
listStudent.jsp
<%--
Created by IntelliJ IDEA.
User: zeng
Date: 19-5-30
Time: 下午2:28
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java"
pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<%-- 引入JQ和Bootstrap --%>
<script src="js/jquery/2.0.0/jquery.min.js"></script>
<link href="css/bootstrap/3.3.6/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap/3.3.6/bootstrap.min.js"></script>
<link href="css/style.css" rel="stylesheet">
<title>学生管理页面</title>
<!-- <meta http-equiv="refresh" content="0;url=${pageContext.request.contextPath}/listStudent?pagestart=0"/>-->
<script>
$(function () {
$("ul.pagination li.disabled a").click(function () {
return false;
});
$()
});
function del() {
var msg = "您真的确定要删除吗?\n\n请确认!";
if (confirm(msg) == true) {
return true;
} else {
return false;
}
}
</script>
</head>
<body>
<div>
<form action="${pageContext.request.contextPath}/listStudent?pagestart=0" method="post">
<tr>
<input id="update" type="submit" value="刷新">
</tr>
</form>
<form action="${pageContext.request.contextPath}/addStudentPage" method="post">
<tr>
<input id="addStudent" type="submit" value="添加学生">
</tr>
</form>
<form action="${pageContext.request.contextPath}/searchStudent" method="post">
查找学生:<input id="searchStudent" type="text" name="searchStudent"/>
<input type="submit" value="查找"/>
</form>
</div>
<div class="listDIV">
<table class="table table-striped table-bordered table-hover table-condensed">
<caption>学生列表 - 共${page.total+1 }人</caption>
<thead>
<tr class="success">
<th>学号</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>出生日期</th>
<th>家庭地址</th>
<th>身份证号</th>
<th>电话号码</th>
<th>编辑</th>
<th>删除</th>
</tr>
</thead>
<tbody>
<c:forEach items="${students}" var="s" varStatus="status">
<tr>
<td>${s.num}</td>
<td>${s.name}</td>
<td>${s.age}</td>
<td>${s.sex}</td>
<td>${s.birthday}</td>
<td>${s.address}</td>
<td>${s.idcard}</td>
<td>${s.tel}</td>
<td><a href="${pageContext.request.contextPath}/editStudent?edit_id=${s.num}"><span class="glyphicon glyphicon-edit"></span> </a></td>
<td><a href="${pageContext.request.contextPath}/deleteStudent?del_id=${s.num}" onclick="javascript:return del();"><span class="glyphicon glyphicon-trash"></span> </a></td>
</tr>
</c:forEach>
</tbody>
</table>
</form>
</div>
<nav class="pageDIV">
<ul style="list-style-type:none;margin:0;padding:0;">
<li style="margin:0 10px;float: left;"<c:if test="${!page.hasPreviouse}">class="disabled"</c:if>>
<a>
<form action="${pageContext.request.contextPath}/listStudent?pagestart=0" method="post">
<input type="submit" value="«">
</form>
</a>
</li>
<li style="margin:0 10px;float: left;"<c:if test="${!page.hasPreviouse}">class="disabled"</c:if>>
<form action="${pageContext.request.contextPath}/listStudent?pagestart=${page.start-page.count}" method="post">
<input type="submit" value="‹">
</form>
</a>
</li>
<c:forEach begin="0" end="${page.totalPage}" varStatus="status">
<c:if test="${status.count*page.count-page.start<=30 && status.count*page.count-page.start>=-10}">
<li style="margin:0 10px;float: left;"<c:if test="${status.index*page.count==page.start}">class="disabled"</c:if>>
<a <c:if test="${status.index*page.count==page.start}">class="current"</c:if> >
<form action="${pageContext.request.contextPath}/listStudent?pagestart=${status.index*page.count}" method="post">
<input type="submit" value=${status.count}>
</form>
</a>
</li>
</c:if>
</c:forEach>
<li style="margin:0 10px;float: left;"<c:if test="${!page.hasNext}">class="disabled"</c:if>>
<form action="${pageContext.request.contextPath}/listStudent?pagestart=${page.start+page.count}" method="post">
<input type="submit" value="›">
</form>
</li>
<li style="margin:0 10px;float: left;"<c:if test="${!page.hasNext}">class="disabled"</c:if>>
<form action="${pageContext.request.contextPath}/listStudent?pagestart=${page.last}" method="post">
<input type="submit" value="»">
</form>
</li>
</ul>
</nav>
</body>
</html>
studentInfo.jsp
<%--
Created by IntelliJ IDEA.
User: zeng
Date: 19-6-2
Time: 上午10:11
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>个人信息</title>
<%-- 引入JQ和Bootstrap --%>
<script src="js/jquery/2.0.0/jquery.min.js"></script>
<link href="css/bootstrap/3.3.6/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap/3.3.6/bootstrap.min.js"></script>
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<div class="addDIV">
<div class="panel panel-success">
<div class="panel-heading">
<h3 class="panel-title">个人信息</h3>
</div>
<div class="panel-body">
<form method="post" role="form">
<table class="addTable">
<tr>
<td>学号:</td>
<td><input type="text" name="student_id" id="student_id" value="${stu_info.num}"
readonly="true">
</td>
</tr>
<tr>
<td>姓名:</td>
<td><input type="text" name="name" id="name" value="${stu_info.name}"
readonly="true">
</td>
</tr>
<tr>
<td>密码:</td>
<td><input type="text" name="password" id="password" value="${stu_info.password}"
readonly="true">
</td>
</tr>
<tr>
<td>年龄:</td>
<td><input type="text" name="age" id="age" value="${stu_info.age}"
readonly="true">
</td>
</tr>
<tr>
<td>性别:</td>
<td><input type="text" name="sex" id="sex" value="${stu_info.sex}" readonly="true">
</td>
</tr>
<tr>
<td>出生日期:</td>
<td><input type="date" name="birthday" id="birthday" value="${stu_info.birthday}"
readonly="true">
</td>
</tr>
<tr>
<td>地址:</td>
<td><input type="text" name="address" id="address" value="${stu_info.address}"
readonly="true">
</td>
</tr>
<tr>
<td>电话:</td>
<td><input type="text" name="tel" id="tel" value="${stu_info.tel}"
readonly="true">
</td>
</tr>
<tr>
<td>身份证号:</td>
<td><input type="text" name="IDCard" id="IDCard" value="${stu_info.idcard}"
readonly="true">
</td>
</tr>
</table>
</form>
</div>
</div>
</div>
</body>
</html>
addStudent.jsp
<%--
Created by IntelliJ IDEA.
User: zeng
Date: 19-5-31
Time: 上午8:58
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>添加学生</title>
<%-- 引入JQ和Bootstrap --%>
<script src="js/jquery/2.0.0/jquery.min.js"></script>
<link href="css/bootstrap/3.3.6/bootstrap.min.css" rel="stylesheet">
<script src="js/bootstrap/3.3.6/bootstrap.min.js"></script>
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<div class="addDIV">
<div class="panel panel-success">
<div class="panel-heading">
<h3 class="panel-title">增加学生</h3>
</div>
<div class="panel-body">
<form method="post" action="${pageContext.request.contextPath}/addStudent" role="form">
<table class="addTable">
<tr>
<td>学号:</td>
<td><input type="text" name="student_id" id="student_id" value="${update_student.num}"
placeholder="请在这里输入学号"></td>
</tr>
<tr>
<td>姓名:</td>
<td><input type="text" name="name" id="name" value="${update_student.name}" placeholder="请在这里输入名字">
</td>
</tr>
<tr>
<td>密码:</td>
<td><input type="text" name="password" id="password" value="${update_student.password}" placeholder="请在这里输入密码">
</td>
</tr>
<tr>
<td>年龄:</td>
<td><input type="text" name="age" id="age" value="${update_student.age}" placeholder="请在这里输入年龄"></td>
</tr>
<tr>
<td>性别:</td>
<td><input type="radio" class="radio radio-inline" name="sex" value="男"> 男
<input type="radio" class="radio radio-inline" name="sex" value="女"> 女
</td>
</tr>
<tr>
<td>出生日期:</td>
<td><input type="date" name="birthday" id="birthday" value="${update_student.birthday}"
placeholder="请在这里输入出生日期"></td>
</tr>
<tr>
<td>地址:</td>
<td><input type="text" name="address" id="address" value="${update_student.address}"
placeholder="请在这里输入地址"></td>
</td>
</tr>
<tr>
<td>电话:</td>
<td><input type="text" name="tel" id="tel" value="${update_student.tel}"
placeholder="请在这里输入电话"></td>
</td>
</tr>
<tr>
<td>身份证号:</td>
<td><input type="text" name="IDCard" id="IDCard" value="${update_student.idcard}"
placeholder="请在这里输入身份证号"></td>
</td>
</tr>
<tr class="submitTR">
<td colspan="2" align="center">
<button type="submit" class="btn btn-success">提 交</button>
</td>
</tr>
</table>
</form>
</div>
</div>
</div>
</body>
</html>
studentController.java
package com.springmvc.controller;
import com.springmvc.entity.Course;
import com.springmvc.entity.Score;
import com.springmvc.entity.Student;
import com.springmvc.service.CourseService;
import com.springmvc.service.ScoreService;
import com.springmvc.service.StudentService;
import com.springmvc.util.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
@Controller
@RequestMapping("")
public class StudentController {
@Autowired
private StudentService studentService;
@Autowired
private ScoreService scoreService;
@Autowired
private CourseService courseService;
// 获取分页参数
int start = 0;
int count = 10;
Page page = new Page(start, count);
Integer student_current_id=-1;
@RequestMapping("BaseStudentPage")
public String rtnStuIndexPage(){
return "listStudent";
}
@RequestMapping("StudentInfoPage")
public ModelAndView stuInfo(@RequestParam("student_id")int id){
ModelAndView mav = new ModelAndView("StudentInfo");
if(student_current_id.equals(-1)){
student_current_id=id;
}
Student student = new Student();
student = studentService.s_selectByPrimaryKey(id);
mav.addObject("stu_info",student);
return mav;
}
@RequestMapping("StudentScorePage")
public ModelAndView stuScore(@RequestParam("pagestart")int pagestart,HttpServletRequest request){
ModelAndView mav = new ModelAndView("StudentScore");
try {
start = pagestart;
count = Integer.parseInt(request.getParameter("page.count"));
} catch (Exception e) {
}
page.setStart(start);
List<Score> scores = new LinkedList<Score>();
scores = scoreService.sc_selectByStudent(student_current_id);
int total = studentService.s_getTotal();
page.setTotal(total-1);
mav.addObject("page", page);
mav.addObject("stu_scores",scores);
return mav;
}
@RequestMapping("StudentCoursePage")
public ModelAndView stuCourse(@RequestParam("student_id")int id){
ModelAndView mav = new ModelAndView("StudentCourse");
if(student_current_id.equals(-1)){
student_current_id=id;
}
Course course = new Course();
course = courseService.c_selectByPrimaryKey(id);
mav.addObject("stu_course",course);
return mav;
}
@RequestMapping("StudentAddCoursePage")
public ModelAndView stuAddCourse(@RequestParam("student_id")int id){
ModelAndView mav = new ModelAndView("addCourse");
if(student_current_id.equals(-1)){
student_current_id=id;
}
Course course = new Course();
course = courseService.c_selectByPrimaryKey(id);
mav.addObject("stu_course",course);
return mav;
}
@RequestMapping(value = "/addStudent", method = {RequestMethod.POST, RequestMethod.GET})
public String addStudent(HttpServletRequest request, HttpServletResponse response) {
Student student = new Student();
int studentID = Integer.parseInt(request.getParameter("student_id"));
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
String sex = request.getParameter("sex");
String address=request.getParameter("address");
int password=Integer.parseInt(request.getParameter("password"));
int idcard = Integer.parseInt(request.getParameter("IDCard"));
int tel = Integer.parseInt(request.getParameter("tel"));
Date birthday = null;
// String 类型按照 yyyy-MM-dd 的格式转换为 java.util.Date 类
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
birthday = simpleDateFormat.parse(request.getParameter("birthday"));
} catch (ParseException e) {
e.printStackTrace();
}
student.setNum(studentID);
student.setName(name);
student.setAge(age);
student.setSex(sex);
student.setBirthday(birthday);
student.setPassword(password);
student.setAddress(address);
student.setIdcard(idcard);
student.setTel(tel);
studentService.s_insert(student);
//为啥不能使用redirect:
return "listStudent";
}
@RequestMapping(value = "/listStudent", method = {RequestMethod.POST, RequestMethod.GET})
public ModelAndView listStudent(@RequestParam("pagestart")int pagestart,HttpServletRequest request) {
ModelAndView mav = new ModelAndView("listStudent");
try {
start = pagestart;
count = Integer.parseInt(request.getParameter("page.count"));
} catch (Exception e) {
}
page.setStart(start);
List<Student> students = studentService.s_list(page.getStart(), page.getCount());
int total = studentService.s_getTotal();
page.setTotal(total-1);
mav.addObject("page", page);
mav.addObject("students", students);
return mav;
}
@RequestMapping("/deleteStudent")
public String deleteStudent(@RequestParam("del_id")int id) {
studentService.s_deleteByPrimaryKey(id);
return "listStudent";
}
@RequestMapping("/editStudent")
public ModelAndView editStudent(@RequestParam("edit_id")int id) {
ModelAndView mav = new ModelAndView("editStudent");
Student student = studentService.s_selectByPrimaryKey(id);
mav.addObject("update_student", student);
return mav;
}
@RequestMapping(value = "/updateStudent", method = {RequestMethod.POST, RequestMethod.GET})
public String updateStudent(HttpServletRequest request) {
Student student=new Student();
String tel = request.getParameter("tel");
String name = request.getParameter("name");
String studentID = request.getParameter("student_id");
String age = request.getParameter("age");
String sex = request.getParameter("sex");
String pass = request.getParameter("password");
String idcard =request.getParameter("IDCard");
String address =request.getParameter("address");
Date birthday = null;
// String 类型按照 yyyy-MM-dd 的格式转换为 java.util.Date 类
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
birthday = simpleDateFormat.parse(request.getParameter("birthday"));
} catch (ParseException e) {
e.printStackTrace();
}
Integer i_age=Integer.parseInt(age);
student.setName(name);
student.setAge(i_age);
student.setNum(Integer.parseInt(studentID));
student.setSex(sex);
student.setBirthday(birthday);
student.setPassword(Integer.parseInt(pass));
student.setTel(Integer.parseInt(tel));
student.setIdcard(Integer.parseInt(idcard));
student.setAddress(address);
studentService.s_updateByPrimaryKeySelective(student);
return "listStudent";
}
@RequestMapping(value = "/addStudentPage", method = {RequestMethod.POST, RequestMethod.GET})
public String addStudentPage(){
return "addStudent";
}
@RequestMapping(value = "/searchStudent", method = {RequestMethod.POST, RequestMethod.GET})
public ModelAndView searchStudent(HttpServletRequest request) {
ModelAndView mav = new ModelAndView("listStudent");
int ind=Integer.parseInt(request.getParameter("searchStudent"));
List<Student> students = new LinkedList<Student>();
Student student=studentService.s_selectByPrimaryKey(ind);
students.add(student);
mav.addObject("students", students);
return mav;
}
}
参考书籍及博客:
https://www.cnblogs.com/toutou/p/ssm_spring.html https://www.jianshu.com/p/6a594fbea51d h
ttps://www.cnblogs.com/mumudechengzhang/p/7682361.html
https://www.cnblogs.com/Samuel-Leung/p/10691158.html
https://blog.csdn.net/jianghao233/article/details/81879370
工程的github:
https://github.com/Iconzjy/SSM_JavaEE_FinalReport_Student