1.开发环境搭建以及创建Maven Web项目
参看之前的博文:http://www.cnblogs.com/cainiaomahua/p/6306476.html
2.SSM整合
这次整合有2个配置文件,分别是spring-mybatis.xml,包含spring和mybatis的配置文件,还有个是spring-mvc的配置文件,此外有2个资源文件:jdbc.propertis和log4j.properties。
完整目录结构如下:
使用框架的版本:
Spring 4.0.2 RELEASE
Spring MVC 4.0.2 RELEASE
MyBatis 3.2.6
2.1 Maven引入需要的JAR包
在pom.xml中引入jar包(此处引入jar包,可以复制代码,也可以使用视图的方式,参考此链接:http://www.360doc.com/content/14/0517/18/9560593_378558295.shtml)
1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
3 <modelVersion>4.0.0</modelVersion>
4 <groupId>org.storm</groupId>
5 <artifactId>storm</artifactId>
6 <version>0.0.1-SNAPSHOT</version>
7 <name>storm</name>
8 <url>http://maven.apache.org</url>
9
10 <properties>
11 <!-- Spring版本号 -->
12 <spring.version>4.0.2.RELEASE</spring.version>
13 <!-- mybatis版本号 -->
14 <mybatis.version>3.2.6</mybatis.version>
15 <!-- log4j日志文件管理包版本 -->
16 <slf4j.version>1.7.7</slf4j.version>
17 <log4j.version>1.2.17</log4j.version>
18 </properties>
19
20 <dependencies>
21 <dependency>
22 <groupId>junit</groupId>
23 <artifactId>junit</artifactId>
24 <version>4.11</version>
25 <!-- 表示开发的时候引入,发布的时候不会加载此包 -->
26 <scope>test</scope>
27 </dependency>
28
29 <!-- Spring核心包 -->
30 <dependency>
31 <groupId>org.springframework</groupId>
32 <artifactId>spring-core</artifactId>
33 <version>4.0.2.RELEASE</version>
34 </dependency>
35 <dependency>
36 <groupId>org.springframework</groupId>
37 <artifactId>spring-web</artifactId>
38 <version>4.0.2.RELEASE</version>
39 </dependency>
40 <dependency>
41 <groupId>org.springframework</groupId>
42 <artifactId>spring-oxm</artifactId>
43 <version>4.0.2.RELEASE</version>
44 </dependency>
45 <dependency>
46 <groupId>org.springframework</groupId>
47 <artifactId>spring-tx</artifactId>
48 <version>4.0.2.RELEASE</version>
49 </dependency>
50 <dependency>
51 <groupId>org.springframework</groupId>
52 <artifactId>spring-jdbc</artifactId>
53 <version>4.0.2.RELEASE</version>
54 </dependency>
55 <dependency>
56 <groupId>org.springframework</groupId>
57 <artifactId>spring-webmvc</artifactId>
58 <version>4.0.2.RELEASE</version>
59 </dependency>
60 <dependency>
61 <groupId>org.springframework</groupId>
62 <artifactId>spring-aop</artifactId>
63 <version>4.0.2.RELEASE</version>
64 </dependency>
65 <dependency>
66 <groupId>org.springframework</groupId>
67 <artifactId>spring-context-support</artifactId>
68 <version>4.0.2.RELEASE</version>
69 </dependency>
70 <dependency>
71 <groupId>org.springframework</groupId>
72 <artifactId>spring-test</artifactId>
73 <version>4.0.2.RELEASE</version>
74 </dependency>
75
76 <!-- mybatis核心包 -->
77 <dependency>
78 <groupId>org.mybatis</groupId>
79 <artifactId>mybatis</artifactId>
80 <version>3.2.6</version>
81 </dependency>
82
83 <!-- mybatis/spring包 -->
84 <dependency>
85 <groupId>org.mybatis</groupId>
86 <artifactId>mybatis-spring</artifactId>
87 <version>1.2.2</version>
88 </dependency>
89
90 <!-- 引入java ee jar 包 -->
91 <dependency>
92 <groupId>javax</groupId>
93 <artifactId>javaee-api</artifactId>
94 <version>7.0</version>
95 </dependency>
96
97 <!-- 导入oracle包 -->
98 <dependency>
99 <groupId>com.oracle</groupId>
100 <artifactId>ojdbc</artifactId>
101 <version>6</version>
102 </dependency>
103
104 <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
105 <dependency>
106 <groupId>commons-dbcp</groupId>
107 <artifactId>commons-dbcp</artifactId>
108 <version>1.2.2</version>
109 </dependency>
110
111 <!-- JSTL标签类 -->
112 <dependency>
113 <groupId>jstl</groupId>
114 <artifactId>jstl</artifactId>
115 <version>1.2</version>
116 </dependency>
117
118 <!-- 日志文件管理包 -->
119 <!-- log start -->
120 <dependency>
121 <groupId>log4j</groupId>
122 <artifactId>log4j</artifactId>
123 <version>1.2.17</version>
124 </dependency>
125
126 <!-- 格式化对象,方便输出日志 -->
127 <dependency>
128 <groupId>com.alibaba</groupId>
129 <artifactId>fastjson</artifactId>
130 <version>1.1.41</version>
131 </dependency>
132 <dependency>
133 <groupId>org.slf4j</groupId>
134 <artifactId>slf4j-api</artifactId>
135 <version>1.7.7</version>
136 </dependency>
137 <dependency>
138 <groupId>org.slf4j</groupId>
139 <artifactId>slf4j-log4j12</artifactId>
140 <version>1.7.7</version>
141 </dependency>
142 <!-- log end -->
143 <!-- 映入JSON -->
144 <dependency>
145 <groupId>org.codehaus.jackson</groupId>
146 <artifactId>jackson-mapper-asl</artifactId>
147 <version>1.9.13</version>
148 </dependency>
149
150 <!-- 上传组件包 -->
151 <dependency>
152 <groupId>commons-fileupload</groupId>
153 <artifactId>commons-fileupload</artifactId>
154 <version>1.3.1</version>
155 </dependency>
156 <dependency>
157 <groupId>commons-io</groupId>
158 <artifactId>commons-io</artifactId>
159 <version>2.4</version>
160 </dependency>
161 <dependency>
162 <groupId>commons-codec</groupId>
163 <artifactId>commons-codec</artifactId>
164 <version>1.9</version>
165 </dependency>
166 </dependencies>
167 <build>
168 <finalName>storm</finalName>
169 <plugins>
170 <plugin>
171 <groupId>org.eclipse.jetty</groupId>
172 <artifactId>jetty-maven-plugin</artifactId>
173 <version>9.2.8.v20150217</version>
174 <configuration>
175 <httpConnector>
176 <port>8090</port>
177 </httpConnector>
178 <stopKey>shutdown</stopKey>
179 <stopPort>9966</stopPort>
180 </configuration>
181 </plugin>
182 </plugins>
183 </build>
184 <packaging>war</packaging>
185 </project>
2.2 整合SpringMVC
2.2.1 配置spring-mvc.xml
配置里面的注释也很详细,主要是自动扫描控制器,视图模式,注解的启动这三个。
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
4 xmlns:context="http://www.springframework.org/schema/context"
5 xmlns:mvc="http://www.springframework.org/schema/mvc"
6 xsi:schemaLocation="
7 http://www.springframework.org/schema/beans
8 http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
9 http://www.springframework.org/schema/context
10 http://www.springframework.org/schema/context/spring-context-3.1.xsd
11 http://www.springframework.org/schema/mvc
12 http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
13 <!-- 自动扫描,使SpringMVC认为包下用了@Controller注解的类是控制器 -->
14 <context:component-scan base-package="com.cn.hnust.controller" />
15 <!-- 扩充了注解驱动,可以将请求参数绑定到控制器参数 -->
16 <mvc:annotation-driven />
17 <!-- 静态资源处理 css js imgs -->
18 <mvc:resources location="/resources/**" mapping="/resources" />
19 <!-- 避免IE执行AJAX时,返回JSON出现下载文件 -->
20 <bean id="mappingJacksonHttpMessageConverter"
21 class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
22 <property name="supportedMediaTypes">
23 <list>
24 <value>text/html;charset=UTF-8</value>
25 </list>
26 </property>
27 </bean>
28
29 <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
30 <bean
31 class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
32 <property name="messageConverters">
33 <list>
34 <!-- JSON转换器 -->
35 <ref bean="mappingJacksonHttpMessageConverter" />
36 </list>
37 </property>
38 </bean>
39
40 <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->
41 <bean id="multipartResolver"
42 class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
43 <!-- 默认编码 -->
44 <property name="defaultEncoding" value="utf-8"></property>
45 <!-- 文件大小最大值 -->
46 <property name="maxUploadSize" value="10485760000"></property>
47 <!-- 内存中的最大值 -->
48 <property name="maxInMemorySize" value="40960"></property>
49 <!-- 启用是为了推迟文件解析,以便捕获文件大小异常 -->
50 <property name="resolveLazily" value="true"></property>
51 </bean>
52
53 <!-- 配置ViewResolver。可用多个ViewResolver。使用order属性排序。 InternalResourceViewResolver
54 放在最后 -->
55 <bean
56 class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
57 <property name="order" value="1"></property>
58 <property name="mediaTypes">
59 <map>
60 <!-- 告诉视图解析器,返回的类型是json格式 -->
61 <entry key="json" value="application/json"></entry>
62 <entry key="xml" value="application/xml"></entry>
63 <entry key="htm" value="text/htm"></entry>
64 </map>
65 </property>
66 <property name="defaultViews">
67 <list>
68 <!-- ModelAndView里的数据变成JSON -->
69 <bean
70 class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"></bean>
71 </list>
72 </property>
73 <property name="ignoreAcceptHeader" value="true"></property>
74 </bean>
75 <!-- 定义跳转的文件的前后缀,视图模式配置 -->
76 <bean
77 class="org.springframework.web.servlet.view.InternalResourceViewResolver">
78 <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
79 <property name="prefix" value="/WEB-INF/jsp/"></property>
80 <property name="suffix" value=".jsp"></property>
81 </bean>
82 </beans>
2.2.2 配置web.xml文件
配置的spring-mvc的Servlet就是为了完成SpringMVC+MAVEN的整合。
web.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3 xmlns="http://java.sun.com/xml/ns/javaee"
4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
5 version="3.0">
6 <display-name>Archetype Created Web Application</display-name>
7 <!-- Spring和MyBatis的配置文件 -->
8 <!-- <context-param>
9 <param-name>contextConfigLocation</param-name>
10 <param-value>classpath:spring-mybatis.xml</param-value>
11 </context-param> -->
12 <!-- 编码过滤器 -->
13 <filter>
14 <filter-name>encodingFilter</filter-name>
15 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
16 <async-supported>true</async-supported>
17 <init-param>
18 <param-name>encoding</param-name>
19 <param-value>UTF-8</param-value>
20 </init-param>
21 </filter>
22 <filter-mapping>
23 <filter-name>encodingFilter</filter-name>
24 <url-pattern>/*</url-pattern>
25 </filter-mapping>
26 <!-- Spring监听器 -->
27 <!-- <listener>
28 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
29 </listener> -->
30 <!-- 防止Spring内存溢出监听器 -->
31 <!-- <listener>
32 <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
33 </listener> -->
34
35 <!-- Spring MVC servlet -->
36 <servlet>
37 <servlet-name>SpringMVC</servlet-name>
38 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
39 <!-- 下面init-param是自定义servlet.xml配置文件的位置和名称,默认为WEB-INF目录下,名称为[<servlet-name>]-servlet.xml,如spring-servlet.xml -->
40 <init-param>
41 <param-name>contextConfigLocation</param-name>
42 <param-value>classpath:spring-mvc.xml</param-value>
43 </init-param>
44 <load-on-startup>1</load-on-startup>
45 <async-supported>true</async-supported>
46 </servlet>
47 <servlet-mapping>
48 <servlet-name>SpringMVC</servlet-name>
49 <!-- 此处可以配置成*.do,对应struts的后缀习惯 -->
50 <url-pattern>/</url-pattern>
51 </servlet-mapping>
52 <welcome-file-list>
53 <welcome-file>/index.jsp</welcome-file>
54 </welcome-file-list>
55 </web-app>
2.2.3 Log4j的配置
为了方便调试,一般都会使用日志来输出信息,Log4j是Apache的一个开放源代码项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件,甚至是套接口服务器、NT的事件记录器、UNIX Syslog守护进程等;我们也可以控制每一条日志的输出格式;通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。
Log4j的配置很简单,而且也是通用的,下面给出一个基本的配置,换到其他项目中也无需做多大的调整。
log4j.properties
1 #定义LOG输出级别
2 log4j.rootLogger=INFO,Console,File
3 #定义日志输出目的地为控制台
4 log4j.appender.Console=org.apache.log4j.ConsoleAppender
5 log4j.appender.Console.Target=System.out
6 #可以灵活地指定日志输出格式,下面一行是指定具体的格式
7 log4j.appender.Console.layout=org.apache.log4j.PatternLayout
8 log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n
9
10 #文件大小达到指定尺寸的时候产生一个新的文件
11 log4j.appender.File=org.apache.log4j.RollingFileAppender
12 #指定输出目录
13 log4j.appender.File.File=logs/ssm.log
14 #定义文件最大大小
15 log4j.appender.File.MaxFileSize=10MB
16 #输出所有日志,如果换成DEBUG表示输出DEBUG以上级别日志
17 log4j.appender.File.Threshold=ALL
18 log4j.appender.File.layout=org.apache.log4j.PatternLayout
19 log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
2.2.4 使用Jetty测试
Student类对应于数据库中表的属性
1 package com.cn.hnust.pojo;
2
3 public class Student {
4 private Integer id;
5
6 private String stu_name;
7
8 private Integer gender;
9
10 private Integer age;
11
12 private String address;
13
14 public Integer getId() {
15 return id;
16 }
17
18 public void setId(Integer id) {
19 this.id = id;
20 }
21
22 public String getStu_name() {
23 return stu_name;
24 }
25
26 public void setStu_name(String stu_name) {
27 this.stu_name = stu_name;
28 }
29
30 public Integer getGender() {
31 return gender;
32 }
33
34 public void setGender(Integer gender) {
35 this.gender = gender;
36 }
37
38 public Integer getAge() {
39 return age;
40 }
41
42 public void setAge(Integer age) {
43 this.age = age;
44 }
45
46 public String getAddress() {
47 return address;
48 }
49
50 public void setAddress(String address) {
51 this.address = address;
52 }
53
54 @Override
55 public String toString() {
56 return "Student [id=" + id + ", stu_name=" + stu_name + ", gender="
57 + gender + ", age=" + age + ", address=" + address + "]";
58 }
59 }
控制器类
1 package com.cn.hnust.controller;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.util.Map;
6
7 import javax.annotation.Resource;
8 import javax.servlet.http.HttpServletRequest;
9
10 import org.apache.commons.io.FileUtils;
11 import org.slf4j.Logger;
12 import org.slf4j.LoggerFactory;
13 import org.springframework.http.HttpStatus;
14 import org.springframework.http.ResponseEntity;
15 import org.springframework.stereotype.Controller;
16 import org.springframework.ui.Model;
17 import org.springframework.web.bind.annotation.PathVariable;
18 import org.springframework.web.bind.annotation.RequestMapping;
19 import org.springframework.web.bind.annotation.RequestMethod;
20 import org.springframework.web.bind.annotation.RequestParam;
21 import org.springframework.web.bind.annotation.ResponseBody;
22 import org.springframework.web.multipart.MultipartFile;
23
24 import com.cn.hnust.pojo.Student;
25 import com.cn.hnust.service.IStudentService;
26
27 @Controller
28 @RequestMapping("/student")
29 public class StudentController {
30 private static Logger log = LoggerFactory
31 .getLogger(StudentController.class);
32
33 @Resource
34 private IStudentService studentService;
35
36 // /student/test?id=1
37 @RequestMapping(value = "/test", method = RequestMethod.GET)
38 public String test(HttpServletRequest request, Model model) {
39 int studentId = Integer.parseInt(request.getParameter("id"));
40 System.out.println("test studentId:" + studentId);
41 Student student = null;
42 if (studentId == 1) {
43 student = new Student();
44 student.setAge(19);
45 student.setId(1);
46 student.setGender(1);
47 student.setAddress("北京七里省际大厦3栋4402");
48 student.setStu_name("江泽");
49 }
50
51 log.debug(student.toString());
52 model.addAttribute("student", student);
53 return "index";
54 }
55 }
运行测试
控制台没有报错
在浏览器中输入:http://localhost:8090/student/test?id=1 (端口号根据你的设置有关,自己调查)
到此 SpringMVC+Maven 整合完毕
2.3 Spring与MyBatis的整合
取消2.2.2 web.xml中注释的代码,下面是去除后的代码
1 <?xml version="1.0" encoding="UTF-8"?>
2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3 xmlns="http://java.sun.com/xml/ns/javaee"
4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
5 version="3.0">
6 <display-name>Archetype Created Web Application</display-name>
7 <!-- Spring和MyBatis的配置文件 -->
8 <context-param>
9 <param-name>contextConfigLocation</param-name>
10 <param-value>classpath:spring-mybatis.xml</param-value>
11 </context-param>
12 <!-- 编码过滤器 -->
13 <filter>
14 <filter-name>encodingFilter</filter-name>
15 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
16 <async-supported>true</async-supported>
17 <init-param>
18 <param-name>encoding</param-name>
19 <param-value>UTF-8</param-value>
20 </init-param>
21 </filter>
22 <filter-mapping>
23 <filter-name>encodingFilter</filter-name>
24 <url-pattern>/*</url-pattern>
25 </filter-mapping>
26 <!-- Spring监听器 -->
27 <listener>
28 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
29 </listener>
30 <!-- 防止Spring内存溢出监听器 -->
31 <listener>
32 <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
33 </listener>
34
35 <!-- Spring MVC servlet -->
36 <servlet>
37 <servlet-name>SpringMVC</servlet-name>
38 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
39 <!-- 下面init-param是自定义servlet.xml配置文件的位置和名称,默认为WEB-INF目录下,名称为[<servlet-name>]-servlet.xml,如spring-servlet.xml -->
40 <init-param>
41 <param-name>contextConfigLocation</param-name>
42 <param-value>classpath:spring-mvc.xml</param-value>
43 </init-param>
44 <load-on-startup>1</load-on-startup>
45 <async-supported>true</async-supported>
46 </servlet>
47 <servlet-mapping>
48 <servlet-name>SpringMVC</servlet-name>
49 <!-- 此处可以配置成*.do,对应struts的后缀习惯 -->
50 <url-pattern>/</url-pattern>
51 </servlet-mapping>
52 <welcome-file-list>
53 <welcome-file>/index.jsp</welcome-file>
54 </welcome-file-list>
55 </web-app>
2.3.1、建立JDBC属性文件
jdbc.properties(文件编码修改为utf-8) 根据自己数据库配置url username password
1 #连接数据库
2 #jdbc.driver=net.sf.log4jdbc.DriverSpy
3 #jdbc.url=jdbc:log4jdbc:oracle:thin:@192.168.0.125:1521:xe
4 jdbc.driver=oracle.jdbc.OracleDriver
5 jdbc.url=jdbc:oracle:thin:@192.168.0.125:1521:xe
6 jdbc.username=orcl
7 jdbc.password=orcl
8
9 #dbcp settings
10 dbcp.maxIdle=5
11 dbcp.maxActive=50
2.3.2、建立spring-mybatis.xml配置文件
这个文件就是用来完成spring和mybatis的整合的。主要的就是自动扫描,自动注入,配置数据库。注释也很详细,大家看看就明白了。
spring-mybatis.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
4 xmlns:context="http://www.springframework.org/schema/context"
5 xmlns:mvc="http://www.springframework.org/schema/mvc"
6 xsi:schemaLocation="
7 http://www.springframework.org/schema/beans
8 http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
9 http://www.springframework.org/schema/context
10 http://www.springframework.org/schema/context/spring-context-3.1.xsd
11 http://www.springframework.org/schema/mvc
12 http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
13 <!-- 自动扫描 -->
14 <context:component-scan base-package="com.cn.hnust" />
15
16 <!-- 使用annotation 自动注册bean, 并保证@Required、@Autowired的属性被注入 -->
17 <!--<context:component-scan base-package="com.cn.hnust">
18 <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
19 </context:component-scan>-->
20
21 <!-- 引入配置文件 -->
22 <bean id="propertyConfigurer"
23 class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
24 <property name="location" value="classpath:jdbc.properties" />
25 </bean>
26
27 <!-- 数据源配置, 使用应用中的DBCP数据库连接池 -->
28 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
29 destroy-method="close">
30 <!-- Connection Info -->
31 <property name="driverClassName" value="${jdbc.driver}" />
32 <property name="url" value="${jdbc.url}" />
33 <property name="username" value="${jdbc.username}" />
34 <property name="password" value="${jdbc.password}" />
35
36 <!-- Connection Pooling Info -->
37 <property name="maxActive" value="${dbcp.maxActive}" />
38 <property name="maxIdle" value="${dbcp.maxIdle}" />
39 <property name="defaultAutoCommit" value="false" />
40 <!-- 连接Idle一个小时后超时 -->
41 <property name="timeBetweenEvictionRunsMillis" value="3600000" />
42 <property name="minEvictableIdleTimeMillis" value="3600000" />
43 </bean>
44
45 <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
46 <bean id="sqlSessionFactory"
47 class="org.mybatis.spring.SqlSessionFactoryBean">
48 <property name="dataSource" ref="dataSource"/>
49 <!-- 自动扫描mapping.xml文件 -->
50 <property name="mapperLocations" value="classpath:com/cn/hnust/mapping/*.xml"></property>
51 </bean>
52 <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
53 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
54 <property name="basePackage" value="com.cn.hnust.dao"></property>
55 <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
56 </bean>
57
58 <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
59 <bean id="transactionManager"
60 class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
61 <property name="dataSource" ref="dataSource" />
62 </bean>
63 </beans>
2.4 JUnit测试
创建实体类、MyBatis映射文件以及DAO接口
DAO接口类
1 package com.cn.hnust.dao;
2
3 import com.cn.hnust.pojo.Student;
4
5 public interface IStudentDao {
6 int deleteByPrimaryKey(Integer id);
7
8 int insert(Student record);
9
10 int insertSelective(Student record);
11
12 Student selectByPrimaryKey(Integer id);
13
14 int updateByPrimaryKeySelective(Student record);
15
16 int updateByPrimaryKey(Student record);
17 }
实现增删改查的xml配置文件
1 <?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE mapper
3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
5 <mapper namespace="com.cn.hnust.dao.IStudentDao">
6 <resultMap type="com.cn.hnust.pojo.Student" id="BaseResultMap">
7 <id column="id" property="id" jdbcType="INTEGER" />
8 <result column="stu_name" property="stu_name" jdbcType="VARCHAR" />
9 <result column="age" property="age" jdbcType="INTEGER" />
10 <result column="gender" property="gender" jdbcType="INTEGER" />
11 <result column="address" property="address" jdbcType="VARCHAR" />
12 </resultMap>
13 <sql id="Base_Column_List">
14 id,stu_name,age,gender,address
15 </sql>
16 <select id="selectByPrimaryKey" resultMap="BaseResultMap"
17 parameterType="java.lang.Integer">
18 select
19 <include refid="Base_Column_List"></include>
20 from student
21 where id = #{id,jdbcType=INTEGER}
22 </select>
23 <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
24 delete from
25 student
26 where id = #{id,jdbcType=INTEGER}
27 </delete>
28 <insert id="insert" parameterType="com.cn.hnust.pojo.Student">
29 insert into
30 student(id,stu_name,age,gender,address)
31 values
32 (#{id,jdbcType=INTEGER},#{stu_name,jdbcType=VARCHAR},#{age,jdbcType=INTEGER},#{gender,jdbcType=INTEGER},#{address,jdbcType=VARCHAR})
33 </insert>
34 <insert id="insertSelective" parameterType="com.cn.hnust.pojo.Student">
35 insert into student
36 <trim prefix="(" suffix=")" suffixOverrides=",">
37 <if test="id != null">
38 id,
39 </if>
40 <if test="stu_name != null">
41 stu_name,
42 </if>
43 <if test="age != null">
44 age,
45 </if>
46 <if test="gender != null">
47 gender,
48 </if>
49 <if test="address != null">
50 address,
51 </if>
52 </trim>
53 <trim prefix="values (" suffix=")" suffixOverrides=",">
54 <if test="id != null">
55 #{id,jdbcType=INTEGER},
56 </if>
57 <if test="stu_name != null">
58 #{stu_name,jdbcType=VARCHAR},
59 </if>
60 <if test="age != null">
61 #{age,jdbcType=INTEGER},
62 </if>
63 <if test="gender != null">
64 #{gender,jdbcType=INTEGER},
65 </if>
66 <if test="address != null">
67 #{address,jdbcType=VARCHAR},
68 </if>
69 </trim>
70 </insert>
71 <update id="updateByPrimaryKeySelective" parameterType="com.cn.hnust.pojo.Student">
72 update student
73 <set >
74 <if test="stu_name != null">
75 stu_name = #{stu_name,jdbcType=VARCHAR},
76 </if>
77 <if test="age != null">
78 age = #{age,jdbcType=INTEGER},
79 </if>
80 <if test="gender != null">
81 gender = #{gender,jdbcType=INTEGER},
82 </if>
83 <if test="address != null">
84 address = #{address,jdbcType=VARCHAR},
85 </if>
86 </set>
87 where id = #{id,jdbcType=INTEGER}
88 </update>
89 <update id="updateByPrimaryKey" parameterType="com.cn.hnust.pojo.Student">
90 update student
91 set stu_name = #{stu_name,jdbcType=VARCHAR},
92 age = #{age,jdbcType=INTEGER},
93 gender = #{gender,jdbcType=INTEGER},
94 address = #{address,jdbcType=VARCHAR}
95 where id = #{id,jdbcType=INTEGER}
96 </update>
97 </mapper>
建立Service接口和实现类
1 package com.cn.hnust.service;
2
3 import com.cn.hnust.pojo.Student;
4
5 public interface IStudentService {
6 public Student getStudentById(int studentId);
7 }
1 package com.cn.hnust.service.impl;
2
3 import javax.annotation.Resource;
4
5 import org.springframework.stereotype.Service;
6
7 import com.cn.hnust.dao.IStudentDao;
8 import com.cn.hnust.pojo.Student;
9 import com.cn.hnust.service.IStudentService;
10
11 @Service("studentService")
12 public class StudentServiceImpl implements IStudentService {
13
14 @Resource
15 private IStudentDao studentDao;
16
17 @Override
18 public Student getStudentById(int studentId) {
19 return this.studentDao.selectByPrimaryKey(studentId);
20 }
21
22 }
建立UserController类
1 package com.cn.hnust.controller;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.util.Map;
6
7 import javax.annotation.Resource;
8 import javax.servlet.http.HttpServletRequest;
9
10 import org.apache.commons.io.FileUtils;
11 import org.slf4j.Logger;
12 import org.slf4j.LoggerFactory;
13 import org.springframework.http.HttpStatus;
14 import org.springframework.http.ResponseEntity;
15 import org.springframework.stereotype.Controller;
16 import org.springframework.ui.Model;
17 import org.springframework.web.bind.annotation.PathVariable;
18 import org.springframework.web.bind.annotation.RequestMapping;
19 import org.springframework.web.bind.annotation.RequestMethod;
20 import org.springframework.web.bind.annotation.RequestParam;
21 import org.springframework.web.bind.annotation.ResponseBody;
22 import org.springframework.web.multipart.MultipartFile;
23
24 import com.cn.hnust.pojo.Student;
25 import com.cn.hnust.service.IStudentService;
26
27 @Controller
28 @RequestMapping("/student")
29 public class StudentController {
30 private static Logger log = LoggerFactory
31 .getLogger(StudentController.class);
32
33 @Resource
34 private IStudentService studentService;
35
36 // /student/test?id=1
37 @RequestMapping(value = "/test", method = RequestMethod.GET)
38 public String test(HttpServletRequest request, Model model) {
39 int studentId = Integer.parseInt(request.getParameter("id"));
40 System.out.println("test studentId:" + studentId);
41 Student student = null;
42 if (studentId == 1) {
43 student = new Student();
44 student.setAge(19);
45 student.setId(1);
46 student.setGender(1);
47 student.setAddress("北京七里省际大厦3栋4402");
48 student.setStu_name("江泽");
49 }
50
51 log.debug(student.toString());
52 model.addAttribute("student", student);
53 return "index";
54 }
55
56 // /student/showStudent?id=1
57 @RequestMapping(value = "/showStudent", method = RequestMethod.GET)
58 public String toIndex(HttpServletRequest request, Model model) {
59 int studentId = Integer.parseInt(request.getParameter("id"));
60 System.out.println("toIndex studentId:" + studentId);
61 Student student = this.studentService.getStudentById(studentId);
62 log.debug(student.toString());
63 model.addAttribute("student", student);
64 return "showStudent";
65 }
66
67 // /student/showStudent2?id=1
68 @RequestMapping(value = "/showStudent2", method = RequestMethod.GET)
69 public String toIndex2(@RequestParam("id") String id, Model model) {
70 int studentId = Integer.parseInt(id);
71 System.out.println("toIndex2 studentId:" + studentId);
72 Student student = this.studentService.getStudentById(studentId);
73 log.debug(student.toString());
74 model.addAttribute("student", student);
75 return "showStudent";
76 }
77
78 // /student/showStudent3/{id}
79 @RequestMapping(value = "/showStudent3/{id}", method = RequestMethod.GET)
80 public String toIndex3(@RequestParam("id") String id,
81 Map<String, Object> model) {
82 int studentId = Integer.parseInt(id);
83 System.out.println("toIndex3 studentId:" + studentId);
84 Student student = this.studentService.getStudentById(studentId);
85 log.debug(student.toString());
86 model.put("student", student);
87 return "showStudent";
88 }
89
90 // /student{id}
91 @RequestMapping(value = "/{id}", method = RequestMethod.GET)
92 public @ResponseBody
93 Student getStudentInJson(@PathVariable String id, Map<String, Object> model) {
94 int studentId = Integer.parseInt(id);
95 System.out.println("getStudentInJson studentId:" + studentId);
96 Student student = this.studentService.getStudentById(studentId);
97 log.info(student.toString());
98 return student;
99 }
100
101 // /student/{id}
102 @RequestMapping(value = "/jsontype/{id}", method = RequestMethod.GET)
103 public ResponseEntity<Student> getStudentInJson2(@PathVariable String id,
104 Map<String, Object> model) {
105 int studentId = Integer.parseInt(id);
106 System.out.println("getStudentInJson2 studentId:" + studentId);
107 Student student = this.studentService.getStudentById(studentId);
108 log.info(student.toString());
109 return new ResponseEntity<Student>(student, HttpStatus.OK);
110 }
111
112 // 文件上传
113 @RequestMapping(value = "/upload")
114 public String showUploadPage() {
115 return "student_admin/file";
116 }
117
118 @RequestMapping(value = "/doUpload", method = RequestMethod.GET)
119 public String doUploadFile(@RequestParam("file") MultipartFile file)
120 throws IOException {
121 if (!file.isEmpty()) {
122 log.info("Process file:{}", file.getOriginalFilename());
123 }
124 FileUtils.copyInputStreamToFile(file.getInputStream(), new File("F:\\",
125 System.currentTimeMillis() + file.getOriginalFilename()));
126 return "sucess";
127 }
128 }
新建jsp页面
file.jsp
1 <%@ page language="java" contentType="text/html;charset=utf-8"
2 pageEncoding="utf-8" %>
3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org//TR/html4/loose.dtd">
4 <html>
5 <head>
6 <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
7 <title>Insert title here</title>
8 </head>
9 <body>
10 <h1>上传文件</h1>
11 <form action="/student/doUpload" method="post" enctype="multipart/form-data">
12 <input type="file" name="file"/>
13 <input type="submit" value="上传文件"/>
14 </form>
15 </body>
16 </html>
index.jsp
1 <%@ page language="java" import="java.util.*"
2 pageEncoding="utf-8" %>
3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
4 <html>
5 <body>
6 <h2>Hello zou</h2>
7 <br>
8 <a href="jsp/showStudent.jsp">跳转</a>
9 </body>
10 </html>
showUser.jsp
1 <%@ page language="java" import="java.util.*"
2 pageEncoding="utf-8" %>
3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
4 <html>
5 <head>
6 <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
7 <title>Testing</title>
8 </head>
9 <body>
10 ${student.stu_name}
11 </body>
12 </html>
success.jsp
1 <%@ page language="java" contentType="text/html;charset=utf-8"
2 pageEncoding="utf-8" %>
3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org//TR/html4/loose.dtd">
4 <html>
5 <head>
6 <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
7 <title>success</title>
8 </head>
9 <body>
10 <h1>success</h1>
11 </body>
12 </html>
部署项目
输入地址:http://localhost:8090/student/jsontype/2