springMVC是当下很流行的轻量级JavaEE架构设计,现将整个框架搭建过程记录下来,以备后期使用。
1.使用Eclipse创建一个maven项目
2.选择项目的工作空间
3.在所列选项中选择 xxx-webapp 1.0
4.输入项目名称mvc,点击finish
5.创建的项目目录结构如下:
6.在项目根目录下创建src/test/resources目录
7.单击项目,按Alt+Enter键,进入如下界面,删除与test相关的目录:
8.此时目录结构如图:
9.编辑web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd "
version="2.5">
<!-- 配置web.xml,使其具有springmvc特性,主要配置两处,一个是ContextLoaderListener,一个是DispatcherServlet -->
<display-name>maven</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext.xml</param-value>
</context-param>
<!-- 配置ContextLoaderListener表示,该工程要以spring的方式启动。启动时会默认在/WEB-INF目录下查找applicationContext.xml
作为spring容器的配置文件,该文件里可以初始化一些bean -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 字符集过滤器 -->
<filter>
<filter-name>encodingFilter</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>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- spring mvc 配置 -->
<!-- 配置DispatcherServlet表示,该工程将采用springmvc的方式。启动时也会默认在/WEB-INF目录下查找XXX-servlet.xml作为配置文件,
XXX就是DispatcherServlet的名字,该文件中将配置两项重要的mvc特性:HandlerMapping,负责为DispatcherServlet这个前端控制器的请求查找Controller;
ViewResolver,负责为DispatcherServlet查找ModelAndView的视图解析器。
此处使用指定的配置文件spring-mvc.xml -->
<servlet>
<servlet-name>dispatch</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--<init-param>
<param-name>contextConfigLocation</param-name> -->
<!--<param-value>/WEB-INF/classes/spring-mvc-servlet.xml</param-value>-->
<!-- <param-value>classpath*:springConfig-servlet.xml</param-value>
</init-param>
-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatch</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
10.在web.xml的同级目录创建dispatch-servlet.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"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 注册HandlerMapper、HandlerAdapter两个映射类 -->
<mvc:annotation-driven />
<context:component-scan base-package="com.jiang.*" />
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="velocityConfigurer" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
<property name="resourceLoaderPath">
<value>views</value>
</property>
<property name="velocityProperties">
<props>
<prop key="file.resource.loader.cache">true</prop>
<prop key="file.resource.loader.modificationCheckInterval">2</prop>
<prop key="input.encoding">UTF-8</prop>
<prop key="output.encoding">UTF-8</prop>
<prop key="contentType">text/html;charset=UTF-8</prop>
</props>
</property>
</bean>
<!-- 访问静态资源 -->
<!--<mvc:default-servlet-handler />-->
<mvc:resources mapping="/resources/**" location="/resources/"
cache-period="86400" />
<mvc:resources mapping="/upload/**" location="/upload/"
cache-period="86400" />
<!-- 视图解析器 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver">
<property name="cache" value="false" />
<property name="prefix" value="" />
<property name="suffix" value=".vm" />
<property name="contentType" value="text/html;charset=UTF-8" />
<property name="exposeSpringMacroHelpers" value="true" />
<!--是否使用spring对宏定义的支持 -->
<property name="exposeRequestAttributes" value="true" />
<!--是否开放request属性 -->
<property name="requestContextAttribute" value="rc" />
<!--request属性引用名称 -->
<property name="exposeSessionAttributes" value="true"></property>
<property name="allowSessionOverride" value="true" />
<!--允许session覆盖旧值 VelocityViewResolver配置 -->
<property name="allowRequestOverride" value="true"></property>
<property name="layoutUrl" value="layout/default.vm" />
</bean>
</beans>
11.在同级目录继续创建applicationContext.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd"
default-autowire="byName" >
<!-- <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> -->
<!-- <property name="jndiName"> -->
<!-- <value>java:comp/env/jndi/first</value> -->
<!-- </property> -->
<!-- </bean> -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://127.0.0.1:3306/testdb</value>
</property>
<property name="username">
<value>root</value>
</property>
<property name="password">
<value>jiang</value>
</property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<!-- 数据源 -->
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描实体对象的包结构中存放实体类 -->
<property name="packagesToScan" value="com.jiang.vo" />
<!-- hibernate的相关属性配置 -->
<property name="hibernateProperties">
<value>
<!-- 设置数据库方言 -->
hibernate.dialect=org.hibernate.dialect.MySQLDialect
<!-- 设置自动创建|更新|验证数据库表结构 -->
hibernate.hbm2ddl.auto=none
<!-- 是否在控制台显示sql -->
hibernate.show_sql=true
<!-- 是否格式化sql,优化显示 -->
hibernate.format_sql=true
<!-- 是否开启二级缓存 -->
hibernate.cache.use_second_level_cache=false
<!-- 是否开启查询缓存 -->
hibernate.cache.use_query_cache=false
<!-- 创建session方式 hibernate4.x 的方式 -->
hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
<!-- 默认情况下是auto的, 不设置的话会自动去classpath下面找一个bean-validation**包,所以把它设置为none即可 -->
javax.persistence.validation.mode=none
</value>
</property>
</bean>
<!-- 创建hibernateTemplate实例 -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 定义事务管理 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 配置读取外部配置文件 -->
<context:property-placeholder location="classpath:db.properties" />
</beans>
12.在webapp目录下建文件夹:views,在views文件夹下建common、layout两个文件夹
13.分别在新创建的3个文件夹下创建3个vm文件,源码如下:
login.vm:
<div>
<div>用户登录</div><br/>
<form action="${rc.contextPath}/user/loginOK.html" method="post">
<div>用户名:<input type="text" name="username" /></div>
<div>密码:<input type="text" name="password" /></div>
<input type="submit" value="登录"/>
</form>
</div>
head.vm:
hello,springMVC!
<br/>
modal.vm:
<br/>
愚公移山
default.vm:
<!-- 全局页面-->
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<meta name="description" content="">
<meta name="author" content="">
<title>Hello Word</title>
<!-- 引入全局js -->
<link rel="stylesheet" href="${rc.contextPath}/resources/js/jquery/jquery-1.8.3.min.js" >
<!--声明全局变量-->
<script>
var webRoot = '${rc.contextPath}';
</script>
</head>
<body>
<div style="max-width:1200px;margin:0 auto;">
<!---网站头部引入开始--->
#parse("/common/head.vm")
<!---网站头部引入结束--->
<!-- 网站中间内容开始 -->
$screen_content
<!-- 网站中间内容结束 -->
<!-- Custom javascript for this template -->
<script src="${rc.contextPath}/resources/js/upcrm.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="${rc.contextPath}/resources/js/ie10-viewport-bug-workaround.js"></script>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="//cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="//cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- placeholder in IE -->
<!--[if IE]>
<script src="${rc.contextPath}/resources/js/jquery/jquery.placeholder.min.js"></script>
<script>
$(':input[placeholder]').placeholder();
</script>
<![endif]-->
<!-- 加载全局变量,方便自动补全判断浏览器兼容性-->
<script type="text/javascript">
$.browser = {};
$.browser.mozilla = /firefox/.test(navigator.userAgent.toLowerCase());
$.browser.webkit = /webkit/.test(navigator.userAgent.toLowerCase());
$.browser.opera = /opera/.test(navigator.userAgent.toLowerCase());
$.browser.msie = /msie/.test(navigator.userAgent.toLowerCase());
// JavaScript Document
if (!console) {
var console = {
debug : function() {
return false;
},
info : function() {
return false;
},
log : function() {
return false;
}
}
}
</script>
<!---网站底部引入开始--->
#parse("/common/modal.vm")
<!---网站底部引入结束--->
</div>
</body>
</html>
14.引入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.0</modelVersion>
<groupId>com.jiang</groupId>
<artifactId>maven</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>maven Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.0.RELEASE</version>
</dependency>
<!-- fastJson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.8</version>
</dependency>
<!-- velocity -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-tools</artifactId>
<version>2.0</version>
</dependency>
</dependencies>
<build>
<finalName>maven</finalName>
</build>
</project>
15.右击项目,在maven选项处点击update project…,然后点击项目,按alt+enter :进行如下两图的操作,即可引入maven依赖。
16.创建controller
package com.jiang.test;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping(value = "user")
public class UserController {
@RequestMapping("/login")
public String index(HttpServletRequest request,HttpServletResponse response)throws Exception{
return "login";
}
}
16.启动服务器,输入:http://localhost:8080/mvc/user/login
17.资源链接:
http://download.csdn.net/download/ilovecc2015/9880640
tips: 整个搭建步骤略显繁琐,但根据这篇文章做下来,是可以成功搭建SpringMVC+maven+velocity的框架的,如有问题,可直接与我联系。
联系方式,QQ:1792352361,微信:jiangzhiyao2015