SSM整合(SSM的简单整合、逆向工程、分页插件的使用)
1.SSM整合初体验
1.导包:
1).Spring
a.IOC核心包
- commons-logging-1.1.3.jar
- spring-aop-4.0.0.RELEASE.jar
- spring-beans-4.0.0.RELEASE.jar
- spring-context-4.0.0.RELEASE.jar
- spring-core-4.0.0.RELEASE.jar
- spring-expression-4.0.0.RELEASE.jar
b.jdbc核心包
- spring-jdbc-4.0.0.RELEASE.jar
- spring-orm-4.0.0.RELEASE.jar
- spring-tx-4.0.0.RELEASE.jar
c.测试核心包
- spring-test-4.0.0.RELEASE.jar
d.aop核心包
- com.springsource.net.sf.cglib-2.2.0.jar
- com.springsource.org.aopalliance-1.0.0.jar
- com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
- spring-aspects-4.0.0.RELEASE.jar
2).SpringMVC
a.SpringMVC核心
- spring-web-4.0.0.RELEASE.jar
- spring-webmvc-4.0.0.RELEASE.jar
b.上传下载
- commons-fileupload-1.2.1.jar
- commons-io-2.0.jar
c.jstl-jsp标准标签库
- jstl.jar
- standard.jar
d.数据校验
- hibernate-validator-5.0.0.CR2.jar
- hibernate-validator-annotation-processor-5.0.0.CR2.jar
e.ajax
- jackson-annotations-2.1.5.jar
- jackson-core-2.1.5.jar
- jackson-databind-2.1.5.jar
3).MyBatis
a.核心包
- mybatis-3.4.1.jar
b.ehcache整合
- ehcache-core-2.6.8.jar
- mybatis-ehcache-1.0.3.jar
- log4j-1.2.17.jar
- slf4j-api-1.6.1.jar
- slf4j-log4j12-1.6.2.jar
4).其他的包
a.数据源
- mysql-connector-java-8.0.17.jar
- c3p0-0.9.5.2.jar
- mchange-commons-java-0.2.12.jar
b.spring与mybatis的整合包
- mybatis-spring-1.3.0.jar
2.写配置
0).web.xml配置
代码示例:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>SSM_01</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 配置spring容器启动 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- 指定spring配置文件路径 -->
<param-value>class:spring/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>
<!-- 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>class:spring/applicationContext-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!--配置前端控制器-->
<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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</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>
1).Spring配置
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.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.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<context:component-scan base-package="com.luyi">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 导入配置文件 -->
<context:property-placeholder location="classpath:dbconfig.properties"/>
<!-- 配数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="driverClass" value="${jdbc.driverclass}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcurl}"></property>
</bean>
<!-- 配置使用mybatis操作数据库 -->
<!-- 可以根据配置文件得到sqlSession -->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property>
<!-- 注意:这里的name值对应的是ref,不是value,写成value的话,就有可能一路报错 -->
<property name="dataSource" ref="dataSource"></property>
<property name="mapperLocations" value="classpath:mybatis/dao/*.xml"></property>
</bean>
<!-- 我们要把每一个dao接口的实现加入到ioc容器中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 指定dao接口所在的包 -->
<property name="basePackage" value="com.luyi.dao"></property>
</bean>
<!-- 配置事务控制,配置事务管理器,让他控制住数据源里面的链接的关闭和提交 -->
<bean id="tm" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 基于xml配置,配置事务,哪些方法切入事务要写切入点表达式 -->
<aop:config>
<!-- 配置切入点表达式 -->
<aop:pointcut expression="execution(* com.lui.service.*.*(..))" id="txPoint"/>
<aop:advisor advice-ref="myTx" pointcut-ref="txPoint"/>
</aop:config>
<!-- 配置事务增强 (事务属性,事务建议)
transaction-manager="tm":指定要配置的事务管理器的id
-->
<tx:advice id="myTx" transaction-manager="tm">
<tx:attributes>
<tx:method name="*" rollback-for="java.lang.Exception"/>
<tx:method name="get*" read-only="true"/>
</tx:attributes>
</tx:advice>
</beans>
2).SpringMVC配置
代码示例:
<?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.0.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.0.xsd">
<!-- 配置springMVC容器只扫描Controller组件 -->
<context:component-scan base-package="com.luyi" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB_INF/page/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 配置文件上传解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<property name="maxUploadSize" value="#{1024*1024*20}"></property>
</bean>
<!-- 扫描静态资源 -->
<mvc:default-servlet-handler/>
<!-- 扫描动态资源 -->
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
3).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>
<!-- 开启延迟加载 -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 开启属性按需加载 -->
<setting name="aggressiveLazyLoading" value="false"/>
<setting name="cacheEnabled" value="true"/>
</settings>
</configuration>
SQL映射配置文件:
<?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.luyi.dao.TeacherDao">
<select id="getTeacherById" resultType="com.luyi.bean.Teacher">
select * from teacher where id = #{id}
</select>
</mapper>
4).其他小框架的 配置
properties配置sql连接:
jdbc.username=root
jdbc.password=123
jdbc.jdbcurl=jdbc:mysql://localhost:3306/my?serverTimezone=UTC
jdbc.driverclass=com.mysql.cj.jdbc.Driver
log4j.xml文件:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Encoding" value="UTF-8" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
</layout>
</appender>
<logger name="java.sql">
<level value="debug" />
</logger>
<logger name="org.apache.ibatis">
<level value="info" />
</logger>
<root>
<level value="debug" />
<appender-ref ref="STDOUT" />
</root>
</log4j:configuration>
3.测试
为了完成我们对ssm整合的测试除了以上的配置文件以外,还需要一些环境的搭建:
数据库的设计(只有一个表):
与数据库对应的POJO:
//Teacher.java
package com.luyi.bean;
import java.util.Date;
public class Teacher{
private Integer id;
private String teacherName;
private String address;
private Date birth;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTeacherName() {
return teacherName;
}
public void setTeacherName(String teacherName) {
this.teacherName = teacherName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
@Override
public String toString() {
return "Teacher [id=" + id + ", teacherName=" + teacherName
+ ", address=" + address + ", birth=" + birth + "]";
}
}
提供操作数据库的接口:
//TeacherDao.java
package com.luyi.dao;
import com.luyi.bean.Teacher;
public interface TeacherDao {
public Teacher getTeacherById(Integer id);
}
操作数据库的文件:
//TeacherService.java
package com.luyi.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.luyi.bean.Teacher;
import com.luyi.dao.TeacherDao;
@Service
public class TeacherService {
@Autowired
private TeacherDao teacherDao;
public Teacher getTeacher(Integer id) {
Teacher t = teacherDao.getTeacherById(id);
return t;
}
}
控制请求转发的文件:
//TeacherController.java
package com.luyi.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.luyi.bean.Teacher;
import com.luyi.service.TeacherService;
@Controller
public class TeacherController {
@Autowired
TeacherService teacherService;
@RequestMapping("/getTeacher")
public String getTeacher(@RequestParam(value="id", defaultValue="1")Integer id, Model model){
Teacher t = teacherService.getTeacher(id);
model.addAttribute("teacher", t);
return "success";
}
}
请求发起后的成功页面:
// /WEB-INF/page/success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>SUCCESS</h1>
<h2>${teacher}</h2>
</body>
</html>
环境部署好了,那我们就开始测试吧!测试文件(index.jsp):
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="getTeacher?id=1">获取教师信息</a>
</body>
</html>
2.MBG
概述:MBG,全称为MyBatis Generator,也就是MyBatis的代码生成器,通过这个生成器,可以帮我们生成代码,缩短开发时间,这个过程被称为逆向工程何为逆向工程呢?逆向工程就是根据数据库表,逆向分析数据表,自动生成javaBean,dao接口,SQL映射等文件,而正向工程就是我们平时开发时的做法,根据数据表,创建对应的javaBean,然后写dao接口等等
MBG实现的步骤
- 导包
- 写配置
- 生成代码
代码实现:
1.导包:mybatis-generator-core-1.3.2.jar
2.写配置
//mbg.xml
<?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>
<!-- targetRuntime配置生成的dao接口里面的方法是简单的增删改查,还是有比较复杂的增删改查 -->
<context id="DB2Tables" targetRuntime="MyBatis3Simple">
<!-- 用于连接数据库的配置 -->
<jdbcConnection
driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/my?serverTimezone=UTC"
userId="root"
password="123">
</jdbcConnection>
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 生成POJO,targetProjec放在哪个包下 -->
<javaModelGenerator targetPackage="com.luyi.bean" targetProject=".\src">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- sql映射文件生成器,指定xml生成的地方 -->
<sqlMapGenerator targetPackage="com.luyi.dao" targetProject=".\conf">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- 用于生成dao接口的配置 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.luyi.dao" targetProject=".\src">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 指定生成哪张数据表 -->
<table tableName="teacher" domainObjectName="Teacher" >
</table>
</context>
</generatorConfiguration>
3.通过写java代码生成代码:
//MBGTest.java
package com.luyi.test;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;
public class MBGTest {
public static void main(String[] args) throws IOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("mbg.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
System.out.println("代码生成了");
}
}
3.分页插件的使用
使用步骤
1.导包
- pagehelper-5.1.0.jar
- jsqlparser-1.0.jar
2.写配置
在mybatis-config.xml追加一个插件配置:
<plugins>
<!-- com.github.pagehelper为PageHelper类所在包名 -->
<plugin interceptor="com.github.pagehelper.PageInterceptor">
</plugin>
</plugins>
3.测试:
在我们的第一个SSM整合文件中进行一些小修改即可完成我们的测试:
dao包下的文件:
package com.luyi.dao;
import java.util.List;
import com.luyi.bean.Teacher;
public interface TeacherDao {
public Teacher getTeacherById(Integer id);
public List<Teacher> getAll();
}
service包下的文件:
package com.luyi.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.luyi.bean.Teacher;
import com.luyi.dao.TeacherDao;
@Service
public class TeacherService {
@Autowired
private TeacherDao teacherDao;
public Teacher getTeacher(Integer id) {
Teacher t = teacherDao.getTeacherById(id);
return t;
}
public List<Teacher> getAll() {
return teacherDao.getAll();
}
}
controller包下的文件:
package com.luyi.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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.luyi.bean.Teacher;
import com.luyi.service.TeacherService;
@Controller
public class TeacherController {
@Autowired
TeacherService teacherService;
@RequestMapping("/getTeacher")
public String getTeacher(@RequestParam(value="id", defaultValue="1")Integer id, Model model){
Teacher t = teacherService.getTeacher(id);
model.addAttribute("teacher", t);
return "success";
}
@RequestMapping("/getAllTeachers")
public String getAllTeacher(@RequestParam(value="pn", defaultValue="1") Integer pn, Model model){
//紧跟他的查询就是一个分页查询
PageHelper.startPage(pn, 5);
List<Teacher> list = teacherService.getAll();
//我们可以把我们的查询结果放在pageinfo中的,这个pageInfo对象就有非常多的方法供我们使用
PageInfo<Teacher> info = new PageInfo<>(list, 6);
System.out.println(info.getPageNum());
System.out.println(info.getPageSize());
model.addAttribute("info", info);
return "success";
}
}
success.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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>SUCCESS</h1>
<h2>${teacher}</h2>
<table cellpadding="5" cellspacing="0" border="1">
<tr>
<td>id</td>
<td>teacherName</td>
<td>address</td>
<td>birth</td>
</tr>
<c:forEach items="${info.list}" var="teacher">
<tr>
<td>${teacher.id}</td>
<td>${teacher.teacherName}</td>
<td>${teacher.address}</td>
<td>${teacher.birth}</td>
</tr>
</c:forEach>
<tr>
<td colspan="4">
<a href="getAllTeachers?pn=1">首页</a><a href="getAllTeachers?pn=${info.prePage}">上一页</a>
<c:forEach items="${info.navigatepageNums}" var="number">
<a href="getAllTeachers?pn=${number}">${number}</a>
</c:forEach>
<a href="getAllTeachers?pn=${info.nextPage}">下一页</a>
</td>
</tr>
</table>
</body>
</html>
index.jsp(测试文件,程序入口):
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="getTeacher?id=1">获取教师信息</a>
<a href="getAllTeachers?pn=1">获取所有老师的信息</a>
</body>
</html>
作者:卢一
出处:http://www.cnblogs.com/luyi001/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。