SSM整合
环境配置
要手动导的包很多,还是maven好啊…
db.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?serverTimezone=Hongkong
jdbc.username=root
jdbc.password=cyt19880818
web.xml 配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>ssm</display-name>
<!-- Spring 配置 -->
<!-- needed for ContextLoaderListener -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- Bootstraps the root web application context before servlet initialization -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring MVC配置 -->
<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 字符编码过滤器 -->
<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>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- REST 过滤器 -->
<filter>
<filter-name>hiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
SpringMVC配置
spring-mvc.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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
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.3.xsd">
<!-- 组件扫描 -->
<context:component-scan base-package="com.cyt.ssm" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 视图解析器 -->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<mvc:default-servlet-handler/>
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
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"
xmlns:tx="http://www.springframework.org/schema/tx"
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.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 组件扫描 -->
<context:component-scan base-package="com.cyt.ssm">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 数据源 -->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 事务 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
Spring 整合Mybatis
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"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
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.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 组件扫描 -->
<context:component-scan base-package="com.cyt.ssm">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 数据源 -->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 事务 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- Spring 整合 Mybatis -->
<!-- Mybatis的SqlSession的创建 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- Mybatis全局配置文件 -->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<!-- 数据源 -->
<property name="dataSource" ref="dataSource"></property>
<!-- Mybatis的SQL映射文件 -->
<property name="mapperLocations" value="classpath:com/cyt/ssm/mapper/*.xml"></property>
<!-- <property name="typeAliasesPackage" value=""></property> -->
</bean>
<!-- MyBatis的数据接口的代理实现类 -->
<mybatis-spring:scan base-package="com.cyt.ssm.dao"/>
</beans>
在文件中添加 <!-- Spring 整合 Mybatis --> 部分
mybatis-config.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="mapUnderscoreToCamelCase" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
</configuration>
案例
Dao基本实现
Goods.java
public class Goods {
private Integer goodsId;
private String name;
private Integer price;
private Integer quantity;
GoodsDao.java
public interface GoodsDao {
public Goods getGoodsById(Integer id);
public void update(Goods goods);
public List<Goods> getAllGoods();
}
GoodsMapper.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.cyt.ssm.dao.GoodsDao">
<!-- public Goods getGoodsById(Integer id); -->
<select id="getGoodsById" resultType="com.cyt.ssm.bean.Goods">
select * from tbl_goods
where goods_id=#{id};
</select>
<!-- public void update(Goods goods); -->
<select id="update">
update tbl_goods set name=#{name}, price=#{price}, quantity=#{quantity}
where goods_id=#{goodsId};
</select>
<!-- public List<Goods> getAllGoods(); -->
<select id="getAllGoods" resultType="com.cyt.ssm.bean.Goods">
select * from tbl_goods;
</select>
</mapper>
Junit Test
class GoodsDaoTest {
private SqlSession session;
private ConfigurableApplicationContext context;
@BeforeEach
public void Init() {
context = new ClassPathXmlApplicationContext("applicationContext.xml");
SqlSessionFactory factory = context.getBean("sqlSessionFactory",SqlSessionFactory.class);
session = factory.openSession();
}
@AfterEach
public void close() {
context.close();
}
// 测试查询单个
@Test
void testGetGoodsById() {
try {
System.out.println(session);
GoodsDao dao = session.getMapper(GoodsDao.class);
Goods goods = dao.getGoodsById(101);
System.out.println(goods);
} catch (Exception e) {
session.close();
}
}
// 测试查询多个
@Test
void testGetAllGoods() {
try {
System.out.println(session);
GoodsDao dao = session.getMapper(GoodsDao.class);
List<Goods> goods = dao.getAllGoods();
System.out.println(goods);
} catch (Exception e) {
session.close();
}
}
// 测试更新
@Test
void testUpdate() {
try {
System.out.println(session);
GoodsDao dao = session.getMapper(GoodsDao.class);
Goods goods = new Goods(101, "Nike", 55, 14);
dao.update(goods);
} catch (Exception e) {
session.close();
}
}
}
List实现
GoodsController.java
package com.cyt.ssm.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.cyt.ssm.bean.Goods;
import com.cyt.ssm.service.GoodsService;
@Controller
@RequestMapping("/goods")
public class GoodsController {
@Autowired
private GoodsService service;
@GetMapping("/list")
public String list(Model model) {
List<Goods> goods = service.getAllGoods();
model.addAttribute("goods",goods);
return "goodsList";
}
}
GoodsService.java
@Service
public class GoodsService {
@Autowired
private GoodsDao dao;
public List<Goods> getAllGoods(){
return dao.getAllGoods();
}
}
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>LALALALA</title>
</head>
<body>
<a href="${pageContext.request.contextPath }/goods/list">Go to List Page</a>
</body>
</html>
goodsList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Good List</title>
</head>
<body>
<h4>Goods List Page</h4>
<table border="1" cellspacing="0" cellpadding="3">
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Update</th>
<th>Delete</th>
</tr>
<c:forEach items="${requestScope.goods }" var="g">
<tr>
<td>${g.goodsId }</td>
<td>${g.name }</td>
<td>${g.price }</td>
<td>${g.quantity }</td>
<td><a href="${pageContext.request.contextPath }/goods/edit/${g.goodsId }">Update</a></td>
<td>delete</td>
</tr>
</c:forEach>
</table>
</body>
</html>
Edit 实现
goodsEdit.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Goods Edit</title>
</head>
<body>
<h4>Good Edit Page</h4>
<form:form modelAttribute="goods" action="${pageContext.request.contextPath }/goods/update"
method="post">
<form:hidden path="goodsId"/>
<input type="hidden" name="_method" value="put"/>
Name: ${requestScope.goods.name }<br><br>
Price: <form:input path="price"/><br><br>
Quantity: <form:input path="quantity"/><br><br>
<input type="submit" value="Submit">
</form:form>
</body>
</html>
GoodsController.java 添加 public String edit(@PathVariable("id") Integer id,Model model)
package com.cyt.ssm.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import com.cyt.ssm.bean.Goods;
import com.cyt.ssm.service.GoodsService;
@Controller
@RequestMapping("/goods")
public class GoodsController {
@Autowired
private GoodsService service;
@GetMapping("/list")
public String list(Model model) {
List<Goods> goods = service.getAllGoods();
model.addAttribute("goods",goods);
return "goodsList";
}
@GetMapping("/edit/{id}")
public String edit(@PathVariable("id") Integer id,Model model) {
Goods goods = service.getGoodsById(id);
model.addAttribute("goods", goods);
return "goodsEdit";
}
}
Update实现
在 GoodsService.java 中添加 updateGoods
@Service
public class GoodsService {
@Autowired
private GoodsDao dao;
public List<Goods> getAllGoods(){
return dao.getAllGoods();
}
public Goods getGoodsById(Integer id) {
return dao.getGoodsById(id);
}
public void updateGoods(Goods goods) {
dao.update(goods);
}
}
在 GoodsController.java 中添加 prepareModel 和 update
@Controller
@RequestMapping("/goods")
public class GoodsController {
......
@ModelAttribute
public void prepareModel(@RequestParam(value = "goodsId", required = false)Integer id,HttpServletRequest request,
Model model) {
String servletPath = request.getServletPath();
if (servletPath.equals("/goods/update")) {
Goods goods = service.getGoodsById(id);
model.addAttribute("goods", goods);
}
}
@PutMapping("/update")
public String update(Goods goods) {
// System.out.println(goods);
service.updateGoods(goods);
return "redirect:/goods/list";
}
}
如同SpringMVC中讲过的 @ModelAttribute,可以在控制器执行之前对数据做预装载
注意事项
- 使用REST风格开发时,发送的请求url中含有所需数据的,可以用 @PathVariable 取出,@Pa thVariable(“id”) 中的 id 和 @GetMapping("/edit/{id}") 中的 id 对应
例如
@GetMapping("/edit/{id}")
public String edit(@PathVariable("id") Integer id,Model model) {
Goods goods = service.getGoodsById(id);
model.addAttribute("goods", goods);
return "goodsEdit";
}
- 请求类型的转换
在这个例子中需要对post请求转换成put请求,故使用 <input type="hidden" name="_method" value="put"/>
<form:form modelAttribute="goods" action="${pageContext.request.contextPath }/goods/update"
method="post">
<form:hidden path="goodsId"/>
<input type="hidden" name="_method" value="put"/>
Name: ${requestScope.goods.name }<br><br>
Price: <form:input path="price"/><br><br>
Quantity: <form:input path="quantity"/><br><br>
<input type="submit" value="Submit">
</form:form>
起作用的 HiddenHttpMethodFilter 过滤器:
web.xml
<!-- REST 过滤器 -->
<filter>
<filter-name>hiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
- 使用@ModelAttribute准备模型数据:
在用户的页面中有时候不能把需要的数据显示出来,故需要用hidden的一些标签,但如此过于繁琐,可以用@ModelAttribute在方法中把模型数据获取,进行操作后得到完成的对象数据等在往下进行。