目录
1、目标: 创建一个基于Maven的SSM框架 Web项目(Spring/SpringMVC/MyBatis)
4、正对[3]中的web项目, 做完如下6步操作后的项目结构图如下
4.2 在web.xml文件中配置: 中央控制器/spring监听器/字符集过滤器
4.3 新建spring-mvc.xml文件, 用来声名Controller和其他web相关的对象
4.4 新建mybatis.xml文件, 用来声名MyBatis相关的设置
4.5 新建spring.xml文件, 用来声名service/dao/工具类等对象
4.6 新建mysql连接需要的配置文件jdbc.properties
5.4 编写mysql的mapper文件:StudentDao.xml
5.5 编写Service层接口:StudentService.java
5.6 编写Service层接口的实现类:StudentServiceImpl.java
5.7 编写Controller层接口:StudentController.java
5.8.1 主页面:注册功能和浏览功能的页面:index.jsp
5.8.2 点击主页面中“注册学生”时跳转到的注册页面:addStudent.jsp
5.8.3 点击“注册页面”中的“注册”按钮时会执行超链接对应的处理器: student/addStudent.do
5.8.4 执行完“student/addStudent.do”中的“add”操作后会跳转到“注册成功”的页面: addStudentResult.jsp
6.1 Controller层:StudentController.java
6.2.2 点击“浏览学生”按钮后进入的“学生数据列表页面”:queryStudent.jsp
6.2.3 在“学生数据列表页面”可以点击“查需学生数据”来刷新该页面的新数据:queryStudent.jsp
1、目标: 创建一个基于Maven的SSM框架 Web项目(Spring/SpringMVC/MyBatis)
2、SSM框架整合的大致步骤: 文字描述
3、创建一个空的web项目
3.1 按照如下步骤初始化一个原始的web项目
3.2 上述步骤完成之后的初始化web项目结构图如下
3.3 对该初始化好的项目做一些目录调整
(1)在main目录下创建一个存放java源代码的 java目录,并把该目录标记为 Sources Root
(2)在main目录下创建一个存放各种资源文件的 resources目录,并把该目录标记为 Resources Root
(3)在main目录下创建一个存放单元测试的 test目录,并把该目录标记为 Test Sources Root
3.4 对该初始化好的web.xml做一下版本升级
3.5 web项目调整完毕:项目结构图
4、正对[3]中的web项目, 做完如下6步操作后的项目结构图如下
4.1 在pom.xml文件中引入需要依赖的jar
<?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.wind</groupId>
<artifactId>ssm-web</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>ssm-web 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.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<spring.version>5.3.2</spring.version>
<mybatis.version>3.4.6</mybatis.version>
<mybatis.spring.version>2.0.3</mybatis.spring.version>
<mysql.version>8.0.22</mysql.version>
<druid.version>1.2.4</druid.version>
</properties>
<dependencies>
<!--Spring事务依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!--Spring原生JDBC依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--SpringMVC依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--SpringMVC使用的Servlet依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<!--SpringMVC使用的jsp依赖-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2.1-b03</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--MyBatis依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!--MyBatis与SpringMVC整合时需要的依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis.spring.version}</version>
</dependency>
<!--mysql驱动依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!--mysql数据库连接池依赖:使用的是德鲁伊数据库连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<!--springMVC序列化用的jackson依赖-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.10.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.2</version>
</dependency>
<!--单元测试依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>ssm-web</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
<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默认扫描src/main/java中的文件而不理会src/main/resources中的xml文件,
所以后来添加了resource节点,这样就将src/main/resources中的xml文件改变maven默认的扫描策略,
防止造成src/main/resources下的配置文件打包丢失。
编译之后的文件中少了mapper.xml,这个和maven有关,maven编译src/java代码的时候,
默认只会对java文件进行编译然后放在target/classes目录,需要在pom.xml中加入下面配置-->
<!--如果不添加此节点,mapper.xml文件、config.properties文件、config.spring文件等
都不会被加载到target的classes中去,也就不能被使用,也就会报错。-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
</project>
4.2 在web.xml文件中配置: 中央控制器/spring监听器/字符集过滤器
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--注册前端控制器,也即整个web项目中唯一的一个后端中央控制器,用于分发给不同的Controller处理器-->
<servlet>
<servlet-name>springmvc-servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc-servlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--注册Spring的监听器-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/spring.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--注册字符集过滤器,一般使用Spring框架自带的字符集过滤器即可-->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--加载静态资源-->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
</web-app>
4.3 新建spring-mvc.xml文件, 用来声名Controller和其他web相关的对象
<?xml version="1.0" encoding="UTF-8"?>
<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.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--SpringMVC的配置文件,用来声名Controller和其他web相关的对象-->
<!--配置组件扫描器-->
<context:component-scan base-package="com.wind.controller"/>
<!--视图解析器:添加前缀和后缀。
SpringMVC框架为了避免对于请求资源路径与扩展名上的冗余,在视图解析器 InternalResouceViewResolver
中引入了请求的前辍与后辍。而 ModelAndView 中只需给出要跳转页面的文件名即可,对于具体的文件路径与文件扩展名,
视图解析器会自动完成拼接。-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--视图文件的路径-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--视图文件的扩展名-->
<property name="suffix" value=".jsp"/>
</bean>
<!--注册注解驱动。
(1)响应ajax请求,返回json字符串。
(2)解决静态资源访问问题。-->
<mvc:annotation-driven/>
<!--加载静态资源图片啊,jQuery文件啊等等-->
<mvc:resources location="js/" mapping="/js/**"/>
<mvc:resources location="images/" mapping="/images/**"/>
</beans>
4.4 新建mybatis.xml文件, 用来声名MyBatis相关的设置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!-- 打印SQL-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!--给实体类设置别名-->
<typeAliases>
<package name="com.wind.entity"/>
</typeAliases>
<!--SQL Mapper映射文件的位置-->
<mappers>
<!--name:是包名,这个包下的mapper文件能够一次性加载-->
<!--package:使用这个属性的前提是:
(1)mapper文件名称和dao接口名必须完全一样,包括大小写。
(2)mapper文件和dao接口必须在同一目录下。-->
<package name="com.wind.dao"/>
</mappers>
</configuration>
4.5 新建spring.xml文件, 用来声名service/dao/工具类等对象
<?xml version="1.0" encoding="UTF-8"?>
<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"
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.xsd">
<!--Spring的配置文件,用来声名service、dao、工具类等对象-->
<!--加载连接mysql时需要的配置文件-->
<context:property-placeholder location="classpath:config/jdbc.properties"/>
<!--声名数据源,连接数据库-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!--配置数据库连接池的初始化大小、最小、最大-->
<property name="initialSize" value="5"/>
<property name="minIdle" value="5"/>
<property name="maxActive" value="20"/>
<!--配置获取连接等待超时的时间,单位是毫秒-->
<property name="maxWait" value="10000"/>
<!--配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒-->
<property name="timeBetweenEvictionRunsMillis" value="60000"/>
<!--配置一个连接在池中最小生存的时间,单位是毫秒-->
<property name="minEvictableIdleTimeMillis" value="300000"/>
</bean>
<!--声名一个SqlSessionFactoryBean,用它来创建SqlSessionFactory-->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:config/mybatis.xml"/>
</bean>
<!--声名MyBatis的扫描器,创建dao接口接口对象-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean"/>
<property name="basePackage" value="com.wind.dao"/>
</bean>
<!--声名service的注解@Service所在的包名-->
<context:component-scan base-package="com.wind.service"/>
<!--事务的配置:注解的配置方式;aspectJ的配置方式。可以后期去加。-->
</beans>
4.6 新建mysql连接需要的配置文件jdbc.properties
##数据库驱动
jdbc.driverClassName=com.mysql.jdbc.Driver
##MySQL连接信息
jdbc.url=jdbc:mysql://127.0.0.1:3306/RUNOOB?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=GMT
##用户名
jdbc.username=root
##密码
jdbc.password=root
5、做一个addStudent的业务逻辑
5.1 建表
CREATE TABLE `RUN_Student` (
`Id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID(学号)',
`Name` varchar(256) NOT NULL DEFAULT '' COMMENT '姓名',
`ClassId` int(11) NOT NULL COMMENT '班级',
`Status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '有效=1,无效=-1',
`AddTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '添加时间',
`UpdateTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='学生信息表';
5.2 编写实体类:StudentEntity.java
package com.wind.entity;
import org.springframework.stereotype.Component;
import java.io.Serializable;
import java.util.Date;
@Component
public class StudentEntity implements Serializable {
private static final long serialVersionUID = 7475710140661551551L;
private int id; //学号
private String name; //姓名
private int classId; //班级
private int status; //是否有效(1:有效,-1:无效)
private Date addTime; //添加时间
private Date updateTime; //更新时间
//省略setter和gettter方法
}
5.3 编写dao层接口:StudentDao.java
package com.wind.dao;
import com.wind.entity.StudentEntity;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface StudentDao {
int insertStudent(@Param("studentEntity") StudentEntity studentEntity);
int deleteStudent(@Param("id") int id);
int updateStudent(@Param("studentEntity") StudentEntity studentEntity);
StudentEntity findStudentById(@Param("id") int id);
List<StudentEntity> findAllValidStudent();
}
5.4 编写mysql的mapper文件:StudentDao.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wind.dao.StudentDao">
<resultMap id="studentMap" type="com.wind.entity.StudentEntity">
<result column="Id" property="id"/>
<result column="Name" property="name"/>
<result column="ClassId" property="classId"/>
<result column="Status" property="status"/>
<result column="AddTime" property="addTime"/>
<result column="UpdateTime" property="updateTime"/>
</resultMap>
<sql id="sql_select">
select Id, Name, ClassId, Status, AddTime, UpdateTime from RUN_Student
</sql>
<insert id="insertStudent" parameterType="studentEntity" keyProperty="studentEntity.id" useGeneratedKeys="true">
insert into RUN_Student
(
Id,
Name,
ClassId,
Status
)
values
(
#{studentEntity.id},
#{studentEntity.name},
#{studentEntity.classId},
1
)
</insert>
<update id="deleteStudent" parameterType="int" useGeneratedKeys="true">
update RUN_Student set status = -1 where id = #{id}
</update>
<update id="updateStudent" parameterType="studentEntity" useGeneratedKeys="true">
update RUN_Student set
Name = #{studentEntity.name},
ClassId = #{studentEntity.classId},
Status = 1
where id = #{studentEntity.id}
</update>
<select id="findStudentById" parameterType="int" resultMap="studentMap">
<include refid="sql_select"/>
where id = #{id} and status = 1
</select>
<select id="findAllValidStudent" resultMap="studentMap">
<include refid="sql_select"/>
where status = 1
</select>
</mapper>
5.5 编写Service层接口:StudentService.java
package com.wind.service;
import com.wind.entity.StudentEntity;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public interface StudentService {
int insertStudent(StudentEntity studentEntity);
int deleteStudent(int id);
int updateStudent(StudentEntity studentEntity);
StudentEntity findStudentById(int id);
List<StudentEntity> findAllStudent();
}
5.6 编写Service层接口的实现类:StudentServiceImpl.java
package com.wind.serviceImpl;
import com.wind.dao.StudentDao;
import com.wind.entity.StudentEntity;
import com.wind.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDao studentDao;
@Override
public int insertStudent(StudentEntity studentEntity) {
int result = studentDao.insertStudent(studentEntity);
return result;
}
@Override
public int deleteStudent(int id) {
int result = studentDao.deleteStudent(id);
return result;
}
@Override
public int updateStudent(StudentEntity studentEntity) {
int result = studentDao.updateStudent(studentEntity);
return result;
}
@Override
public StudentEntity findStudentById(int id) {
StudentEntity studentEntity = studentDao.findStudentById(id);
return studentEntity;
}
@Override
public List<StudentEntity> findAllStudent() {
List<StudentEntity> studentEntityList = studentDao.findAllValidStudent();
return studentEntityList;
}
}
5.7 编写Controller层接口:StudentController.java
package com.wind.controller;
import com.wind.entity.StudentEntity;
import com.wind.service.StudentService;
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.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
@Controller
@ResponseBody
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentService studentService;
@RequestMapping(value = "addStudent.do", method = RequestMethod.POST)
public ModelAndView addStudent(StudentEntity studentEntity) {
//创建一个视图
ModelAndView modelAndView = new ModelAndView();
String tips = "注册失败,请稍后重试。";
int insertResult = studentService.insertStudent(studentEntity);
if (insertResult > 0) {
tips = "学生【" + studentEntity.getName() + "】注册成功。";
}
//添加数据
modelAndView.addObject("tips", tips);
//添加视图
modelAndView.setViewName("addStudentResult");
return modelAndView;
}
/**
* 处理查询,这是一个ajax请求
*/
@RequestMapping(value = "queryStudent.do", method = RequestMethod.GET)
public List<StudentEntity> queryStudent() {
List<StudentEntity> studentEntities = studentService.findAllStudent();
return studentEntities;
}
}
5.8 编写前端页面
5.8.1 主页面:注册功能和浏览功能的页面:index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<%
String basePath = request.getScheme()
+ "://" + request.getServerName()
+ ":" + request.getServerPort()
+ request.getContextPath() + "/";
%>
<head>
<title>学生功能入口</title>
<base href="<%=basePath%>"/>
</head>
<body>
<div align="center">
<p>SSM整合的小例子</p>
<img src="WEB-INF/images/car.jpg"/>
<table>
<tr>
<td><a href="addStudent.jsp">注册学生</a></td>
</tr>
<tr>
<td><a href="queryStudent.jsp">浏览学生</a></td>
</tr>
</table>
</div>
</body>
</html>
5.8.2 点击主页面中“注册学生”时跳转到的注册页面:addStudent.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<%
String basePath = request.getScheme()
+ "://" + request.getServerName()
+ ":" + request.getServerPort()
+ request.getContextPath() + "/";
%>
<head>
<title>注册学生</title>
<head>
<base href="<%=basePath%>"/>
</head>
</head>
<body>
<div align="center">
<form action="student/addStudent.do" method="post">
<table>
<tr>
<td>姓名:</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>班级ID:</td>
<td><input type="text" name="classId"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="注册"></td>
</tr>
</table>
</form>
</div>
</body>
</html>
5.8.3 点击“注册页面”中的“注册”按钮时会执行超链接对应的处理器: student/addStudent.do
5.8.4 执行完“student/addStudent.do”中的“add”操作后会跳转到“注册成功”的页面: addStudentResult.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3 addStudentResult.jsp 结果页面,注册结果是:>${tips}</h3>
</body>
</html>
5.9 “注册学生”功能的测试与项目结构图
6、做一个queryStudent的业务逻辑
6.1 Controller层:StudentController.java
package com.wind.controller;
import com.wind.entity.StudentEntity;
import com.wind.service.StudentService;
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.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
@Controller
@ResponseBody
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentService studentService;
@RequestMapping(value = "addStudent.do", method = RequestMethod.POST)
public ModelAndView addStudent(StudentEntity studentEntity) {
//创建一个视图
ModelAndView modelAndView = new ModelAndView();
String tips = "注册失败,请稍后重试。";
int insertResult = studentService.insertStudent(studentEntity);
if (insertResult > 0) {
tips = "学生【" + studentEntity.getName() + "】注册成功。";
}
//添加数据
modelAndView.addObject("tips", tips);
//添加视图
modelAndView.setViewName("addStudentResult");
return modelAndView;
}
/**
* 处理查询,这是一个ajax请求
*/
@RequestMapping(value = "queryStudent.do", method = RequestMethod.GET)
public List<StudentEntity> queryStudent() {
List<StudentEntity> studentEntities = studentService.findAllStudent();
return studentEntities;
}
}
6.2 前端页面
6.2.1 “浏览学生”的主页面:index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<%
String basePath = request.getScheme()
+ "://" + request.getServerName()
+ ":" + request.getServerPort()
+ request.getContextPath() + "/";
%>
<head>
<title>学生功能入口</title>
<base href="<%=basePath%>"/>
</head>
<body>
<div align="center">
<p>SSM整合的小例子</p>
<img src="WEB-INF/images/car.jpg"/>
<table>
<tr>
<td><a href="addStudent.jsp">注册学生</a></td>
</tr>
<tr>
<td><a href="queryStudent.jsp">浏览学生</a></td>
</tr>
</table>
</div>
</body>
</html>
6.2.2 点击“浏览学生”按钮后进入的“学生数据列表页面”:queryStudent.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<%
String basePath = request.getScheme()
+ "://" + request.getServerName()
+ ":" + request.getServerPort()
+ request.getContextPath() + "/";
%>
<head>
<title>查询学生的ajax</title>
<head>
<base href="<%=basePath%>"/>
<script type="text/javascript" src="js/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(function () {
//(1)在当前页面的dom对象一加载,主动来执行加载数据的方法,这样就不用先点击再查询了
queryStudentData();
//(2)先点击查询按钮,再触发方法的执行来刷新新增的学生数据
$("#btnLoader").click(function () {
queryStudentData();
})
})
function queryStudentData() {
$.ajax({
url: "student/queryStudent.do",
type: "get",
dataType: "json",
success: function (date) {
// 测试的时候使用
// alert("date=" + date);
//先清除旧的数据
$("#info").html("");
//再增加新的数据
$.each(date, function (i, n) {
$("#info").append("<tr>")
.append("<td>" + n.id + "<td>")
.append("<td>" + n.name + "<td>")
.append("<td>" + n.classId + "<td>")
.append("<td>" + n.addTime + "<td>")
.append("</tr>");
})
}
})
}
</script>
</head>
</head>
<body>
<div align="center">
<table>
<thead>
<tr>
<td>学号</td>
<td>姓名</td>
<td>班级</td>
<td>注册时间</td>
</tr>
</thead>
<tbody id="info">
</tbody>
</table>
<input type="button" id="btnLoader" value="查询学生数据"/>
</div>
</body>
</html>
6.2.3 在“学生数据列表页面”可以点击“查需学生数据”来刷新该页面的新数据:queryStudent.jsp
因为该jsp文件中有对“按钮”的监听事件(监听方法),如下。
$(function () {
//(1)在当前页面的dom对象一加载,主动来执行加载数据的方法,这样就不用先点击再查询了
queryStudentData();
//(2)先点击查询按钮,再触发方法的执行来刷新新增的学生数据
$("#btnLoader").click(function () {
queryStudentData();
})
})
6.3 前端测试与项目结构图