SpringMVC+freemarker框架搭建
目录
2.3.添加springMVC和freemarker的配置文件...8
1.开发环境
l 操作系统:win7
l 开发工具:springtool suite 3.2.0.RELEASE
l 程序代码构建:maven
l Java JDK:1.6
l Maven版本:3.0.4
2.框架搭建
2.1.新建Maven Web项目
1、 菜单栏:New-other-mavenprojects
2、 填入goupid和artifact id点击finish即可
3、 这时候程序的架构如下:
4、 为了更好的管理代码和资源文件,修改项目的结构如下:
2.2.修改pom文件
引入基本的spring包、freemarker包、log包和一些其他的依赖包,并设置项目jdk为1.6,配置如下:
<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.0http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wq</groupId>
<artifactId>demo</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>demo Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>3.2.2.RELEASE</spring.version>
</properties>
<dependencies>
<!-- 基本web框架begin -->
<!-- junit测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
<scope>test</scope>
</dependency>
<!-- servlet -->
<dependency>
<groupId>servletapi</groupId>
<artifactId>servlet-api</artifactId>
<version>2.4</version>
</dependency>
<!-- spring框架 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<!-- freemarker -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.19</version>
</dependency>
<!-- log -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.5</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.6.6</version>
</dependency>
<!-- org.apache.commons -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
<!-- jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.1.4</version>
</dependency>
<!-- 基本web框架end -->
</dependencies>
<build>
<finalName>demo</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<compilerArgument>-Xlint:all</compilerArgument>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
右键项目maven-update下。
2.3.添加springMVC和freemarker的配置文件
添加位置如下,内容先空着不管:
2.4.修改web.xml文件
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<!-- 加载spring文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 编码设置为UTF-8 -->
<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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 初始化web容器 -->
<filter>
<filter-name>initWebContentFilter</filter-name>
<filter-class>com.wq.common.web.InitWebContentFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>initWebContentFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- freemarker配置 -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/applicationContext-freemarker.xml</param-value>
</init-param>
<init-param>
<param-name>NoCache</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>detectAllHandlerMappings</param-name>
<param-value>false</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- 欢迎页 -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 程序出错跳转地址 -->
<error-page>
<error-code>403</error-code>
<location>/error.do</location>
</error-page>
<error-page>
<error-code>401</error-code>
<location>/error.do</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/error.do</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/error.do</location>
</error-page>
</web-app>
2.5.springMVC配置
主要配置3个内容:
1、 设置Controller层上传参数和输出参数的数据转化器,例如date类型的参数,统一设置上传和输出格式为yyyy-MM-dd HH:mm:ss,double类型的参数精确到小数点后两位等,并设置ajax请求输出的格式为json数据格式。
2、 由于使用的是freemarker渲染,即每个页面都要经过一次后台服务器,然后指定渲染的文件路径,但是通常并不需要对每个页面写一个controller控制层的方法,这样工作量太大且不符合实际,我们希望的是输入http://aaa/bbb/ccc.htm就可以直接出现页面,而不是输入http://aaa/bbb/ccc.do,然后在controller层写一个方法,指定到ccc.htm的模板文件去,所以我们需要一个类似过滤器的中转器,将以htm或者html结尾的请求拦截下来,然后转化成freemarker可以解析的路径。
3、 全局的异常处理器。
4、配置文件applicationContext-springMVC.xml内容如下(具体引用的代码请下载附件= =,没积分了,大爷们施舍1分吧~):
<?xml version="1.0"encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
xsi:schemaLocation="http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://code.alibabatech.com/schema/dubbo
http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
<!-- 说明:springMVC配置 -->
<!-- 设置上传参数和输出参数的数据转化器 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter"/>
<!-- json转换器 -->
</list>
</property>
<property name="webBindingInitializer">
<bean class="com.wq.common.web.springmvc.BindingInitializer"/>
<!-- 参数渲染绑定 -->
</property>
</bean>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter"/>
<!-- json转换器 -->
</list>
</property>
<property name="webBindingInitializer">
<bean class="com.wq.common.web.springmvc.BindingInitializer"/>
<!-- 参数渲染绑定 -->
</property>
</bean>
<!-- 数据输出格式为json -->
<bean id="mappingJacksonHttpMessageConverter"class="com.wq.common.web.springmvc.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 所有请求都要经过该控制器,主要设置url地址是“.html”和“.htm”成freemarker可以渲染的路径 -->
<bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="defaultHandler"ref="wildcardMVCController"/>
</bean>
<bean id="wildcardMVCController" class="com.wq.common.web.springmvc.WildcardMVCController"/>
<!-- spring mvc全局异常处理 -->
<bean class="com.wq.common.web.GlobalExceptionHandler">
<property name="contentType" value="${system.contentType}" />
<property name="errorUrl" value="/error"/>
</bean>
</beans>
2.6.freemarker配置
主要配置3个内容:
1、 设置渲染模板页面的统一文件路径和文件名称(也就是前缀和后缀)。
2、 设置渲染视图的基类,通常每个页面都会需要公用的一些信息,比如登录人的信息、项目的名称等,这些信息我们统一渲染出来,而不需要在每个controller层去set这些信息。
3、 渲染结果的全局的配置,例如时间参数格式等。
4、 配置文件applicationContext-freemarker.xml内容如下(具体引用的代码请下载附件= =,没积分了,大爷们施舍1分吧~):
<?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:p="http://www.springframework.org/schema/p"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-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<!-- 说明:freemarker配置 -->
<!-- 采用注解方式扫描该包下所有含有org.springframework.stereotype.Controller注解的类 -->
<context:component-scan base-package="com.wq.ctrl" />
<!-- InternalResourceViewResolver默认的就是JstlView所以这里就不用配置viewClass了 -->
<bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<!-- 渲染页面前缀 -->
<property name="prefix" value="/freemarker/ftl"></property>
<!-- 渲染页面后缀 -->
<property name="suffix" value="/index.ftl"></property>
<property name="contentType" value="textml; charset=UTF-8"/>
<property name="exposeSessionAttributes"value="true" />
<property name="exposeSpringMacroHelpers"value="true" />
<!-- 渲染视图的基类,可以作为全局公用属性的输出和渲染 -->
<property name="viewClass"value="com.wq.common.web.springmvc.WebFreeMarkerView"/>
</bean>
<mvc:annotation-driven />
<!-- 渲染全局配置 -->
<bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath"value=""/>
<property name="freemarkerSettings">
<props>
<prop key="tag_syntax">auto_detect</prop>
<prop key="template_update_delay">0</prop>
<prop key="defaultEncoding">UTF-8</prop>
<prop key="url_escaping_charset">UTF-8</prop>
<prop key="locale">en_US</prop>
<prop key="boolean_format">true,false</prop>
<prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
<prop key="date_format">yyyy-MM-dd</prop>
<prop key="time_format">HH:mm:ss</prop>
<prop key="number_format">0.######</prop>
<prop key="whitespace_stripping">true</prop>
</props>
</property>
</bean>
</beans>
5、 添加渲染路径如下:
此时输入http://localhost:8080/demo/test.htm既可以渲染出index.ftl的内容。
Freemarker所认的路径为”/test”,前面配置了前缀和后缀,即实际的渲染路径为:
“/freemarker/ftl”+”/test” +”/index.flt”=”/freemarker/ftl/test/index.ftl”
2.7.项目文件说明
具体代码请下载附件(= =,没积分了,大爷们施舍1分吧~)
2.8.测试
1、测试请求地址以htm或者html结尾,是否可以渲染出页面:
2、测试controller层的方法
l 添加包路径如下(典型的ctrl、service、dao、po、dto五个包):
l Ctrl层代码:
packagecom.wq.ctrl;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.ResponseBody;
importorg.springframework.web.servlet.ModelAndView;
importcom.wq.common.web.Response;
importcom.wq.dto.TestDTO;
/**
* 测试控制层.
*
* @author qingwu
* @date 2014-3-21 上午9:42:55
*/
@Controller
@RequestMapping("test")
publicclass TestCtrl {
/**
* 页面跳转.
*
* @param req
* @param res
* @return
* @author qingwu
* @date 2014-1-26 上午11:25:54
*/
@RequestMapping("/page")
public ModelAndViewlogin(HttpServletRequest req, HttpServletResponse res) {
ModelAndView view = newModelAndView();
view.setViewName("/test");
return view;
}
/**
* ajax请求.
*
* @param ermpUserDTO
* 查询参数
* @return
* @author qingwu
* @date 2014-1-20 上午10:48:37
*/
@RequestMapping("/ajax")
@ResponseBody
public Response<TestDTO>queryUser(TestDTO params) {
Response<TestDTO> r =new Response<TestDTO>();
r.setData(params);
return r;
}
}
l 上传参数(依照本人的理解和经验,最好先确定项目的主要参数类型有哪些,比如时间、字符串、数字、浮点型,这四种参数就足够应付绝大多数的业务场景了,此时就要确定时间参数统一是Date或者Timestamp,整形类型为Long,浮点类型为Double,而非又date又Timestamp,又Long又Integer,又Double又Float的,这样需要在springmvc绑定相应类型的数据为同样的输出格式,徒增麻烦和调试的精力)
参数如下:
packagecom.wq.dto;
importjava.io.Serializable;
importjava.sql.Timestamp;
/**
* 测试DTO.
*
* @author qingwu
* @date 2014-3-21 上午9:53:59
*/
publicclass TestDTO implements Serializable {
/**
*
*/
private static final long serialVersionUID= -7835040757972828392L;
/**
* 字符串类型.
*/
private String str;
/**
* 时间类型.
*/
private Timestamp date;
/**
* 整形数字类型.
*/
private Long num;
/**
* 浮点型数字类型.
*/
private Double d;
/**
* @return the str
*/
public String getStr() {
return str;
}
/**
* @param str
* the str to set
*/
public void setStr(String str) {
this.str = str;
}
/**
* @return the date
*/
public Timestamp getDate() {
return date;
}
/**
* @param date
* the date to set
*/
public void setDate(Timestamp date) {
this.date = date;
}
/**
* @return the num
*/
public Long getNum() {
return num;
}
/**
* @param num
* the num to set
*/
public void setNum(Long num) {
this.num = num;
}
/**
* @return the d
*/
public Double getD() {
return d;
}
/**
* @param d
* the d to set
*/
public void setD(Double d) {
this.d = d;
}
}
l 结果:
页面跳转请求成功(http://localhost:8080/demo/test/page.do):
Ajax请求成功
(http://localhost:8080/demo/test/ajax.do?str=11111&date=2014-03-21%2023:59:59&num=123456789&d=2):
3.收尾
好了,这样简单的一个springMVC+freemarker的框架就搭建完成了,下一章节就是添加数据库层的东东了~
PS:代码大家如果感兴趣的话可以下载看看~
下载地址:http://download.csdn.net/detail/wq105032007067/7076359