本系列文章將從環境搭建開始逐步詳細地記錄一個基於SSM框架的個人博客系統的完整構建過程,適合於已初步了解java web、SSM框架(spring, springmvc, mybatis)等相關技術的並且沒有項目經驗的初學者。網絡上關於web項目的資料數不勝數,但也十分繁雜,對於初學者來說不知從何處入手,成本的出版書籍或者成套的項目教學視頻,完整的看一遍相當耗時,而且有些對新手很不友好。Java web相關技術多而雜,然而,做一個項目的過程中似乎不太需要事先完整而系統地掌握這些知識點,在具體實踐中遇到問題然后學習,也是個不錯的選擇。由於本人也僅僅是個准入門者,在文章中的敘述或者項目中的做法定會存在諸多不當之處,望各位海涵並不吝指出,以便及時修改。另外特別聲明:項目內容屬於偽原創,參考了網上其他的博客內容或代碼,權當學習記錄、總結,侵刪!以下是正式內容。
本文使用的開發工具為Eclipse,JDK版本為1.8,數據庫MySQL及其可視化工具SQLyog,服務器為tomcat7。
一、創建項目
首先是環境搭建,這里使用Maven管理項目,所以需要創建一個Maven工程,在File->new中選擇Maven Project,直接next在Filter中搜索web,選擇webapp一項,如下圖:
然后填寫Group Id 和Artifact Id:
然后點擊finished。接下來由於maven項目默認的jdk版本較低,在項目名右鍵選擇Build Path->Configure Build Path,將低版本的jdk移除並添加較高版本的jdk以及tomcat7,如圖:
接下來是此時項目的目錄結構:
將項目添加到tomcat服務器並啟動,在瀏覽器中輸入localhost:8080/MyBlog/ ,顯示如下表明項目初步搭建成功。
Hello World為index.jsp中的內容,由於我這里將tomcat的端口改成了8081(默認為8080),所以我在瀏覽器中輸入的是8081。
二、SSM框架整合
1.添加jar包
框架的整合需要一系列的jar包,直接在pom.xml文件中引用即可,這里直接給出所有需要的jar包
pom.xml:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
|
<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/maven-v4_0_0.xsd"
>
<modelVersion>
4.0
.
0
</modelVersion>
<groupId>com.neya</groupId>
<artifactId>MyBlog</artifactId>
<packaging>war</packaging>
<version>
0.0
.
1
-SNAPSHOT</version>
<name>MyBlog Maven Webapp</name>
<url>http:
//maven.apache.org</url>
<build>
<finalName>MyBlog</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>
1.6
</source>
<target>
1.6
</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<project.build.sourceEncoding>UTF-
8
</project.build.sourceEncoding>
<spring.version>
4.1
.
4
.RELEASE</spring.version>
<jackson.version>
2.5
.
0
</jackson.version>
</properties>
<repositories>
<repository>
<id>aliyun</id>
<name>aliyun</name>
<url>http:
//maven.aliyun.com/nexus/content/groups/public/</url>
<layout>
default
</layout>
<releases>
<enabled>
true
</enabled>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>
true
</enabled>
<updatePolicy>never</updatePolicy>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>aliyun</id>
<name>aliyun</name>
<url>http:
//maven.aliyun.com/nexus/content/groups/public/</url>
<releases>
<enabled>
true
</enabled>
</releases>
<snapshots>
<enabled>
false
</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>
3.8
.
1
</version>
<scope>test</scope>
</dependency>
<!-- 添加Servlet支持 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>
3.1
.
0
</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>
2.3
.
1
</version>
</dependency>
<!-- 添加jtl支持 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>
1.2
</version>
</dependency>
<!-- 添加Spring支持 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>
4.1
.
7
.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>
4.1
.
7
.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>
4.1
.
7
.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>
4.1
.
7
.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>
4.1
.
7
.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>
4.1
.
7
.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>
4.1
.
7
.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>
4.1
.
7
.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>
4.1
.
7
.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>
4.1
.
7
.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>
4.1
.
7
.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>
1.2
.
3
</version>
</dependency>
<!-- 添加日志支持 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>
1.2
.
17
</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>
1.7
.
12
</version>
</dependency>
<!-- 添加mybatis支持 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>
3.3
.
0
</version>
</dependency>
<!-- jdbc驅動包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>
5.1
.
37
</version>
</dependency>
<!-- apache公共包 -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>
1.10
</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>
2.5
</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>
1.8
.
0
</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>
3.2
.
1
</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>
1.1
.
1
</version>
</dependency>
<!-- 添加連接池druid支持 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>
1.0
.
16
</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>
1.8
.
3
</version>
</dependency>
</dependencies>
</project>
|
2.1 整合spring-mybatis
1.applicationContext-dao.xml配置文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
<?xml version=
"1.0"
encoding=
"UTF-8"
?>
<beans xmlns=
"http://www.springframework.org/schema/beans"
xmlns:context=
"http://www.springframework.org/schema/context"
xmlns:p=
"http://www.springframework.org/schema/p"
xmlns:aop=
"http://www.springframework.org/schema/aop"
xmlns:tx=
"http://www.springframework.org/schema/tx"
xmlns:xsi=
"http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http:
//www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.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
http:
//www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 加載配置文件 -->
<context:property-placeholder location=
"classpath:*.properties"
/>
<!-- 配置數據庫連接池 -->
<bean id=
"dataSource"
class
=
"com.alibaba.druid.pool.DruidDataSource"
>
<property name=
"driverClassName"
value=
"${jdbc.driver}"
></property>
<property name=
"url"
value=
"${jdbc.url}"
></property>
<property name=
"username"
value=
"${jdbc.username}"
></property>
<property name=
"password"
value=
"${jdbc.password}"
></property>
</bean>
<!-- 讓spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
<bean id=
"sqlSessionFactory"
class
=
"org.mybatis.spring.SqlSessionFactoryBean"
>
<property name=
"dataSource"
ref=
"dataSource"
></property>
<property name=
"configLocation"
value=
"classpath:SqlMapConfig.xml"
></property>
</bean>
<!-- Mapper 掃描器 -->
<bean
class
=
"org.mybatis.spring.mapper.MapperScannerConfigurer"
>
<property name=
"basePackage"
value=
"com.neya.mapper"
></property>
<property name=
"sqlSessionFactoryBeanName"
value=
"sqlSessionFactory"
></property>
</bean>
<bean id=
"transactionManager"
class
=
"org.springframework.jdbc.datasource.DataSourceTransactionManager"
>
<property name=
"dataSource"
ref=
"dataSource"
></property>
</bean>
<!-- 配置通知 -->
<tx:advice id=
"txAdvice"
transaction-manager=
"transactionManager"
>
<tx:attributes>
<tx:method name=
"insert*"
propagation=
"REQUIRED"
/>
<tx:method name=
"update*"
propagation=
"REQUIRED"
/>
<tx:method name=
"edit*"
propagation=
"REQUIRED"
/>
<tx:method name=
"save*"
propagation=
"REQUIRED"
/>
<tx:method name=
"add*"
propagation=
"REQUIRED"
/>
<tx:method name=
"new*"
propagation=
"REQUIRED"
/>
<tx:method name=
"set*"
propagation=
"REQUIRED"
/>
<tx:method name=
"remove*"
propagation=
"REQUIRED"
/>
<tx:method name=
"delete*"
propagation=
"REQUIRED"
/>
<tx:method name=
"change*"
propagation=
"REQUIRED"
/>
<tx:method name=
"check*"
propagation=
"REQUIRED"
/>
<tx:method name=
"get*"
propagation=
"REQUIRED"
read-only=
"true"
/>
<tx:method name=
"find*"
propagation=
"REQUIRED"
read-only=
"true"
/>
<tx:method name=
"load*"
propagation=
"REQUIRED"
read-only=
"true"
/>
<tx:method name=
"*"
propagation=
"REQUIRED"
read-only=
"true"
/>
</tx:attributes>
</tx:advice>
<!-- 配置攔截service -->
<aop:config>
<aop:advisor advice-ref=
"txAdvice"
pointcut=
"execution(* com.neya.service.*.*(..))"
/>
</aop:config>
</beans>
|
2.applicationContext-service.xml配置文件
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<?xml version=
"1.0"
encoding=
"UTF-8"
?>
<beans xmlns=
"http://www.springframework.org/schema/beans"
xmlns:context=
"http://www.springframework.org/schema/context"
xmlns:p=
"http://www.springframework.org/schema/p"
xmlns:aop=
"http://www.springframework.org/schema/aop"
xmlns:tx=
"http://www.springframework.org/schema/tx"
xmlns:xsi=
"http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http:
//www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.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
http:
//www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<context:component-scan base-
package
=
"com.neya.service"
></context:component-scan>
</beans>
|
3.db.properties文件
1
2
3
4
|
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:
//localhost:3306/myblog
jdbc.username=root
jdbc.password=root
|
這里的除第一行以外根據自己的實際情況配置
4.log4j.properties文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{
1
}:%L - %m%n
### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c:/mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{
1
}:%L - %m%n
### set log levels -
for
more verbose logging change
'info'
to
'debug'
###
log4j.rootLogger=debug, stdout
|
5.測試整合結果
接下來測試spring於mybatis的整合結果,首先在數據庫中創建表user:
1
2
3
4
5
6
7
8
9
10
11
|
CREATE
TABLE
`
user
` (
`id`
int
(11)
NOT
NULL
AUTO_INCREMENT,
`username`
varchar
(40)
NOT
NULL
,
`
password
`
varchar
(255)
NOT
NULL
,
`age`
int
(4)
NOT
NULL
,
PRIMARY
KEY
(`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2
DEFAULT
CHARSET=utf8;
/*Data
for
the
table
`user_t` */
insert
into
`
user
`(`id`,`username`,`
password
`,`age`)
values
(1,
'zhangsan'
,
'sfasgfaf'
,24);
|
然后,可以使用mybatis的逆向工程根據數據庫自動生成實體類以及mapper,這里需要在eclipse安裝Mybatis-generator插件。
逆向工程文件generatorConfig.xml:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
<?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>
<classPathEntry
location=
"C:\Users\admin\.m2\repository\mysql\mysql-connector-java\5.1.37\mysql-connector-java-5.1.37.jar"
/>
<context id=
"DB2Tables"
targetRuntime=
"MyBatis3"
>
<commentGenerator>
<!-- 抑制警告 -->
<property name=
"suppressTypeWarnings"
value=
"true"
/>
<!-- 是否去除自動生成的注釋
true
:是 :
false
:否 -->
<property name=
"suppressAllComments"
value=
"true"
/>
<!-- 是否生成注釋代時間戳 -->
<property name=
"suppressDate"
value=
"true"
/>
<property name=
"isMergeable"
value=
""
/>
</commentGenerator>
<!--數據庫連接的信息:驅動類、連接地址、用戶名、密碼 -->
<jdbcConnection driverClass=
"com.mysql.jdbc.Driver"
connectionURL=
"jdbc:mysql://localhost/myblog"
userId=
"root"
password=
"root"
>
</jdbcConnection>
<javaModelGenerator targetPackage=
"com.neya.domain"
targetProject=
"MyBlog\src\main\java"
>
<property name=
"enableSubPackages"
value=
"false"
/>
<property name=
"trimStrings"
value=
"true"
/>
</javaModelGenerator>
<sqlMapGenerator targetPackage=
"com.neya.mapper"
targetProject=
"MyBlog\src\main\java"
>
<property name=
"enableSubPackages"
value=
"true"
/>
</sqlMapGenerator>
<javaClientGenerator type=
"XMLMAPPER"
targetPackage=
"com.neya.mapper"
targetProject=
"MyBlog\src\main\java"
>
<property name=
"enableSubPackages"
value=
"true"
/>
</javaClientGenerator>
<!-- tableName:用於自動生成代碼的數據庫表;domainObjectName:對應於數據庫表的javaBean類名 -->
<!-- <table schema=
"untodo"
tableName=
"T_USER"
domainObjectName=
"User"
/> -->
<!-- 要生成那些表(更改tableName和domainObjectName就可以) -->
<!-- <table schema=
"untodo"
tableName=
"T_USER"
domainObjectName=
"User"
enableCountByExample=
"false"
enableUpdateByExample=
"false"
enableDeleteByExample=
"false"
enableSelectByExample=
"false"
selectByExampleQueryId=
"false"
/> -->
<!--生成對應表及類名 -->
<!-- <table tableName=
"t_blogger"
domainObjectName=
"Blogger"
></table> -->
<!-- <table tableName=
"t_blog"
domainObjectName=
"Blog"
></table>
<table tableName=
"t_blogtype"
domainObjectName=
"Blogtype"
></table> -->
<!-- <table tableName=
"t_comment"
domainObjectName=
"Comment"
></table> -->
<!-- <table tableName=
"t_link"
domainObjectName=
"Link"
></table> -->
<table tableName=
"user"
domainObjectName=
"User"
></table>
</context>
</generatorConfiguration>
|
創建service及其實現類:
1
2
3
4
5
6
7
8
|
package
com.neya.service;
import
com.neya.domain.User;
public
interface
UserService {
public
User getUserById(Integer id);
}
|
實現類:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
package
com.neya.service.impl;
import
org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.stereotype.Service;
import
com.neya.domain.User;
import
com.neya.mapper.UserMapper;
import
com.neya.service.UserService;
@Service
(
"userService"
)
public
class
UserServiceImpl
implements
UserService {
@Autowired
private
UserMapper userMapper;
@Override
public
User getUserById(Integer id) {
// TODO Auto-generated method stub
return
userMapper.selectByPrimaryKey(id);
}
}
|
在src/test/java內創建測試類TestUser,直接使用spring-test測試:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
package
com.neya.test;
import
org.junit.Test;
import
org.junit.runner.RunWith;
import
org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.test.context.ContextConfiguration;
import
org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import
com.neya.service.UserService;
@RunWith
(SpringJUnit4ClassRunner.
class
)
//表示繼承了SpringJUnit4ClassRunner類
@ContextConfiguration
(locations = {
"classpath:applicationContext-*.xml"
})
public
class
TestUser {
@Autowired
private
UserService userService;
@Test
public
void
test() {
System.out.println(userService.getUserById(
1
));
}
}
|
需要重點提一下,在這個測試過程中遇到了一個坑,按照以上的代碼及配置,運行test()方法后會報錯並提示無法注入UserService,而UserServiceImpl類上明明已經添加了@Service注解,報錯信息如下所示:
23:34:16,959 ERROR TestContextManager:215 - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@215be6bb] to prepare test instance [com.neya.test.TestUser@224edc67]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.neya.test.TestUser': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.neya.service.UserService com.neya.test.TestUser.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.neya.service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:{@org.springframework.beans.factory.annotation.Autowired(required=true)}
而此時添加了springMVC相關的配置之后,在controller中卻可以正常注入UserService,被這個問題困擾了好久,后來發現,在/src/test/java中配置的掃描的配置文件,會默認到/src/test/resource中去尋找,而maven創建的項目中並沒有此資源包,於是自己創建了此資源包,並將context配置文件以及db.properties拷貝到此目錄下,終於可以正常注入並查詢到相應信息:
至此,spring-mybatis整合完畢。
2.2 整合springMVC
1.配置文件springmvc.xml
主要是自動掃描注解、視圖解析、注解啟動這幾個部分
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
<?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:mvc=
"http://www.springframework.org/schema/mvc"
xmlns:context=
"http://www.springframework.org/schema/context"
xmlns:aop=
"http://www.springframework.org/schema/aop"
xmlns:tx=
"http://www.springframework.org/schema/tx"
xsi:schemaLocation="http:
//www.springframework.org/schema/beans
http:
//www.springframework.org/schema/beans/spring-beans-4.0.xsd
http:
//www.springframework.org/schema/mvc
http:
//www.springframework.org/schema/mvc/spring-mvc-4.0.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.neya"
></context:component-scan>
<mvc:annotation-driven></mvc:annotation-driven>
<mvc:resources location=
"/WEB-INF/static/"
mapping=
"/static/**"
/>
<bean id=
"viewResolver"
class
=
"org.springframework.web.servlet.view.InternalResourceViewResolver"
>
<property name=
"viewClass"
value=
"org.springframework.web.servlet.view.JstlView"
></property>
<property name=
"prefix"
value=
"/"
/>
<property name=
"suffix"
value=
".jsp"
/>
</bean>
<!-- 圖片上傳解析器 后續使用 -->
<!-- <bean id=
"multipartResolver"
class
=
"org.springframework.web.multipart.commons.CommonsMultipartResolver"
>
設置上傳文件的最大尺寸為5MB
<property name=
"maxUploadSize"
>
<value>
5242880
</value>
</property>
</bean> -->
</beans>
|
2.配置web.xml文件
這里主要是引入applicationContext的配置文件以及SpringMVC的servlet還有編碼過濾:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
<?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_2_5.xsd"
id=
"WebApp_ID"
version=
"2.5"
>
<display-name>MyBlog</display-name>
<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>
<!-- 加載Spring配置文件 -->
<listener>
<listener-
class
>org.springframework.web.context.ContextLoaderListener</listener-
class
>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-*.xml</param-value>
</context-param>
<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:springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.
do
</url-pattern>
</servlet-mapping>
<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>
</web-app>
|
3.測試
為方便起見,本次直接在src/main/java中直接測試,創建包com.neya.controller及其下TestController類:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
package
com.neya.controller;
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.ResponseBody;
import
org.springframework.web.servlet.ModelAndView;
import
com.neya.domain.User;
import
com.neya.service.UserService;
@Controller
@RequestMapping
(
"/test"
)
public
class
TestController {
@Autowired
private
UserService userService;
// @ResponseBody //使用此注解不走視圖解析器,可以直接返回字符串,或者添加相應json配置后返回json數據到網頁
@RequestMapping
(
"/testUser"
)
public
ModelAndView testUser() {
ModelAndView mv=
new
ModelAndView();
User user=userService.getUserById(
1
);
mv.addObject(
"user"
, user);
mv.setViewName(
"test"
);
// return user.getUsername();
return
mv;
}
}
|
在webapp下創建test.jsp,簡單輸出查詢到的數據:
1
2
3
4
5
6
7
8
9
10
11
12
|
<%@ 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>
${user.username }
</body>
</html>
|
在瀏覽器中輸入localhost:8080/MyBlog/test/testUser.do,顯示結果如下:
至此,SSM三大框架全部整合完畢,后續將在此基礎上繼續添加其他功能。