上一次复习搭建了SpringMVC+Mybatis,这次搭建一下SpringMVC,采用的是SpringJDBC,没有采用任何其他的ORM框架,SpringMVC提供了一整套的WEB框架,所以如果想搭建纯的SpringMVC的话,而且不必映入别的任何框架,SpringMVC都给我们提供了,下面试spring + SpringMVC的详细搭建过程。
项目包含:数据库MySQL(其实那个数据库都无所谓),连接池采用的是c3p0。
数据表很简单,user_info
Maven项目搭建一笔带过(前面有介绍),其搭建后的webapp结构项目如下:
导入所需的spring,以及数据源,spring-mvc,json等依赖。
pom.xml
<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.0modelVersion>
<groupId>org.andy.springmvcgroupId>
<artifactId>springmvc_demoartifactId>
<packaging>warpackaging>
<version>0.0.1-SNAPSHOTversion>
<name>springmvc_demo Maven Webappname>
<url>http://maven.apache.orgurl>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<spring.version>4.1.4.RELEASEspring.version>
<jackson.version>2.5.0jackson.version>
properties>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-beansartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>${spring.version}version>
<scope>testscope>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.34version>
dependency>
<dependency>
<groupId>com.mchangegroupId>
<artifactId>c3p0artifactId>
<version>0.9.5-pre10version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.3version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-annotationsartifactId>
<version>${jackson.version}version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-coreartifactId>
<version>${jackson.version}version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>${jackson.version}version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>servlet-apiartifactId>
<version>3.0-alpha-1version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>commons-iogroupId>
<artifactId>commons-ioartifactId>
<version>2.4version>
dependency>
<dependency>
<groupId>commons-fileuploadgroupId>
<artifactId>commons-fileuploadartifactId>
<version>1.2.2version>
dependency>
dependencies>
<build>
<finalName>springmvc_demofinalName>
<plugins>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-surefire-pluginartifactId>
<version>2.4.2version>
<configuration>
<skipTests>trueskipTests>
configuration>
plugin>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-war-pluginartifactId>
<version>2.3version>
<configuration>
<webXml>src/main/webapp/WEB-INF/web.xmlwebXml>
configuration>
plugin>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-javadoc-pluginartifactId>
<version>2.9.1version>
<configuration>
<javadocDirectory>target/javadocjavadocDirectory>
<reportOutputDirectory>target/javadocreportOutputDirectory>
<charset>UTF-8charset>
<encoding>UTF-8encoding>
<docencoding>UTF-8docencoding>
<show>privateshow>
configuration>
plugin>
<plugin>
<groupId>org.codehaus.cargogroupId>
<artifactId>cargo-maven2-pluginartifactId>
<version>1.0version>
<configuration>
<container>
<containerId>tomcat6xcontainerId>
<home>D:\WebServer\apache-tomcat-6.0.39home>
container>
<configuration>
<type>existingtype>
<home>D:\WebServer\apache-tomcat-6.0.39home>
configuration>
configuration>
plugin>
plugins>
build>
project>
src/main/resources/applicationConfig.xml
#application all config
#jdbc c3p0
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf-8
jdbc.username = root
jdbc.password = 12345
src/main/resources/applicationContext.xml
xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
">
<context:property-placeholder location="classpath*:/applicationConfig.properties" />
<context:component-scan base-package="org.andy.shop.dao.Impl,org.andy.shop.service.Impl" />
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${jdbc.driver}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="checkoutTimeout" value="30000" />
<property name="idleConnectionTestPeriod" value="30" />
<property name="maxIdleTime" value="30" />
<property name="initialPoolSize" value="5" />
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="acquireIncrement" value="5" />
bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
bean>
<bean id="namedParameterJdbcTemplate"
class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="dataSource" />
bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
bean>
<bean id="transactionInterceptor"
class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property name="transactionManager" ref="transactionManager" />
<property name="transactionAttributes">
<props>
<prop key="save*">PROPAGATION_REQUIREDprop>
<prop key="del*">PROPAGATION_REQUIREDprop>
<prop key="update">PROPAGATION_REQUIREDprop>
<prop key="get*">PROPAGATION_SUPPORTS,readOnlyprop>
<prop key="find*">PROPAGATION_SUPPORTS,readOnlyprop>
<prop key="*">PROPAGATION_REQUIREDprop>
props>
property>
bean>
<bean
class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="beanNames">
<list>
<value>*Servicevalue>
list>
property>
<property name="interceptorNames">
<list>
<value>transactionInterceptorvalue>
list>
property>
bean>
beans>
上面配置的详细功能已写出。
src/main/resources/log4j.properties
### set log levels ###
log4j.rootLogger = INFO , C , D , E
### console ###
log4j.appender.C = org.apache.log4j.ConsoleAppender
log4j.appender.C.Target = System.out
log4j.appender.C.layout = org.apache.log4j.PatternLayout
log4j.appender.C.layout.ConversionPattern = [springmvc_demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n
### log file ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = ../logs/springmvc-mybatis-demo.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = INFO
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = [springmvc_demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n
### exception ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File = ../logs/springmvc-mybatis-demo_error.log
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = [springmvc_demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n
创建如下包:
org.andy.shop.entity中添加
package org.andy.shop.entity;
import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import org.springframework.jdbc.core.RowMapper;
/**
* 实现数据表与字段的映射
*
* @author andy
*
*/
public class UserInfo implements RowMapper
/**
*
*/
private static final long serialVersionUID = -8823504831198719837L;
private Integer id;
private String uname;
private Integer unumber;
private Date uRegisterTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname == null ? null : uname.trim();
}
public Integer getUnumber() {
return unumber;
}
public void setUnumber(Integer unumber) {
this.unumber = unumber;
}
public Date getuRegisterTime() {
return uRegisterTime;
}
public void setuRegisterTime(Date uRegisterTime) {
this.uRegisterTime = uRegisterTime;
}
@Override
public UserInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
UserInfo userInfo = new UserInfo();
userInfo.setId(rs.getInt("id"));
userInfo.setUname(rs.getString("uname"));
userInfo.setUnumber(rs.getInt("unumber"));
userInfo.setuRegisterTime(rs.getDate("uregister_time"));
return userInfo;
}
}
实现RowMapper接口是为了方便SpringJDBC管理实体与数据库字段的映射。
org.andy.shop.dao添加通用Dao接口
GenericDao.Java:
package org.andy.shop.dao;
import java.io.Serializable;
import java.util.List;
/**
* 创建时间:2015-1-30 上午10:11:59
*
* @author andy
* @version 2.2
*
* Dao通用接口
*/
interface GenericDao
T getById(PK id);
List
PK save(T entity);
}
添加UserInfoDao.java
package org.andy.shop.dao;
import org.andy.shop.entity.UserInfo;
/**
* 创建时间:2015-1-30 上午11:22:37
*
* @author andy
* @version 2.2
*
* UserInfoDao
*/
public interface UserInfoDao extends GenericDao
}
在org.andy.shop.dao.Impl包中添加UserInfoDao的Dao实现类
UserInfoDaoImpl.java
package org.andy.shop.dao.Impl;
import java.util.List;
import org.andy.shop.dao.UserInfoDao;
import org.andy.shop.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
/**
* 创建时间:2015-1-30 上午11:25:30
*
* @author andy
* @version 2.2
*
* UserInfoDao实现类
*/
@Repository("userInfoDao")
public class UserInfoDaoImpl implements UserInfoDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
@Override
public UserInfo getById(Integer id) {
String sql = "SELECT * FROM user_info WHERE id = ?";
UserInfo userInfo = jdbcTemplate.queryForObject(sql, new UserInfo(),
new Object[] { id });
return userInfo;
}
@Override
public List
String sql = "SELECT * FROM user_info";
List
return userInfos;
}
@Override
public Integer save(UserInfo entity) {
String sql = "INSERT INTO user_info(uname, unumber, uregister_time) VALUES(:uname, :unumber, :uregister_time)";
MapSqlParameterSource paramSource = new MapSqlParameterSource();
paramSource.addValue("uname", entity.getUname());
paramSource.addValue("unumber", entity.getUnumber());
paramSource.addValue("uregister_time", entity.getuRegisterTime());
int result = namedParameterJdbcTemplate.update(sql, paramSource);
return result;
}
}
org.andy.shop.dao.service添加UserInfoService接口
UserInfoService.java
package org.andy.shop.service;
import java.util.List;
import org.andy.shop.entity.UserInfo;
/**
* 创建时间:2015-1-30 上午11:31:34
*
* @author andy
* @version 2.2
*
* UserInfoService 接口
*/
public interface UserInfoService {
// 通过Id查询UserInfo
UserInfo getById(Integer id);
// 查询全部的UserInfo
List
// 添加UserInfo
Integer save(UserInfo userInfo);
}
实现UserInfoService接口
package org.andy.shop.service.Impl;
import java.util.List;
import org.andy.shop.dao.UserInfoDao;
import org.andy.shop.entity.UserInfo;
import org.andy.shop.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* 创建时间:2015-1-30 上午11:40:19
*
* @author andy
* @version 2.2 实现接口
*/
@Service("userInfoService")
public class UserInfoServiceImpl implements UserInfoService {
@Autowired
private UserInfoDao userInfoDao;
@Override
public UserInfo getById(Integer id) {
return userInfoDao.getById(id);
}
@Override
public List
return userInfoDao.findAll();
}
@Override
public Integer save(UserInfo userInfo) {
return userInfoDao.save(userInfo);
}
}
单元测试Service中的方法,如果全部成功,Spring和数据连接池搭建完成。
package org.andy.shop.test.service;
import java.util.Date;
import java.util.List;
import org.andy.shop.entity.UserInfo;
import org.andy.shop.service.UserInfoService;
import org.apache.log4j.Logger;
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.alibaba.fastjson.JSON;
/**
* 创建时间:2015-1-30 下午12:01:47
*
* @author andy
* @version 2.2
*/
// 引入Spring环境测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext.xml" })
public class TestUserInfoService {
private static final Logger LOGGER = Logger
.getLogger(TestUserInfoService.class);
@Autowired
private UserInfoService userInfoService;
@Test
public void testGetById() {
//测试查询对应的用户
UserInfo userInfo = userInfoService.getById(1);
LOGGER.info(JSON.toJSONStringWithDateFormat(userInfo,
"yyyy-MM-dd HH:mm:ss"));
}
@Test
public void testFindAll() {
//测试查询全部用户
List
for (UserInfo userInfo : userInfos) {
LOGGER.info(JSON.toJSONStringWithDateFormat(userInfo,
"yyyy-MM-dd HH:mm:ss"));
}
}
@Test
public void testSave() {
//测试保存用户数据
UserInfo userInfo = new UserInfo();
userInfo.setUname("xiaohonghong");
userInfo.setUnumber(5);
userInfo.setuRegisterTime(new Date());
int result = userInfoService.save(userInfo);
LOGGER.info("result = " + result);
}
}
src/main/resources/springMVC.xml
xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<context:component-scan base-package="org.andy.shop.controller" />
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8value>
<value>application/json;charset=UTF-8value>
list>
property>
bean>
mvc:message-converters>
mvc:annotation-driven>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views" />
<property name="suffix" value=".jsp" />
bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding">
<value>UTF-8value>
property>
<property name="maxUploadSize">
<value>32505856value>
property>
<property name="maxInMemorySize">
<value>4096value>
property>
bean>
beans>
添加UserInfoController控制层
package org.andy.shop.controller;
import java.util.List;
import org.andy.shop.entity.UserInfo;
import org.andy.shop.service.UserInfoService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* 创建时间:2015-2-1 下午9:40:03
*
* @author andy
* @version 2.2
*
* userInfo的控制层
*/
@Controller
@RequestMapping("/user")
public class UserInfoController {
private static final Logger LOGGER = Logger
.getLogger(UserInfoController.class);
@Autowired
private UserInfoService userInfoService;
@RequestMapping("/showInfo/{userId}")
public String showUserInfo(ModelMap modelMap, @PathVariable int userId) {
LOGGER.info("查看用户:" + userId);
UserInfo userInfo = userInfoService.getById(1);
modelMap.addAttribute("userInfo", userInfo);
return "/user/showInfo";
}
@RequestMapping("/showInfos")
public @ResponseBody List
LOGGER.info("json返回全部用户的信息");
List
return userInfos;
}
}
在webapp/WEB-INF/views/user中创建showInfo.jsp文件。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
>
<html>
<head>
<base href="<%=basePath%>" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/jquery-1.9.1.min.js">script>
<title>userInfotitle>
head>
<body>
姓名: ${userInfo.uname}
<br/>
ajax显示全部用户信息:
<div id="show_all_user">div>
body>
<script type="text/javascript">
$.ajax({
type : "get",
url : "user/showInfos.htmls",
dataType : "json",
success : function(data) {
$(data).each(
function(i, user) {
var p = " username:"
+ user.unumber + " uregister:"
+ user.uRegisterTime + "p>";
$("#show_all_user").append(p);
});
},
async : true
});
script>
html>
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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
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>springmvc_demodisplay-name>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath*:/applicationContext.xmlparam-value>
context-param>
<filter>
<filter-name>encodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>utf-8param-value>
init-param>
<init-param>
<param-name>forceEncodingparam-name>
<param-value>trueparam-value>
init-param>
filter>
<filter-mapping>
<filter-name>encodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListenerlistener-class>
listener>
<servlet>
<description>spring mvc servletdescription>
<servlet-name>restservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath*:/springMVC.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>restservlet-name>
<url-pattern>*.htmlsurl-pattern>
servlet-mapping>
<session-config>
<session-timeout>30session-timeout>
session-config>
<welcome-file-list>
<welcome-file>/index.jspwelcome-file>
welcome-file-list>
web-app>
maven编译打包部署到tomcat,测试:http://localhost:8080/springmvc_demo/user/showInfo/1.htmls分别测试添加的两个请求地址。
至此,SpringMVC搭建完毕。
喜欢我的文章的,可以关注微信公众号“测试项目开发”,需要什么内容可以在里面提,我看到后会给大家解答。