一、springMVC+freemarker框架搭建
SpringMVC+freemarker框架搭建
目錄
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>
主要配置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>
主要配置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、 新增渲染路徑如下:
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