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

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

一.涉及技术

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 回帖
  • Spring

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

    943 引用 • 1460 回帖 • 1 关注
  • FreeMarker

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

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

相关帖子

欢迎来到这里!

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

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

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

推荐标签 标签

  • 书籍

    宋真宗赵恒曾经说过:“书中自有黄金屋,书中自有颜如玉。”

    78 引用 • 391 回帖 • 2 关注
  • 星云链

    星云链是一个开源公链,业内简单的将其称为区块链上的谷歌。其实它不仅仅是区块链搜索引擎,一个公链的所有功能,它基本都有,比如你可以用它来开发部署你的去中心化的 APP,你可以在上面编写智能合约,发送交易等等。3 分钟快速接入星云链 (NAS) 测试网

    3 引用 • 16 回帖 • 3 关注
  • React

    React 是 Facebook 开源的一个用于构建 UI 的 JavaScript 库。

    192 引用 • 291 回帖 • 375 关注
  • Bootstrap

    Bootstrap 是 Twitter 推出的一个用于前端开发的开源工具包。它由 Twitter 的设计师 Mark Otto 和 Jacob Thornton 合作开发,是一个 CSS / HTML 框架。

    18 引用 • 33 回帖 • 658 关注
  • Spring

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

    943 引用 • 1460 回帖 • 2 关注
  • Wide

    Wide 是一款基于 Web 的 Go 语言 IDE。通过浏览器就可以进行 Go 开发,并有代码自动完成、查看表达式、编译反馈、Lint、实时结果输出等功能。

    欢迎访问我们运维的实例: https://wide.b3log.org

    30 引用 • 218 回帖 • 642 关注
  • Logseq

    Logseq 是一个隐私优先、开源的知识库工具。

    Logseq is a joyful, open-source outliner that works on top of local plain-text Markdown and Org-mode files. Use it to write, organize and share your thoughts, keep your to-do list, and build your own digital garden.

    6 引用 • 63 回帖 • 5 关注
  • jQuery

    jQuery 是一套跨浏览器的 JavaScript 库,强化 HTML 与 JavaScript 之间的操作。由 John Resig 在 2006 年 1 月的 BarCamp NYC 上释出第一个版本。全球约有 28% 的网站使用 jQuery,是非常受欢迎的 JavaScript 库。

    63 引用 • 134 回帖 • 731 关注
  • Spark

    Spark 是 UC Berkeley AMP lab 所开源的类 Hadoop MapReduce 的通用并行框架。Spark 拥有 Hadoop MapReduce 所具有的优点;但不同于 MapReduce 的是 Job 中间输出结果可以保存在内存中,从而不再需要读写 HDFS,因此 Spark 能更好地适用于数据挖掘与机器学习等需要迭代的 MapReduce 的算法。

    74 引用 • 46 回帖 • 568 关注
  • Vim

    Vim 是类 UNIX 系统文本编辑器 Vi 的加强版本,加入了更多特性来帮助编辑源代码。Vim 的部分增强功能包括文件比较(vimdiff)、语法高亮、全面的帮助系统、本地脚本(Vimscript)和便于选择的可视化模式。

    29 引用 • 66 回帖 • 1 关注
  • 博客

    记录并分享人生的经历。

    273 引用 • 2388 回帖
  • 禅道

    禅道是一款国产的开源项目管理软件,她的核心管理思想基于敏捷方法 scrum,内置了产品管理和项目管理,同时又根据国内研发现状补充了测试管理、计划管理、发布管理、文档管理、事务管理等功能,在一个软件中就可以将软件研发中的需求、任务、bug、用例、计划、发布等要素有序的跟踪管理起来,完整地覆盖了项目管理的核心流程。

    6 引用 • 15 回帖 • 75 关注
  • Anytype
    3 引用 • 31 回帖 • 11 关注
  • Git

    Git 是 Linux Torvalds 为了帮助管理 Linux 内核开发而开发的一个开放源码的版本控制软件。

    211 引用 • 358 回帖 • 1 关注
  • Maven

    Maven 是基于项目对象模型(POM)、通过一小段描述信息来管理项目的构建、报告和文档的软件项目管理工具。

    186 引用 • 318 回帖 • 267 关注
  • Outlook
    1 引用 • 5 回帖 • 2 关注
  • jsDelivr

    jsDelivr 是一个开源的 CDN 服务,可为 npm 包、GitHub 仓库提供免费、快速并且可靠的全球 CDN 加速服务。

    5 引用 • 31 回帖 • 86 关注
  • 音乐

    你听到信仰的声音了么?

    61 引用 • 512 回帖
  • 前端

    前端技术一般分为前端设计和前端开发,前端设计可以理解为网站的视觉设计,前端开发则是网站的前台代码实现,包括 HTML、CSS 以及 JavaScript 等。

    247 引用 • 1348 回帖
  • Laravel

    Laravel 是一套简洁、优雅的 PHP Web 开发框架。它采用 MVC 设计,是一款崇尚开发效率的全栈框架。

    20 引用 • 23 回帖 • 733 关注
  • ActiveMQ

    ActiveMQ 是 Apache 旗下的一款开源消息总线系统,它完整实现了 JMS 规范,是一个企业级的消息中间件。

    19 引用 • 13 回帖 • 677 关注
  • SQLServer

    SQL Server 是由 [微软] 开发和推广的关系数据库管理系统(DBMS),它最初是由 微软、Sybase 和 Ashton-Tate 三家公司共同开发的,并于 1988 年推出了第一个 OS/2 版本。

    21 引用 • 31 回帖
  • Oracle

    Oracle(甲骨文)公司,全称甲骨文股份有限公司(甲骨文软件系统有限公司),是全球最大的企业级软件公司,总部位于美国加利福尼亚州的红木滩。1989 年正式进入中国市场。2013 年,甲骨文已超越 IBM,成为继 Microsoft 后全球第二大软件公司。

    107 引用 • 127 回帖 • 367 关注
  • Linux

    Linux 是一套免费使用和自由传播的类 Unix 操作系统,是一个基于 POSIX 和 Unix 的多用户、多任务、支持多线程和多 CPU 的操作系统。它能运行主要的 Unix 工具软件、应用程序和网络协议,并支持 32 位和 64 位硬件。Linux 继承了 Unix 以网络为核心的设计思想,是一个性能稳定的多用户网络操作系统。

    949 引用 • 943 回帖
  • OpenResty

    OpenResty 是一个基于 NGINX 与 Lua 的高性能 Web 平台,其内部集成了大量精良的 Lua 库、第三方模块以及大多数的依赖项。用于方便地搭建能够处理超高并发、扩展性极高的动态 Web 应用、Web 服务和动态网关。

    17 引用 • 39 关注
  • 深度学习

    深度学习(Deep Learning)是机器学习的分支,是一种试图使用包含复杂结构或由多重非线性变换构成的多个处理层对数据进行高层抽象的算法。

    54 引用 • 40 回帖
  • Ngui

    Ngui 是一个 GUI 的排版显示引擎和跨平台的 GUI 应用程序开发框架,基于
    Node.js / OpenGL。目标是在此基础上开发 GUI 应用程序可拥有开发 WEB 应用般简单与速度同时兼顾 Native 应用程序的性能与体验。

    7 引用 • 9 回帖 • 408 关注