首页 > 代码库 > Spring+Mybatis+SpringMVC整合
Spring+Mybatis+SpringMVC整合
这是来到博客园的第一篇文章,做java开发也好几年了,想从现在开始,在这里将自己会的、学到的做个系统的整理,便于自己掌握的更深、也便于以后复习、还便于给刚入门的攻城师们一点点参考(嘿嘿)……好了,废话不多说,第一篇文章就从最基本的javaWeb开发的三大框架整合开始。
至于为什么是从Spring+Mybatis+SpringMVC开始,而不是Spring+Struts+Hibernate,那是因为现在各个公司使用Spring+Mybatis+SpringMVC的越来越多,而Struts则是使用率越来越少,尤其是Struts爆出了多个重大安全漏洞之后,更加让公司在选择框架时首选SpringMVC;而Hibernate嘛,倒是一直使用率很广,但是我觉得还是从Mybatis入门较好,因为Mybatis需要手写SQL语句,对于我们学习数据库还是有好处的(个人意见哈);下面正式开始。
一、我们采用maven来构建和管理我们的项目,IDE工具嘛就随便啦,看自己爱好,这里我们用Intellij IDEA
第一步:先新建一个Maven工程,取名字叫做UserDemo(就当我们在做一个用户管理系统了哈,不会使用maven的请自行百度),建好之后的工程目录如下图
各个模块表示什么意思,放什么东西上图都有标注,这就是一个标准的web项目,现在里面的包和配置文件都还是空的,下面我们就开始将这个项目搭建起来
第二步:修改pom.xml文件,添加我们需要的jar包和一些构建的配置项,代码如下:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <modelVersion>4.0.0</modelVersion> 6 7 <groupId>com.tian.demo</groupId> 8 <artifactId>demo</artifactId> 9 <packaging>war</packaging> 10 <version>1.0-SNAPSHOT</version> 11 <name>UserDemo Maven Webapp</name> 12 <url>http://maven.apache.org</url> 13 14 <properties> 15 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 16 <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> 17 <maven.compiler.encoding>UTF-8</maven.compiler.encoding> 18 <compiler.version>1.7</compiler.version> 19 <!-- spring版本 4.3.5--> 20 <spring.version>4.2.9.RELEASE</spring.version> 21 </properties> 22 23 <dependencies> 24 <dependency> 25 <groupId>junit</groupId> 26 <artifactId>junit</artifactId> 27 <version>3.8.1</version> 28 <scope>test</scope> 29 </dependency> 30 <dependency> 31 <groupId>javax.servlet</groupId> 32 <artifactId>javax.servlet-api</artifactId> 33 <version>3.1.0</version> 34 <scope>provided</scope> 35 </dependency> 36 <!-- 日志记录 --> 37 <dependency> 38 <groupId>org.slf4j</groupId> 39 <artifactId>slf4j-api</artifactId> 40 <version>1.7.22</version> 41 </dependency> 42 <dependency> 43 <groupId>org.slf4j</groupId> 44 <artifactId>slf4j-log4j12</artifactId> 45 <version>1.7.22</version> 46 </dependency> 47 <!-- 添加了spring-web就会自动加载关联的 aop、core、context、commons-logging等这几个jar,不用在另行添加 --> 48 <dependency> 49 <groupId>org.springframework</groupId> 50 <artifactId>spring-web</artifactId> 51 <version>${spring.version}</version> 52 </dependency> 53 <dependency> 54 <groupId>org.springframework</groupId> 55 <artifactId>spring-webmvc</artifactId> 56 <version>${spring.version}</version> 57 </dependency> 58 <dependency> 59 <groupId>com.fasterxml.jackson.core</groupId> 60 <artifactId>jackson-core</artifactId> 61 <version>2.8.5</version> 62 </dependency> 63 <dependency> 64 <groupId>com.fasterxml.jackson.core</groupId> 65 <artifactId>jackson-databind</artifactId> 66 <version>2.8.5</version> 67 </dependency> 68 <!-- 通过mybatis操作mysql数据库 --> 69 <dependency> 70 <groupId>org.springframework</groupId> 71 <artifactId>spring-jdbc</artifactId> 72 <version>${spring.version}</version> 73 </dependency> 74 <dependency> 75 <groupId>org.mybatis</groupId> 76 <artifactId>mybatis-spring</artifactId> 77 <version>1.3.0</version> 78 </dependency> 79 <dependency> 80 <groupId>org.mybatis</groupId> 81 <artifactId>mybatis</artifactId> 82 <version>3.4.1</version> 83 </dependency> 84 <dependency> 85 <groupId>com.alibaba</groupId> 86 <artifactId>druid</artifactId> 87 <version>1.0.27</version> 88 </dependency> 89 <dependency> 90 <groupId>mysql</groupId> 91 <artifactId>mysql-connector-java</artifactId> 92 <version>5.1.40</version> 93 </dependency> 94 <!-- jsp页面标签 --> 95 <dependency> 96 <groupId>jstl</groupId> 97 <artifactId>jstl</artifactId> 98 <version>1.2</version> 99 </dependency> 100 <!-- 对象与JSON串相互转换 --> 101 <dependency> 102 <groupId>com.alibaba</groupId> 103 <artifactId>fastjson</artifactId> 104 <version>1.2.23</version> 105 </dependency> 106 <dependency> 107 <groupId>javax.persistence</groupId> 108 <artifactId>persistence-api</artifactId> 109 <version>1.0</version> 110 </dependency> 111 </dependencies> 112 113 <!-- 项目构建相关的配置 --> 114 <build> 115 <finalName>userdemo</finalName> 116 <resources> 117 <!-- 构建的时候包含properties文件 --> 118 <resource> 119 <directory>src/main/resources</directory> 120 <includes> 121 <include>**/*.properties</include> 122 </includes> 123 </resource> 124 <!-- 构建的时候包含xml文件 --> 125 <resource> 126 <directory>src/main/resources</directory> 127 <includes> 128 <include>**/*.xml</include> 129 </includes> 130 </resource> 131 </resources> 132 <plugins> 133 <plugin> 134 <artifactId>maven-compiler-plugin</artifactId> 135 <version>3.1</version> 136 <configuration> 137 <source>${compiler.version}</source> 138 <target>${compiler.version}</target> 139 <encoding>utf-8</encoding> 140 </configuration> 141 </plugin> 142 <plugin> 143 <groupId>org.apache.maven.plugins</groupId> 144 <artifactId>maven-war-plugin</artifactId> 145 <version>2.1.1</version> 146 <configuration> 147 <archive> 148 <addMavenDescriptor>false</addMavenDescriptor> 149 </archive> 150 <warName>web-demo</warName> 151 <webResources> 152 <resource> 153 <directory>src/main/resources</directory> 154 <targetPath>WEB-INF/classes</targetPath> 155 <filtering>true</filtering> 156 </resource> 157 </webResources> 158 </configuration> 159 </plugin> 160 <plugin> 161 <groupId>org.apache.maven.plugins</groupId> 162 <artifactId>maven-surefire-plugin</artifactId> 163 <configuration> 164 <skip>true</skip> 165 <testFailureIgnore>true</testFailureIgnore> 166 </configuration> 167 </plugin> 168 <plugin> 169 <groupId>org.apache.maven.plugins</groupId> 170 <artifactId>maven-enforcer-plugin</artifactId> 171 <version>1.4.1</version> 172 <executions> 173 <execution> 174 <id>enforce</id> 175 <configuration> 176 <rules> 177 <dependencyConvergence /> 178 </rules> 179 </configuration> 180 <goals> 181 <goal>enforce</goal> 182 </goals> 183 </execution> 184 </executions> 185 </plugin> 186 </plugins> 187 </build> 188 </project>
pom.xml文件配置好之后,现在我们可以用maven构建一下,就可以自动的下载我们需要的jar包,本项目所需的所有jar如下图
二、准备好pom之后,我们在数据库中准备一点数据,用来测试使用,这里用mysql数据库,mysql的安装使用还是自己百度哈;
我们准备数据库名字叫做userdemo,需要的表就一个,叫my_user,里面共有(user_is,user_name,user_password,user_age,user_phone)五个字段,分别表示用户ID、用户名、用户密码、用户年龄、用户手机
在数据库中准备5条测试数据,我就直接把mysql的sql语句代码贴出来了
SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for my_user -- ---------------------------- DROP TABLE IF EXISTS `my_user`; CREATE TABLE `my_user` ( `user_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `user_name` varchar(100) NOT NULL COMMENT ‘用户名‘, `user_password` varchar(100) NOT NULL COMMENT ‘用户密码‘, `user_age` int(5) NOT NULL COMMENT ‘用户年龄‘, `user_phone` varchar(50) NOT NULL COMMENT ‘用户手机号‘, PRIMARY KEY (`user_id`) ) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of my_user -- ---------------------------- INSERT INTO `my_user` VALUES (‘1‘, ‘张三‘, ‘111111‘, ‘20‘, ‘18011112222‘); INSERT INTO `my_user` VALUES (‘2‘, ‘李四‘, ‘222222‘, ‘21‘, ‘18111112222‘); INSERT INTO `my_user` VALUES (‘3‘, ‘王五‘, ‘333333‘, ‘22‘, ‘18211112222‘); INSERT INTO `my_user` VALUES (‘4‘, ‘赵六‘, ‘444444‘, ‘23‘, ‘18511112222‘); INSERT INTO `my_user` VALUES (‘5‘, ‘马七‘, ‘555555‘, ‘24‘, ‘18711112222‘);
三、准备好测试数据之后,我们就要准备需要的代码,按照MVC的设计模式,分别准备entity、dao、service、controller的代码,我就直接把代码贴出来了
1、实体类User.java
package com.user.demo.entity; import java.io.Serializable; /** * 用户User实体类 */ public class User implements Serializable{ private Long userId; private String userName; private String userPassword; private Integer userAge; private String userPhone; public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPassword() { return userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword; } public Integer getUserAge() { return userAge; } public void setUserAge(Integer userAge) { this.userAge = userAge; } public String getUserPhone() { return userPhone; } public void setUserPhone(String userPhone) { this.userPhone = userPhone; } }
2、Dao接口UserDao.java(这里就只写了两个方法哈,一个保存一个查询,仅供测试)
package com.user.demo.dao; import com.user.demo.entity.User; import org.springframework.stereotype.Repository; import java.util.List; /** * 操作数据的DAO */ @Repository public interface UserDao { //查询全部User List<User> findAll(); //保存User void saveUser(User user); }
3、service接口IUserService.java
package com.user.demo.service; import com.user.demo.entity.User; import java.util.List; /** * Service接口 */ public interface IUserService { List<User> findAll(); void saveUser(User user); }
4、service接口的实现类
package com.user.demo.service.impl; import com.user.demo.dao.UserDao; import com.user.demo.entity.User; import com.user.demo.service.IUserService; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.List; /** * Service接口实现类 */ @Service public class UserServiceImpl implements IUserService { @Resource private UserDao userDao; @Override public List<User> findAll() { List<User> users = users = userDao.findAll(); return users; } @Override @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) //事物 public void saveUser(User user) { userDao.saveUser(user); } }
5、控制器类UserController.java
package com.user.demo.controller; import com.user.demo.entity.User; import com.user.demo.service.IUserService; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import javax.annotation.Resource; import java.util.List; /** * 控制器类 */ @Controller @RequestMapping("/user") public class UserController { @Resource private IUserService userService; @RequestMapping(value = "/find", method = RequestMethod.GET) public ModelAndView findAll(ModelAndView mv){ List<User> userList = userService.findAll(); mv.addObject("userList", userList); mv.setViewName("user"); return mv; } @RequestMapping(value = "/save", method = RequestMethod.POST) public ModelAndView saveUser(User u, ModelAndView mv){ userService.saveUser(u); mv.setViewName("redirect:/user/find"); //保存完后重定向到原来页面 return mv; } }
四、代码写完之后,我们就要准备配置文件
1、先准备Mybatis的SQL脚本文件UserDaoMapper.xml,放在/resources/mybatisMapper/下面,代码如下
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.user.demo.dao.UserDao"> <resultMap id="userMap" type="com.user.demo.entity.User"> <id property="userId" column="user_id" /> <result property="userName" column="user_name"/> <result property="userPassword" column="user_password"/> <result property="userAge" column="user_age"/> <result property="userPhone" column="user_phone"/> </resultMap> <select id="findAll" resultMap="userMap"> SELECT user_id,user_name,user_password,user_age,user_phone FROM my_user </select> <insert id="saveUser" parameterType="com.user.demo.entity.User" useGeneratedKeys="true" keyProperty="userId"> INSERT INTO my_user(user_name,user_password,user_age,user_phone) VALUES (#{userName}, #{userPassword}, #{userAge}, #{userPhone}) </insert> </mapper>
2、准备数据源配置文件jdbc.properties,放在/resources/下面,代码如下
#数据库连接信息 datasource.mysql.url=jdbc:mysql://127.0.0.1:3306/userdemo?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull datasource.mysql.username=root datasource.mysql.password=123456 datasource.mysql.driverClassName=com.mysql.jdbc.Driver datasource.initial.size=5 datasource.max.size=10 datasource.min.idle=0 datasource.validation.query=select 1
3、我们要用mybatis来操作mysql,所以我们还要准备一份mybatis的配置文件mybatis-config.xml,放在/resources/下面,代码如下
<?xml version="1.0" encoding="UTF-8" ?> <!-- mybatis配置 --> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <setting name="lazyLoadingEnabled" value="false" /> <setting name="cacheEnabled" value="false" /> <setting name="logImpl" value="STDOUT_LOGGING" /> </settings> <typeAliases> <!-- 扫描实体类所在的包 --> <package name="com.user.demo.entity" /> <!-- 如果有多个包,如vo,dto等,都可以直接在下面添加 --> <!--<package name="com.demo.web.vo" />--> </typeAliases> </configuration>
4、到此我们和数据库操作相关的配置已经全部完成,那么怎么把这些组织起来呢,当然是用spring,我们在/resources/springConfig/下面增加applicationContext-db.xml文件,如图
此文件专门用来配置spring对mybatis的集成操作,下面还有一个applicationContext-resource.xml文件用来最后加载各个配置文件,我们后面会说到,接下来贴出applicationContext-db.xml的代码如下
<?xml version="1.0" encoding="UTF-8"?> <!-- 数据源及mybatis相关配置 --> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName" value="${datasource.mysql.driverClassName}" /> <property name="url" value="${datasource.mysql.url}" /> <property name="username" value="${datasource.mysql.username}" /> <property name="password" value="${datasource.mysql.password}" /> <property name="initialSize" value="${datasource.initial.size}" /> <property name="maxActive" value="${datasource.max.size}" /> <property name="minIdle" value="${datasource.min.idle}" /> <property name="maxWait" value="60000" /> <property name="poolPreparedStatements" value="false" /> <property name="validationQuery" value="${datasource.validation.query}" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <property name="testWhileIdle" value="true" /> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <property name="minEvictableIdleTimeMillis" value="300000" /> <property name="removeAbandoned" value="true" /> <property name="removeAbandonedTimeout" value="1800" /> <property name="logAbandoned" value="true" /> <property name="filters" value="stat" /> <property name="proxyFilters"> <list> <bean class="com.alibaba.druid.filter.logging.Log4jFilter"> <property name="statementExecutableSqlLogEnable" value="true" /> </bean> </list> </property> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 就是在这里加载数据库和mybatis的配置文件 --> <property name="configLocation" value="classpath:mybatis-config.xml" /> <property name="mapperLocations"> <list> <value>classpath:mybatisMapper/*.xml</value> </list> </property> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.user.demo.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" /> </beans>
至此,我们的数据库相关的配置准备工作已经全部完成,胜利在望啊有木有~~接下来我们配置Spring-MVC。
5、Spring-mvc的配置,准备spring-mvc.xml文件,放在/resources/下面,代码如下
<?xml version="1.0" encoding="UTF-8"?> <!--spring mvc配置--> <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" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.3.xsd"> <!-- 扫描路径 --> <context:component-scan base-package="com.user.demo"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <context:property-placeholder location="classpath:*.properties" /> <!-- 配置根视图 --> <mvc:view-controller path="/" view-name="index" /> <!-- 激活基于注解的配置 --> <mvc:annotation-driven> <!-- json返回时默认的转换器,如果不需要返回json結果,可以不用配置 --> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> <!--如果希望返回的json数据中日期能按照某种格式显示,可以这样配置--> <property name="objectMapper"> <bean class="com.fasterxml.jackson.databind.ObjectMapper"> <property name="dateFormat"> <bean class="java.text.SimpleDateFormat"> <constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss" /> </bean> </property> </bean> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- 静态资源配置,比如我们前端页面需要用到的图片啊,字体文件什么的可以放在这个下面,注意resource文件夹是在webapp下面 --> <mvc:resources location="/resource/" mapping="/resource/**"></mvc:resources> <!-- 视图层配置 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
6、spring-mvc的配置写好之后,因为系统需要一个记录日志的地方,这里我们用log4j来记录日志,所以还要一个配置日志的文件,新建log4j.properties放在/resources/下面,代码如下
log4j.rootLogger=INFO,L,stdout,M log4j.appender.L=org.apache.log4j.DailyRollingFileAppender #日志文件保存的位置 log4j.appender.L.File=D:\\UserDemo.log log4j.appender.L.Append=true log4j.appender.L.Threshold=INFO log4j.appender.L.layout=org.apache.log4j.PatternLayout log4j.appender.L.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ :%c:%L ] - [ %p ] %m%n log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %p [%c] %m%n log4j.logger.com.ibatis=INFO log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=INFO log4j.logger.com.ibatis.common.jdbc.ScriptRunner=INFO log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=INFO log4j.logger.java.sql.Connection=INFO log4j.logger.java.sql.Statement=INFO log4j.logger.java.sql.PreparedStatement=INFO log4j.logger.druid.sql.Statement=debug,stdout
7、到此我们所有的配置文件都已经准备完毕,还有一个webConfig.properties文件,待后面有需要的时候使用,比如配置上传文件的存储位置等;然后我们需要有一个统一的地方加载所有的配置文件,让spring可以找到,我们在/resources/springConfig/下面建立applicationContext-resource.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 加载所有的properties文件 --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:*.properties</value> </list> </property> </bean> </beans>
到这里我们所有的配置文件准备完毕,离成功只有一步之遥噢,呵呵~~
五、最后一步,准备web.xml,这个是整个web项目的入口文件,放置在/webapp/WEB-INF/下面,代码如下
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>UserDemo</display-name> <!-- 加载Spring的配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/springConfig/applicationContext-*.xml</param-value> </context-param> <!-- 统一编码 --> <filter> <filter-name>charsetEncoding</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>charsetEncoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 自动装配配置信息 地址由上面的contextConfigLocation指定 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 解决java.beans.Introspector导致的内存泄漏的问题 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- druid自带的sql操作监控 --> <servlet> <servlet-name>DruidStatView</servlet-name> <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>DruidStatView</servlet-name> <url-pattern>/druid/*</url-pattern> </servlet-mapping> <!-- 前端控制器 --> <servlet> <servlet-name>spring-mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 默认加载/WEB-INF/[servlet-name]-servlet.xml,通过下面的contextConfigLocation修改 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring-mvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
六、最后,为了测试,我们准备一个jsp页面,来直观的看到我们的成果,在/webapp/WEB-INF/pages/下面新建user.jsp,这个名字需要和controller中对应的视图名保持一致哈,就是这里
jsp页面中,我们使用jstl表达式来获取数据,至于jstl的用法嘛,还是自己百度哈,非常的简单,直接贴上user.jsp的代码如下
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%> <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, target-densitydpi=medium-dpi, initial-scale=0.5, minimum-scale=0.5, maximum-scale=0.5, user-scalable=no" /> <meta content="yes" name="apple-mobile-web-app-capable" /> <meta content="black" name="apple-mobile-web-app-status-bar-style" /> <meta content="telephone=no" name="format-detection" /> <title>用户列表</title> </head> <body> <c:set var="contextPath" value="${pageContext.request.contextPath}"/> <c:forEach items="${userList}" var="user" varStatus="status"> <div> <p>用户ID:${user.userId}</p> <p>用户名:${user.userName}</p> <p>用户密码:${user.userPassword}</p> <p>用户年龄:${user.userAge}</p> <p>用户手机:${user.userPhone}</p> </div> </c:forEach> <form method="post" action="${contextPath}/user/save"> 用户名:<input type="text" name="userName"/> 用户密码:<input type="password" name="userPassword"/> 用户年龄:<input type="number" name="userAge"/> 用户手机:<input type="number" name="userPhone"/> <input type="submit" value="提交"/> </form> </body> </html>
七、接下来,用Tomcat启动此项目,浏览器中输入http://localhost:8080/userdemo/user/find,看到如下图片
OK,大功告成,我们来添加一个用户试试,如下
点击“提交”,结果为
已经保存成功了,到此我们的Spring+Mybatis+SpringMVC框架整合开发web项目已经圆满完成,当然了这个功能做的非常的简单,后面我会在这个项目的基础上,拓展许多东西,包括mysql数据库读写分离、集成redis缓存数据、tomcat集群等等;
作为一个自学java编程的程序员(大学没学过),工作的几年来确实趟过不少的坑,现在把自己会的一些东西分享出来,也是希望给刚入门的一些朋友们稍作指引,少跳一些坑;因为我也是在不断的学习当中,如果哪位大神对我的文章有什么指教,非常欢迎指导,大家共同探讨!
好了,第一篇博客就写到这,请原谅学工科的人的文笔哈,大家就将就着看,有什么意见欢迎留言讨论;后面我还会继续发一些java的文章,还会发一些关于前端开发(HTML/CSS/JS)的文章,欢迎关注,一起进步!
Spring+Mybatis+SpringMVC整合