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

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

一.涉及技术

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 技术具有卓越的通用性、高效性、平台移植性和安全性。

    3198 引用 • 8215 回帖 • 1 关注
  • Spring

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

    948 引用 • 1460 回帖 • 2 关注
  • FreeMarker

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

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

相关帖子

欢迎来到这里!

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

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

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

推荐标签 标签

  • WebComponents

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

    1 引用 • 10 关注
  • PWA

    PWA(Progressive Web App)是 Google 在 2015 年提出、2016 年 6 月开始推广的项目。它结合了一系列现代 Web 技术,在网页应用中实现和原生应用相近的用户体验。

    14 引用 • 69 回帖 • 178 关注
  • JSON

    JSON (JavaScript Object Notation)是一种轻量级的数据交换格式。易于人类阅读和编写。同时也易于机器解析和生成。

    52 引用 • 190 回帖
  • Kotlin

    Kotlin 是一种在 Java 虚拟机上运行的静态类型编程语言,由 JetBrains 设计开发并开源。Kotlin 可以编译成 Java 字节码,也可以编译成 JavaScript,方便在没有 JVM 的设备上运行。在 Google I/O 2017 中,Google 宣布 Kotlin 成为 Android 官方开发语言。

    19 引用 • 33 回帖 • 80 关注
  • 程序员

    程序员是从事程序开发、程序维护的专业人员。

    588 引用 • 3538 回帖
  • Python

    Python 是一种面向对象、直译式电脑编程语言,具有近二十年的发展历史,成熟且稳定。它包含了一组完善而且容易理解的标准库,能够轻松完成很多常见的任务。它的语法简捷和清晰,尽量使用无异义的英语单词,与其它大多数程序设计语言使用大括号不一样,它使用缩进来定义语句块。

    556 引用 • 675 回帖 • 1 关注
  • Firefox

    Mozilla Firefox 中文俗称“火狐”(正式缩写为 Fx 或 fx,非正式缩写为 FF),是一个开源的网页浏览器,使用 Gecko 排版引擎,支持多种操作系统,如 Windows、OSX 及 Linux 等。

    7 引用 • 30 回帖 • 388 关注
  • H2

    H2 是一个开源的嵌入式数据库引擎,采用 Java 语言编写,不受平台的限制,同时 H2 提供了一个十分方便的 web 控制台用于操作和管理数据库内容。H2 还提供兼容模式,可以兼容一些主流的数据库,因此采用 H2 作为开发期的数据库非常方便。

    11 引用 • 54 回帖 • 667 关注
  • FlowUs

    FlowUs.息流 个人及团队的新一代生产力工具。

    让复杂的信息管理更轻松、自由、充满创意。

    1 引用 • 1 关注
  • 正则表达式

    正则表达式(Regular Expression)使用单个字符串来描述、匹配一系列遵循某个句法规则的字符串。

    31 引用 • 94 回帖
  • 书籍

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

    78 引用 • 396 回帖
  • GraphQL

    GraphQL 是一个用于 API 的查询语言,是一个使用基于类型系统来执行查询的服务端运行时(类型系统由你的数据定义)。GraphQL 并没有和任何特定数据库或者存储引擎绑定,而是依靠你现有的代码和数据支撑。

    4 引用 • 3 回帖 • 7 关注
  • 面试

    面试造航母,上班拧螺丝。多面试,少加班。

    325 引用 • 1395 回帖 • 1 关注
  • 宕机

    宕机,多指一些网站、游戏、网络应用等服务器一种区别于正常运行的状态,也叫“Down 机”、“当机”或“死机”。宕机状态不仅仅是指服务器“挂掉了”、“死机了”状态,也包括服务器假死、停用、关闭等一些原因而导致出现的不能够正常运行的状态。

    13 引用 • 82 回帖 • 76 关注
  • HBase

    HBase 是一个分布式的、面向列的开源数据库,该技术来源于 Fay Chang 所撰写的 Google 论文 “Bigtable:一个结构化数据的分布式存储系统”。就像 Bigtable 利用了 Google 文件系统所提供的分布式数据存储一样,HBase 在 Hadoop 之上提供了类似于 Bigtable 的能力。

    17 引用 • 6 回帖 • 60 关注
  • 游戏

    沉迷游戏伤身,强撸灰飞烟灭。

    181 引用 • 821 回帖
  • TextBundle

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

    1 引用 • 2 回帖 • 83 关注
  • VirtualBox

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

    10 引用 • 2 回帖 • 18 关注
  • GitBook

    GitBook 使您的团队可以轻松编写和维护高质量的文档。 分享知识,提高团队的工作效率,让用户满意。

    3 引用 • 8 回帖
  • Sillot

    Insights(注意当前设置 master 为默认分支)

    汐洛彖夲肜矩阵(Sillot T☳Converbenk Matrix),致力于服务智慧新彖乄,具有彖乄驱动、极致优雅、开发者友好的特点。其中汐洛绞架(Sillot-Gibbet)基于自思源笔记(siyuan-note),前身是思源笔记汐洛版(更早是思源笔记汐洛分支),是智慧新录乄终端(多端融合,移动端优先)。

    主仓库地址:Hi-Windom/Sillot

    文档地址:sillot.db.sc.cn

    注意事项:

    1. ⚠️ 汐洛仍在早期开发阶段,尚不稳定
    2. ⚠️ 汐洛并非面向普通用户设计,使用前请了解风险
    3. ⚠️ 汐洛绞架基于思源笔记,开发者尽最大努力与思源笔记保持兼容,但无法实现 100% 兼容
    29 引用 • 25 回帖 • 114 关注
  • RESTful

    一种软件架构设计风格而不是标准,提供了一组设计原则和约束条件,主要用于客户端和服务器交互类的软件。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。

    30 引用 • 114 回帖 • 6 关注
  • SEO

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

    35 引用 • 200 回帖 • 32 关注
  • 运维

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

    151 引用 • 257 回帖 • 1 关注
  • jsDelivr

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

    5 引用 • 31 回帖 • 111 关注
  • Access
    1 引用 • 3 回帖 • 1 关注
  • Sphinx

    Sphinx 是一个基于 SQL 的全文检索引擎,可以结合 MySQL、PostgreSQL 做全文搜索,它可以提供比数据库本身更专业的搜索功能,使得应用程序更容易实现专业化的全文检索。

    1 引用 • 224 关注
  • API

    应用程序编程接口(Application Programming Interface)是一些预先定义的函数,目的是提供应用程序与开发人员基于某软件或硬件得以访问一组例程的能力,而又无需访问源码,或理解内部工作机制的细节。

    79 引用 • 431 回帖