spring
Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One J2EE Development and Design中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。Spring使用基本的JavaBean来完成以前只可能由EJB完成的事情。然而,Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java应用都可以从Spring中受益。 简单来说,Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架。
springmvc
Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面。Spring MVC 分离了控制器、模型对象、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制。
mybatis
MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。MyBatis是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAO)MyBatis 消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。MyBatis 使用简单的 XML或注解用于配置和原始映射,将接口和 Java 的POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
案列演示
- 项目结构
- 在pom.xml文件中导入依赖jar
<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>ssm</groupId>
<artifactId>ssm</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>ssm</name>
<description/>
<properties>
<webVersion>3.1</webVersion>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- spring版本号 -->
<spring.version>4.0.2.RELEASE</spring.version>
<!-- mybatis版本号 -->
<mybatis.version>3.2.6</mybatis.version>
<!-- log4j日志文件管理包版本 -->
<slf4j.version>1.7.7</slf4j.version>
<log4j.version>1.2.17</log4j.version>
</properties>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.servlet.jsp.jstl</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<!-- 表示开发的时候引入,发布的时候不会加载此包 -->
<scope>test</scope>
</dependency>
<!-- spring核心包 -->
<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>
<!-- 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>
<!-- 导入java ee jar 包 -->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<!-- 导入Mysql数据库链接jar包 -->
<!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<!-- JSTL标签类 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- 日志文件管理包 -->
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<!-- 格式化对象,方便输出日志 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.41</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>
<!-- log end -->
<!-- 映入JSON -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</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>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
- web.xml文件的配置
<!-- Spring和mybatis的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mybatis.xml</param-value>
</context-param>
<!-- 编码过滤器 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<async-supported>true</async-supported>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 防止Spring内存溢出监听器 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!-- Spring MVC 前端控制器-->
<servlet>
<servlet-name>SpringMVC</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>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<!-- 此处可以可以配置成*.do,对应struts的后缀习惯 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
- jdbc.properties
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:orcl
username=scott
password=tiger
#\u5B9A\u4E49\u521D\u59CB\u8FDE\u63A5\u6570
initialSize=0
#\u5B9A\u4E49\u6700\u5927\u8FDE\u63A5\u6570
maxActive=20
#\u5B9A\u4E49\u6700\u5927\u7A7A\u95F2
maxIdle=20
#\u5B9A\u4E49\u6700\u5C0F\u7A7A\u95F2
minIdle=1
#\u5B9A\u4E49\u6700\u957F\u7B49\u5F85\u65F6\u95F4
maxWait=60000
- log4j.properties
#\u5B9A\u4E49LOG\u8F93\u51FA\u7EA7\u522B
log4j.rootLogger=INFO,Console,File
#\u5B9A\u4E49\u65E5\u5FD7\u8F93\u51FA\u76EE\u7684\u5730\u4E3A\u63A7\u5236\u53F0
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
#\u53EF\u4EE5\u7075\u6D3B\u5730\u6307\u5B9A\u65E5\u5FD7\u8F93\u51FA\u683C\u5F0F\uFF0C\u4E0B\u9762\u4E00\u884C\u662F\u6307\u5B9A\u5177\u4F53\u7684\u683C\u5F0F
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n
#\u6587\u4EF6\u5927\u5C0F\u5230\u8FBE\u6307\u5B9A\u5C3A\u5BF8\u7684\u65F6\u5019\u4EA7\u751F\u4E00\u4E2A\u65B0\u7684\u6587\u4EF6
log4j.appender.File = org.apache.log4j.RollingFileAppender
#\u6307\u5B9A\u8F93\u51FA\u76EE\u5F55
log4j.appender.File.File = logs/ssm.log
#\u5B9A\u4E49\u6587\u4EF6\u6700\u5927\u5927\u5C0F
log4j.appender.File.MaxFileSize = 10MB
# \u8F93\u51FA\u6240\u4EE5\u65E5\u5FD7\uFF0C\u5982\u679C\u6362\u6210DEBUG\u8868\u793A\u8F93\u51FADEBUG\u4EE5\u4E0A\u7EA7\u522B\u65E5\u5FD7
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
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:p="http://www.springframework.org/schema/p"
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-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
<context:component-scan base-package="com.it" />
<!--避免IE执行AJAX时,返回JSON出现下载文件 -->
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 -->
</list>
</property>
</bean>
<!-- 定义跳转的文件的前后缀 ,视图模式配置-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 默认编码 -->
<property name="defaultEncoding" value="utf-8" />
<!-- 文件大小最大值 -->
<property name="maxUploadSize" value="10485760000" />
<!-- 内存中的最大值 -->
<property name="maxInMemorySize" value="40960" />
</bean>
</beans>
- spring-mybatis.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:p="http://www.springframework.org/schema/p"
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-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 引入配置文件 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:jdbc.properties" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${driver}" />
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
<!-- 初始化连接大小 -->
<property name="initialSize" value="${initialSize}"></property>
<!-- 连接池最大数量 -->
<property name="maxActive" value="${maxActive}"></property>
<!-- 连接池最大空闲 -->
<property name="maxIdle" value="${maxIdle}"></property>
<!-- 连接池最小空闲 -->
<property name="minIdle" value="${minIdle}"></property>
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="${maxWait}"></property>
</bean>
<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描mapping.xml文件 -->
<property name="mapperLocations" value="classpath:com/it/mapper/*.xml"></property>
</bean>
<!-- DAO接口所在包名,Spring会自动查找其下的类,由spring代为产生StudentMapper代理类。 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.it.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
<!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
- student实体bean
package com.it.bean;
public class Student {
private String stu_id;
private String stu_name;
private String stu_sex;
private String stu_birth;
private String stu_addr;
public String getStu_id() {
return stu_id;
}
public void setStu_id(String stu_id) {
this.stu_id = stu_id;
}
public String getStu_name() {
return stu_name;
}
public void setStu_name(String stu_name) {
this.stu_name = stu_name;
}
public String getStu_sex() {
return stu_sex;
}
public void setStu_sex(String stu_sex) {
this.stu_sex = stu_sex;
}
public String getStu_birth() {
return stu_birth;
}
public void setStu_birth(String stu_birth) {
this.stu_birth = stu_birth;
}
public String getStu_addr() {
return stu_addr;
}
public void setStu_addr(String stu_addr) {
this.stu_addr = stu_addr;
}
public Student(String stu_id, String stu_name, String stu_sex, String stu_birth, String stu_addr) {
super();
this.stu_id = stu_id;
this.stu_name = stu_name;
this.stu_sex = stu_sex;
this.stu_birth = stu_birth;
this.stu_addr = stu_addr;
}
public Student() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "Student [stu_id=" + stu_id + ", stu_name=" + stu_name + ", stu_sex=" + stu_sex + ", stu_birth=" + stu_birth
+ ", stu_addr=" + stu_addr + "]";
}
}
- studentdao
package com.it.dao;
import java.util.List;
import com.it.bean.Student;
public interface StudentDao {
//根据id查找用户
public Student findById(String id);
//查询所有用户
public List<Student> findAll();
//分页查找
public List<Student> findBySplit(int offset,int limit);
//根据id删除用户
public void delete(String id);
//添加用户
public void insert(Student stu);
//修改用于
public void update(Student stu);
}
-StudentMapper.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.it.dao.StudentDao">
<!-- 根据id查找用户 -->
<select id="findById" parameterType="java.lang.String" resultType="com.it.bean.Student">
select * from stuInfo where stu_id=#{id}
</select>
<!-- 查找所有用户 -->
<select id="findAll" resultType="com.it.bean.Student">
select * from stuInfo
</select>
<!-- 分页显示用户 -->
<select id="findBySplit" resultType="com.it.bean.Student">
select tt.stu_id,tt.stu_name,tt.stu_sex,tt.stu_birth,tt.stu_addr
from (select t.*,rownum rownu from stuInfo t
where rownum<=#{param1}*#{param2})tt
where tt.rownu>(#{param1}-1)*#{param2}
</select>
<!-- 删除用户 -->
<delete id="delete" parameterType="String">
delete from stuInfo where stu_id=#{id}
</delete>
<!-- 添加用户 -->
<insert id="insert" parameterType="com.it.bean.Student">
insert into stuInfo values(#{stu_id},#{stu_name},#{stu_sex},#{stu_birth},#{stu_addr})
</insert>
<!-- 修改用户 -->
<update id="update" parameterType="com.it.bean.Student">
update stuInfo set stu_name=#{stu_name},stu_sex=#{stu_sex},stu_birth=#{stu_birth},stu_addr=#{stu_addr} where stu_id=#{stu_id}
</update>
</mapper>
- studenservice
package com.it.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
//import javax.transaction.Transactional;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.it.bean.Student;
import com.it.dao.StudentDao;
@Service
public class StudentService {
@Autowired
private StudentDao studao;
/**
* 修改用户
* @param stu
*/
@Transactional
public void update(Student stu){
studao.update(stu);
}
/**
* 添加用户
* @param stu
*/
@Transactional
public void insert(Student stu){
studao.insert(stu);
}
/**
* 根据id删除用户
* @param id
*/
@Transactional
public void delete(String id){
studao.delete(id);
}
/**
* 根据id查找
* @param id
* @return
*/
@Transactional
public Student findById(String id){
System.out.println(id+"====studentService====");
return studao.findById(id);
}
/**
* 查询所有
* @return
*/
public List<Student> findAll(){
return studao.findAll();
}
/**
* 分页搜索
* @param offset 当前页数
* @param limit 每页记录数
* @return
*/
public List<Student> findBySplit(int offset,int limit){
return studao.findBySplit(offset, limit);
}
public StudentDao getStudao() {
return studao;
}
public void setStudao(StudentDao studao) {
this.studao = studao;
}
}
-studentController
package com.it.controller;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
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 com.it.bean.Student;
import com.it.service.StudentService;
@Controller
public class StudentController {
@Autowired
private StudentService stusv;
/**
* 根据id查找用户
* @param id
* @return
*/
@RequestMapping(value="/findbyid.do")
public String findById(String stu_id,HttpServletRequest request,Map<String,Object> map){
System.out.println(stu_id);
Student stu=stusv.findById(stu_id);
request.setAttribute("stu", stu);
System.out.println(stu.toString());
/*map.put("stu_id",stu_id);
map.put("flag","1");
map.put("student",new Student("1","1","1","1","1"));*/
return "update";
}
@RequestMapping(value="/findAll.do",method=RequestMethod.GET)
public String findAll(HttpServletRequest request){
List<Student> list=stusv.findAll();
request.setAttribute("list",list);
//return "forward:/WEB-INF/views/index.jsp";
return "index";
}
/**
* 分页搜素
* @param request
* @param session 存放当前页数 页数大小
* @param flag 1为上一页 2为下一页
* @return
*/
@RequestMapping(value="/findbysplit.do")
public String findBySplit(HttpServletRequest request,HttpSession session,String flag){
String offset=(String) session.getAttribute("offset");
if(offset==null){
offset="1";
}
String limit=(String) session.getAttribute("limit");
if(limit==null){
limit="5";
}
// String flag=(String) request.getAttribute("flag");
if(flag==null){
flag="0";
}
// System.out.println("offset"+offset+"=======limit"+limit+"=======flag"+flag);
int offset1=Integer.parseInt(offset);
int limit1=Integer.parseInt(limit);
if(flag.equals("1")){
offset1--;
if(offset1<=1){
offset1=1;
}
limit1=5;
}else if(flag.equals("2")){
offset1++;
limit1=5;
}else{
offset1=1;
limit1=5;
}
List<Student> list=stusv.findBySplit(offset1, limit1);
offset=offset1+"";
limit=limit1+"";
session.setAttribute("offset",offset);
session.setAttribute("limit",limit);
request.setAttribute("list",list);
//return "forward:/WEB-INF/views/index.jsp";
return "index";
}
/**
* 删除用户
* @param stu_id
* @return
*/
@RequestMapping(value="/delete.do")
public String delete(String stu_id){
System.out.println(stu_id+"=========");
stusv.delete(stu_id);
return "redirect:/findbysplit.do";
}
/**
* 添加用户
* @param request
* @return
*/
@RequestMapping(value="/insert.do")
public String insert(Student stu){
//Student stu=new Student(stu_id, stu_name, stu_sex, stu_birth, stu_addr);
System.out.println(stu.toString());
stusv.insert(stu);
return "redirect:/findbysplit.do";
}
@RequestMapping(value="/update.do")
public String update(Student stu){
// Student stu=new Student(stu_id, stu_name, stu_sex, stu_birth, stu_addr);
stusv.update(stu);
return "redirect:/findbysplit.do";
}
public StudentService getStusv() {
return stusv;
}
public void setStusv(StudentService stusv) {
this.stusv = stusv;
}
}
-界面自己随便了,这理解不写出了,这样一个简单的ssm框架整合变完成了