一.涉及技术
Spring是Java阵营最重要的框架,没有之一.主要作用是解决企业应用架构的复杂性,实现优雅的分层架构和配置基本的JavaBean完成复杂的业务逻辑.
Spring MVC是Spring的MVC解决方案,相比其它MVC框架,与Spring的风格最为接近,可以无缝整合
Freemarker是轻量级的模板框架,能避免传统JSP的初始化较慢和代码嵌入的问题,也提供了类似于jstl的强大脚本
二.Spring基本配置
首先需要在web.xml配置如下
<context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath*:/applicationContext*.xml </param-value> </context-param><servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:/applicationContext-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping></pre>
在工程的resources目录下applicationContext-mvc.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:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd" default-lazy-init="true" default-autowire="byName"><!-- 公用属性文件 -->
<context:property-placeholder location="classpath*:/important.properties" ignore-resource-not-found="true" ignore-unresolvable="true" />
<!-- 指定注解扫描的包 -->
<context:component-scan base-package="org.sigon" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan><!-- MVC 拦截器 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<mvc:exclude-mapping path="/login/login.action" />
<bean id="logInterceptor" class="com.aunewtop.merchant.web.interceptor.LogInterceptor" />
</mvc:interceptor>
</mvc:interceptors><bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver"> <property name="contentType" value="text/html; charset=UTF-8" /> <property name="suffix" value="${template.suffix}" /> </bean> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8" /> <property name="maxUploadSize"> <value>10485760</value> <!-- 文件大小限为10M --> </property> </bean> <bean id="exceptionResolver" class="org.sigon.demo.web.exception.ExceptionHandler"> <property name="defaultErrorView" value="/msg/error"/> <property name="defaultStatusCode" value="500"/> <property name="statusCodes"><!-- 配置多个statusCode --> <props> <prop key="/msg/maxUploadSize">500</prop> <!-- error.jsp --> <prop key="/msg/error">404</prop> <!-- error1.jsp --> </props> </property> <property name="exceptionMappings"> <props> <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">msg/maxUploadSize</prop> <prop key="java.lang.exception">msg/error</prop> </props> </property> </bean> <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/plain;charset=UTF-8</value> <value>text/html;charset=UTF-8</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven>
<bean id="freeMarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPaths" value="${template.loader_path}" />
<property name="freemarkerSettings">
<props>
<prop key="defaultEncoding">${template.encoding}</prop>
<prop key="tag_syntax">auto_detect</prop>
<prop key="whitespace_stripping">true</prop>
<prop key="classic_compatible">true</prop>
<prop key="template_update_delay">${template.update_delay}</prop>
<prop key="object_wrapper">freemarker.ext.beans.BeansWrapper</prop>
<prop key="datetime_format">${template.datetime_format}</prop>
<prop key="date_format">${template.date_format}</prop>
<prop key="time_format">${template.time_format}</prop>
<prop key="number_format">${template.number_format}</prop>
<prop key="boolean_format">${template.boolean_format}</prop>
<prop key="auto_import">include/spring.ftl as spring</prop>
</props>
</property>
<property name="freemarkerVariables">
<map>
<entry key="systemName" value="${system.project_name}" />
<entry key="systemVersion" value="${system.version}" />
<entry key="systemDescription" value="${system.description}" />
<entry key="locale" value="${locale}" />
<!--<entry key="base" value="${serverside.domain.url}" />-->
<entry key="base" value="" />
</map>
</property>
</bean>
</beans>
三.Java 控制器
package org.sigon.demo.web.action;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
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.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;/**
-
注解:控制器名,映射路径,原型实例
-
User: Sguang
-
Date: 15-10-26
-
Time: 下午 11:17
-
To change this template use File | Settings | File Templates.
*/
@Controller("testController")
@RequestMapping("/test")
@Scope(value = "prototype")
public class TestController extends BaseController {@Resource(name = "testServiceImpl")
private TestService testService;/**
- @param id 路径参数
- @param model 给 Freemarker 模板封装的 Map
- @param request 需要使用 request 的话,只需要在参数中加上就可以
- @return 返回值是 Freemarker 模板的相对路径
**/
@RequestMapping(value = "/method/{id}", method = RequestMethod.GET)
public String list(@PathVariable Long id, ModelMap model, HttpServletRequest request) {
model.addAttribute("str", "SPRING MVC");
model.addAttribute("id", id);
model.addAttribute("testValue", testService.getTestValue());
return "/test/method";
}
/**
- 使用 ResponseBody 注解,会直接返回值,适合 ajax 时返回 json 数据使用
**/
@ResponseBody
@RequestMapping(value = "/userAgent", method = RequestMethod.GET)
public String userAgent(){
return request.getHeader("User-Agent");
}
}
SpringMVC的Controller设计非常优雅灵活,能随心所欲的配置参数和返回值
四.Freemarker例子
对应的Freemarker模板就很简单了
${str} ${id} ${testValue} [#list [1,2,3] as item] ${item} [/#list]
示例里演示了从Controller传下来的model属性的调用方法
还有List的迭代器,更多Freemarker的用法可以去百度
总结:这套整合配置是非常简单的,使用注解的方式省了写属性访问器.也更方便阅读.
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于