Java Web通用架构(一) SpringMVC+Freemarker

本贴最后更新于 3402 天前,其中的信息可能已经东海扬尘

一.涉及技术

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>
    &lt;servlet&gt;
	&lt;servlet-name&gt;springmvc&lt;/servlet-name&gt;
	&lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;
	&lt;init-param&gt;
		&lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
		&lt;param-value&gt;classpath*:/applicationContext-mvc.xml&lt;/param-value&gt;
	&lt;/init-param&gt;
	&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
&lt;/servlet&gt;

&lt;servlet-mapping&gt;
	&lt;servlet-name&gt;springmvc&lt;/servlet-name&gt;
	&lt;url-pattern&gt;*.action&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;</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">
&lt;!-- 公用属性文件 --&gt;

<context:property-placeholder location="classpath*:/important.properties" ignore-resource-not-found="true" ignore-unresolvable="true" />

&lt;!-- 指定注解扫描的包 --&gt;

<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>

&lt;bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver"&gt;
    &lt;property name="contentType" value="text/html; charset=UTF-8" /&gt;
    &lt;property name="suffix" value="${template.suffix}" /&gt;
&lt;/bean&gt;

&lt;bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"&gt;
    &lt;property name="defaultEncoding" value="UTF-8" /&gt;
    &lt;property name="maxUploadSize"&gt;
        &lt;value&gt;10485760&lt;/value&gt;  &lt;!-- 文件大小限为10M --&gt;
    &lt;/property&gt;
&lt;/bean&gt;

&lt;bean id="exceptionResolver" class="org.sigon.demo.web.exception.ExceptionHandler"&gt;
    &lt;property name="defaultErrorView" value="/msg/error"/&gt;
    &lt;property name="defaultStatusCode" value="500"/&gt;
    &lt;property name="statusCodes"&gt;&lt;!-- 配置多个statusCode --&gt;
        &lt;props&gt;
            &lt;prop key="/msg/maxUploadSize"&gt;500&lt;/prop&gt;  &lt;!-- error.jsp --&gt;
            &lt;prop key="/msg/error"&gt;404&lt;/prop&gt;    &lt;!-- error1.jsp --&gt;
        &lt;/props&gt;
    &lt;/property&gt;
    &lt;property name="exceptionMappings"&gt;
        &lt;props&gt;
            &lt;prop key="org.springframework.web.multipart.MaxUploadSizeExceededException"&gt;msg/maxUploadSize&lt;/prop&gt;
            &lt;prop key="java.lang.exception"&gt;msg/error&lt;/prop&gt;
        &lt;/props&gt;
    &lt;/property&gt;
&lt;/bean&gt;

&lt;mvc:annotation-driven&gt;
    &lt;mvc:message-converters&gt;
        &lt;bean class="org.springframework.http.converter.StringHttpMessageConverter"&gt;
            &lt;property name="supportedMediaTypes"&gt;
                &lt;list&gt;
                    &lt;value&gt;text/plain;charset=UTF-8&lt;/value&gt;
                    &lt;value&gt;text/html;charset=UTF-8&lt;/value&gt;
                &lt;/list&gt;
            &lt;/property&gt;
        &lt;/bean&gt;
    &lt;/mvc:message-converters&gt;
&lt;/mvc:annotation-driven&gt;

<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的用法可以去百度

总结:这套整合配置是非常简单的,使用注解的方式省了写属性访问器.也更方便阅读.

  • Java

    Java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由 Sun Microsystems 公司于 1995 年 5 月推出的。Java 技术具有卓越的通用性、高效性、平台移植性和安全性。

    3192 引用 • 8214 回帖 • 2 关注
  • Spring

    Spring 是一个开源框架,是于 2003 年兴起的一个轻量级的 Java 开发框架,由 Rod Johnson 在其著作《Expert One-On-One J2EE Development and Design》中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。框架的主要优势之一就是其分层架构,分层架构允许使用者选择使用哪一个组件,同时为 JavaEE 应用程序开发提供集成的框架。

    943 引用 • 1460 回帖
  • FreeMarker

    FreeMarker 是一款好用且功能强大的 Java 模版引擎。

    23 引用 • 20 回帖 • 457 关注
  • SpringMVC
    4 引用 • 2 回帖

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...
  • zonghua

    有什么好的 freemarker 插件推荐吗,不然 jbosstools 附带那个功能好简陋

