基于SSM框架的个人博客系统(一)环境搭建

本系列文章将从环境搭建开始逐步详细地记录一个基于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一项,如下图:

Snipaste_2018-02-10_18-48-33_maven1.png

然后填写Group Id 和Artifact Id:

Snipaste_2018-02-10_18-51-10_projectId.png

然后点击finished。接下来由于maven项目默认的jdk版本较低,在项目名右键选择Build Path->Configure Build Path,将低版本的jdk移除并添加较高版本的jdk以及tomcat7,如图:

Snipaste_2018-02-10_18-52-55_buildpath.png

接下来是此时项目的目录结构:

Snipaste_2018-02-10_18-56-23_初始工程目录.png

将项目添加到tomcat服务器并启动,在浏览器中输入localhost:8080/MyBlog/ ,显示如下表明项目初步搭建成功。

Snipaste_2018-02-10_18-54-24_maven_project_test.png

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拷贝到此目录下,终于可以正常注入并查询到相应信息:

Snipaste_2018-02-11_00-07-11_test1.png

至此,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,显示结果如下:

Snipaste_2018-02-11_16-56-15_controllerTest.png

至此,SSM三大框架全部整合完毕,后续将在此基础上继续添加其他功能。

转载于:https://www.cnblogs.com/neya/p/8519526.html

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
个人博客系统主要用于发表个人博客,记录个人生活日常,学习心得,技术分享等,供他人浏览,查阅,评论等。本系统结构如下: (1)博主端: 登录模块:登入后台管理系统:首先进入登录页面,需要输入账号和密码。它会使用Shiro进行安全管理,对前台输入的密 码进行加密运算,然后与数据库中的进行比较。成功后才能登入后台系统。 博客管理模块: 博客管理功能分为写博客和博客信息管理。写博客是博主用来发表编写博客的,需要博客标题,然后选择博 客类型,最后将博客内容填入百度的富文本编辑器中,点击发布博客按钮即可发布博客。 博客类别管理模块:博主类别管理系统可以添加,修改和删除博客类型名称和排序序号。将会显示到首页的按日志类别区域。 游客可以从这里查找相关的感兴趣的博客内容 评论信息管理模块:评论管理功能分为评论审核和评论信息管理两部分。评论审核是当有游客或自己发表了评论之后,博主需 要在后台管理系统中审核评论。若想将此评论显示在页面上则点击审核通过,否则点击审核不通过。 个人信息管理模块:修改博主的个人信息,可以修改昵称,个性签名,可以添加个人头像,修改个人简介; 系统管理功能模块:友情链接管理,修改密码,刷新系统缓存和安全退出,友情链接管理可以添加,修改,删除友情链接网址 (2)游客端: 查询博客: 查询具体哪一篇博客 查看博客内容: 查看博客内容 查看博主个人信息:查看博主个人简介 发表评论: 可以评论具体某篇博客 友情链接: 查看友情链接
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值