您的位置:首页 > 编程语言 > Java开发

SpringMVC 4 配置返回JSP,和Freemarker视图

2014-07-24 09:24 627 查看
1.新建Dynamic Web Project。

2.导入Spring及Springmvc 4.0.6 相关库文件

如截图



3.配置web.xml

<?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_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Freemarker_SpringMVC_example</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
说明:配置了一个叫spring的Servlet,然后映射到DispatcherServlet,Spring会自动在WEB-INF目录下查找一个叫spring-servlet.xml的文件,用于配置Springmvc.通过web请求时,spring会把所有的请求拦截,这里配置成允许*.html后缀的请求路径。

4.配置springmvc-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: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-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!--注解说明 -->
<context:annotation-config />

<!-- 注解支持 -->
<mvc:annotation-driven/>
<!-- 使Spring支持自动检测组件,如注解的Controller -->
<context:component-scan base-package="org.web.controller" >
<!-- 允许定义过滤器将基包下的某些类纳入或排除  -->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

<bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape"/>

<!--通用视图解析器-->
<bean id="viewResolverCommon" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/content/"/>
<property name="suffix" value=".jsp"/><!--可为空,方便实现自已的依据扩展名来选择视图解释类的逻辑  -->
<property name="viewClass">
<value>org.springframework.web.servlet.view.InternalResourceView</value>
</property>
<property name="order" value="1"/>
</bean>

<!-- 配置freeMarker视图解析器 -->
<bean id="viewResolverFtl" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.freemarker.FreeMarkerView"/>
<property name="contentType" value="text/html; charset=utf-8"/>
<property name="cache" value="true" />
<property name="suffix" value=".ftl" />
<property name="order" value="0"/>
</bean>
<!-- ftl参数配置 -->
<bean id="freemarkerConfiguration"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="/WEB-INF/freemarker.properties" />
</bean>
<!-- 配置freeMarker的模板路径 -->
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath">
<value>/WEB-INF/ftl/</value>
</property>
<property name="freemarkerVariables">
<map>
<entry key="xml_escape" value-ref="fmXmlEscape" />
</map>
</property>
<property name="defaultEncoding">
<value>utf-8</value>
</property>
<property name="freemarkerSettings">
<props>
<prop key="template_update_delay">3600</prop>
</props>
</property>
</bean>

</beans>


说明:springmvc允许多视图配置view。通过order来指定查找优先级。这里配置先扫描/WEB-INF/ftl下的Freemarker模板文件,如果没有找到再匹配/WEB-INF/view/下的jsp文件。

这里可参考一篇文章:/article/3930836.html

freemarker.properties文件用于配置Freemarker属性

datetime_format=yyyy-MM-dd HH:mm:ss
date_format=yyyy-MM-dd
time_format=HH:mm:ss
number_format=0.######;
boolean_format=true,false
#auto_import="/WEB-INF/ftl/common/app.ftl" as app
whitespace_stripping=true
default_encoding=UTF-8
tag_syntax=square_bracket
url_escaping_charset=UTF-8
#enable the fault. replaced with "" when 'null'
classic_compatible=true
5.在/WEB-INF/下新建ftl和content文件夹,并添加相应的users.ftl文件盒users.jsp文件



编辑users.ftl如下

<html>
<head><title>ViralPatel.net - FreeMarker Spring MVC Hello World</title>
<body>
<div id="header">
<H2>
<#--
<a href="http://viralpatel.net"><img height="37" width="236" border="0px" src="" align="center"/></a>
-->
FreeMarker Spring MVC Hello World
</H2>
</div>

<div id="content">

<fieldset>
<legend>Add User</legend>
<form name="user" action="add.html" method="post">
Firstname: <input type="text" name="firstname" />	<br/>
Lastname: <input type="text" name="lastname" />	<br/>
<input type="submit" value="   Save   " />
</form>
</fieldset>
<br/>
<table class="datatable">
<tr>
<th>Firstname</th>  <th>Lastname</th>
</tr>
<#list model["userList"] as user>
<tr>
<td>${user.firstname}</td> <td>${user.lastname}</td>
</tr>
</#list>
</table>

</div>
</body>
</html>


编辑users.jsp如下

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head><title>ViralPatel.net - FreeMarker Spring MVC Hello World</title>
<body>
<div id="header">
<H2>
FreeMarker Spring MVC Hello World
</H2>
</div>

<div id="content">

<fieldset>
<legend>Add User</legend>
<form name="user" action="add.html" method="post">
Firstname: <input type="text" name="firstname" />	<br/>
Lastname: <input type="text" name="lastname" />	<br/>
<input type="submit" value="   Save   " />
</form>
</fieldset>
<br/>
<table class="datatable">
<tr>
<th>Firstname</th>  <th>Lastname</th>
</tr>
<c:forEach items="${userList}" var="user">
<tr>
<td>${user.firstname}</td> <td>${user.lastname}</td>
</tr>
</c:forEach>

</table>
model["userList"]
</div>
</body>
</html>
6.编写Controller控制类

在org.web.controller下新建UserController.java

package org.web.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class UserController {

/**
* Static list of users to simulate Database
*/
private static List<User> userList = new ArrayList<User>();

// Initialize the list with some data for index screen
static {
userList.add(new User("Bill", "Gates"));
userList.add(new User("Steve", "Jobs"));
userList.add(new User("Larry", "Page"));
userList.add(new User("Sergey", "Brin"));
userList.add(new User("Larry", "Ellison"));
}

/**
* Saves the static list of users in model and renders it via freemarker
* template.
*
* @param model
* @return The index view (FTL)
*/
@RequestMapping(value = "/users", method = RequestMethod.GET)
public String index(@ModelAttribute("model") ModelMap model) {

model.addAttribute("userList", userList);

return "users";
}

/**
* Add a new user into static user lists and display the same into FTL via
* redirect
*
* @param user
* @return Redirect to /index page to display user list
*/
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String add(@ModelAttribute("user") User user) {

if (null != user && null != user.getFirstname()
&& null != user.getLastname() && !user.getFirstname().isEmpty()
&& !user.getLastname().isEmpty()) {

synchronized (userList) {
userList.add(user);
}

}

return "redirect:users.html";
}

}


7.部署到tomcat,访问localhost:8080/springmvcftl/index.html即可
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: