springmvc–ssm整合开发
代码示例:
1.加入相关的依赖:
<?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</groupId>
<artifactId>ch07-ssm</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<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>
</properties>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2.1-b03</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
2.配置中央调度器,springmvc容器,spring监听器,spring容器,字符集过滤器(web.xml):
<?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">
<!--配置中央调度器-->
<servlet>
<servlet-name>myweb</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:conf/dispatcherServlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>myweb</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!--注册spring的监听器-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:conf/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--注册字符集过滤器-->
<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>
</web-app>
3.配置springmvc配置文件(dispatcherServlet.xml)
<?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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--声明组件扫描器-->
<context:component-scan base-package="com.controller"/>
<!--声明springmvc框架中的视图解析器,帮助开发人员设置视图文件的路径-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--有两个属性,一个是前缀,另外一个是后缀-->
<!--前缀:视图文件的路径,前面的‘/’代表根,后面的‘/’代表路径-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--后缀:表示视图文件的扩展名-->
<property name="suffix" value=".jsp"/>
</bean>
<!--mvc:resources和@RequestMapping有一定的冲突,需要加入注解驱动-->
<!--
1.响应ajax请求,返回json
2.解决静态资源的访问问题
-->
<mvc:annotation-driven/>
</beans>
3.数据库源配置文件(jdbc.properties):
jdbc.url=jdbd:mysql://localhost:3306/ssm
jdbc.username=root
jdbc.password=123456789qw
4.配置mybatis主配置文件(mybatis.xml):
<?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>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!--设置别名-->
<typeAliases>
<!--实体类所在的包名-->
<package name="com.domain"/>
</typeAliases>
<mappers>
<!--使用package包名,可以加载包中所有的mapper.xml文件
使用packkage的要求:
1.mapper文件名称和dao接口必须完全一样,包括大小写
2.mapper文件和dao接口必须在同一目录
-->
<package name="com.dao"/>
</mappers>
</configuration>
5.配置spring配置文件(applicationContext.xml):
<?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 https://www.springframework.org/schema/context/spring-context.xsd">
<!--spring配置文件:声明service,dao,工具类等对象-->
<!--指明数据库配置文件的位置-->
<context:property-placeholder location="classpath:conf/jdbc.properties"/>
<!--声明数据源,连接数据库-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--SqlSessionFactoryBean创建SqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:conf/mybatis.xml"/>
</bean>
<!--声明mybatis的扫描器,创建dao对象-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="com.dao"/>
</bean>
<!--开启注解扫描器,声明service的注解@Servcie所在包的位置-->
<context:component-scan base-package="com.service"/>
<!--事务的配置:注解的配置或者aspectJ配置-->
</beans>
6.创建实体类Student对应数据库的数据:
package com.domain;
public class Student {
private Integer id;
private String name;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
7.创建StudentDao:
package com.dao;
import com.domain.Student;
import java.util.List;
public interface StudentDao {
public int insertStudent(Student student);
public List<Student> selectStudents();
}
8.创建相应的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.dao.StudentDao">
<select id="selectStudents" resultType="com.domain.Student">
select id, name, age from student order by id desc
</select>
<insert id="insertStudent">
insert into student(name, age) values(#{name}, #{age})
</insert>
</mapper>
9.创建StudentService接口和实现类StudentServiceImpl:
package com.service;
import com.domain.Student;
import java.util.List;
public interface StudentService {
public int addStudent(Student student);
public List<Student> findStudents();
}
package com.service.impl;
import com.dao.StudentDao;
import com.domain.Student;
import com.service.StudentService;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import java.util.List;
@Service
public class StudentServiceImpl implements StudentService {
//自动注入
@Resource
private StudentDao studentDao;
@Override
public int addStudent(Student student) {
int res = studentDao.insertStudent(student);
return res;
}
@Override
public List<Student> findStudents() {
List<Student> students = studentDao.selectStudents();
return students;
}
}
10.创建控制器类StudentController:
package com.controller;
import com.domain.Student;
import com.service.StudentService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
@Controller
@RequestMapping(value = "/student")
public class StudentController {
@Resource
private StudentService studentService;
@RequestMapping(value = "/addStudent.do")
public ModelAndView addStudent(Student student){
String tips = "注册失败";
//调用service处理student
int res = studentService.addStudent(student);
if (res > 0 ){
//注册成功
tips ="学生 【" + student.getName() + "】 " + "注册成功";
}
ModelAndView mv = new ModelAndView();
//添加数据
mv.addObject("tips", tips);
//指定结果页面
mv.setViewName("result");
return mv;
}
}
11.创建结果页面result.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<p>result.jsp 结果页面,注册结果:${tips}</p>
</body>
</html>
12.创建前端页面index.jsp,里面有两个连接,分别对应了添加学生和查询学生:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String basepath = request.getScheme() + "://" +
request.getServerName() + ":" + request.getServerPort() +
request.getContextPath() + "/";
%>
<html>
<head>
<title>功能入口</title>
<base href="<%=basepath%>"/>
</head>
<body>
<div align="center">
<p>SSM整合的例子</p>
<img src="images/1.jpg"/>
<table>
<tr>
<td><a href="addStudent.jsp">注册学生</a> </td>
</tr>
<tr>
<td><a href="listStudent.jsp">浏览学生</a> </td>
</tr>
</table>
</div>
</body>
</html>
13.创建添加学生功能的页面addStudent.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String basepath = request.getScheme() + "://" +
request.getServerName() + ":" + request.getServerPort() +
request.getContextPath() + "/";
%>
<html>
<head>
<title>注册学生</title>
<base href="<%=basepath%>"/>
</head>
<body>
<div align="center">
<form action="student/addStudent.do" method="post">
<table>
<tr>
<td>姓名:</td>
<!--这里的name和age都必须和controller对象的形参一样-->
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>年龄:</td>
<td><input type="text" name="age"></td>
</tr>
<tr>// 代表空格
<td> </td>
<td><input type="submit" value="注册"></td>
</tr>
</table>
</form>
</div>
</body>
</html>
14.创建查询学生的页面listStudent.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String basepath = request.getScheme() + "://" +
request.getServerName() + ":" + request.getServerPort() +
request.getContextPath() + "/";
%>
<html>
<head>
<title>浏览学生</title>
<base href="<%=basepath%>">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(function (){
//在当前页面dom对象加载后,执行loadStudentData()
loadStudentData();
$("#btn").click(function (){
loadStudentData();
})
//定义ajax函数
function loadStudentData(){
$.ajax({
url:"student/queryStudent.do",
<!--不需要发送数据-->
type:"get",
dataType:"json",
success:function (data){
//清除旧的数据
$("#info").html("");
$.each(data, function (i, n){
//增加新的数据
$("#info").append("<tr>")
.append("<td>" + n.id + "<td>")
.append("<td>" + n.name + "<td>")
.append("<td>" + n.age + "<td>")
.append("<tr>")
})
}
})
}
})
</script>
</head>
<body>
<div align="center">
<table>//<thead>代表表头
<thead>
<tr>
<td>学号</td>
<td>姓名</td>
<td>年龄</td>
</tr>
</thead>
<tbody id="info">
</tbody>
</table>
<input type="button" id="btn" value="查询数据">
</div>
</body>
</html>