推荐标签 标签

  • VirtualBox

    VirtualBox 是一款开源虚拟机软件,最早由德国 Innotek 公司开发,由 Sun Microsystems 公司出品的软件,使用 Qt 编写,在 Sun 被 Oracle 收购后正式更名成 Oracle VM VirtualBox。

    10 引用 • 2 回帖 • 13 关注
  • OnlyOffice
    4 引用 • 14 关注
  • WebComponents

    Web Components 是 W3C 定义的标准,它给了前端开发者扩展浏览器标签的能力,可以方便地定制可复用组件,更好的进行模块化开发,解放了前端开发者的生产力。

    1 引用 • 8 关注
  • 旅游

    希望你我能在旅途中找到人生的下一站。

    93 引用 • 901 回帖
  • 链书

    链书(Chainbook)是 B3log 开源社区提供的区块链纸质书交易平台,通过 B3T 实现共享激励与价值链。可将你的闲置书籍上架到链书,我们共同构建这个全新的交易平台,让闲置书籍继续发挥它的价值。

    链书社

    链书目前已经下线,也许以后还有计划重制上线。

    14 引用 • 257 回帖
  • sts
    2 引用 • 2 回帖 • 203 关注
  • HTML

    HTML5 是 HTML 下一个的主要修订版本,现在仍处于发展阶段。广义论及 HTML5 时,实际指的是包括 HTML、CSS 和 JavaScript 在内的一套技术组合。

    107 引用 • 295 回帖 • 1 关注
  • 快应用

    快应用 是基于手机硬件平台的新型应用形态;标准是由主流手机厂商组成的快应用联盟联合制定;快应用标准的诞生将在研发接口、能力接入、开发者服务等层面建设标准平台;以平台化的生态模式对个人开发者和企业开发者全品类开放。

    15 引用 • 127 回帖 • 1 关注
  • 京东

    京东是中国最大的自营式电商企业,2015 年第一季度在中国自营式 B2C 电商市场的占有率为 56.3%。2014 年 5 月,京东在美国纳斯达克证券交易所正式挂牌上市(股票代码:JD),是中国第一个成功赴美上市的大型综合型电商平台,与腾讯、百度等中国互联网巨头共同跻身全球前十大互联网公司排行榜。

    14 引用 • 102 回帖 • 330 关注
  • SEO

    发布对别人有帮助的原创内容是最好的 SEO 方式。

    35 引用 • 200 回帖 • 23 关注
  • TGIF

    Thank God It's Friday! 感谢老天,总算到星期五啦!

    289 引用 • 4492 回帖 • 657 关注
  • Outlook
    1 引用 • 5 回帖
  • 运维

    互联网运维工作,以服务为中心,以稳定、安全、高效为三个基本点,确保公司的互联网业务能够 7×24 小时为用户提供高质量的服务。

    150 引用 • 257 回帖 • 1 关注
  • PostgreSQL

    PostgreSQL 是一款功能强大的企业级数据库系统,在 BSD 开源许可证下发布。

    22 引用 • 22 回帖 • 2 关注
  • WebSocket

    WebSocket 是 HTML5 中定义的一种新协议,它实现了浏览器与服务器之间的全双工通信(full-duplex)。

    48 引用 • 206 回帖 • 303 关注
  • 尊园地产

    昆明尊园房地产经纪有限公司,即:Kunming Zunyuan Property Agency Company Limited(简称“尊园地产”)于 2007 年 6 月开始筹备,2007 年 8 月 18 日正式成立,注册资本 200 万元,公司性质为股份经纪有限公司,主营业务为:代租、代售、代办产权过户、办理银行按揭、担保、抵押、评估等。

    1 引用 • 22 回帖 • 780 关注
  • V2Ray
    1 引用 • 15 回帖 • 4 关注
  • Postman

    Postman 是一款简单好用的 HTTP API 调试工具。

    4 引用 • 3 回帖
  • FFmpeg

    FFmpeg 是一套可以用来记录、转换数字音频、视频,并能将其转化为流的开源计算机程序。

    23 引用 • 32 回帖 • 1 关注
  • SSL

    SSL(Secure Sockets Layer 安全套接层),及其继任者传输层安全(Transport Layer Security,TLS)是为网络通信提供安全及数据完整性的一种安全协议。TLS 与 SSL 在传输层对网络连接进行加密。

    70 引用 • 193 回帖 • 414 关注
  • Gzip

    gzip (GNU zip)是 GNU 自由软件的文件压缩程序。我们在 Linux 中经常会用到后缀为 .gz 的文件,它们就是 Gzip 格式的。现今已经成为互联网上使用非常普遍的一种数据压缩格式,或者说一种文件格式。

    9 引用 • 12 回帖 • 165 关注
  • TextBundle

    TextBundle 文件格式旨在应用程序之间交换 Markdown 或 Fountain 之类的纯文本文件时,提供更无缝的用户体验。

    1 引用 • 2 回帖 • 66 关注
  • 友情链接

    确认过眼神后的灵魂连接,站在链在!

    24 引用 • 373 回帖
  • 知乎

    知乎是网络问答社区,连接各行各业的用户。用户分享着彼此的知识、经验和见解,为中文互联网源源不断地提供多种多样的信息。

    10 引用 • 66 回帖
  • CloudFoundry

    Cloud Foundry 是 VMware 推出的业界第一个开源 PaaS 云平台,它支持多种框架、语言、运行时环境、云平台及应用服务,使开发人员能够在几秒钟内进行应用程序的部署和扩展,无需担心任何基础架构的问题。

    5 引用 • 18 回帖 • 184 关注
  • SMTP

    SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。SMTP 协议属于 TCP/IP 协议簇,它帮助每台计算机在发送或中转信件时找到下一个目的地。

    4 引用 • 18 回帖 • 625 关注
  • CSS

    CSS(Cascading Style Sheet)“层叠样式表”是用于控制网页样式并允许将样式信息与网页内容分离的一种标记性语言。

    197 引用 • 541 回帖 • 2 关注