Spring REST实践之Spring Web MVC
Spring概要
Spring Framework提供了依赖注入模型和面向切面编程,简化了基础型代码的编写工作以及更好的能够与其它框架和技术整合起来。Spring Framework由data access、instrumentation、messaging、testing、Web
integration等模块组成。开发者可以只关心自己应用程序相关模块。
依赖注入
依赖注入是Spring Framework的核心,能够降低模块之间的耦合度。为了能够更好的理解依赖注入的概念,举个例子解释一下:考虑网上购物的场景,完成一个订单服务需要与订单仓库组件和用户通知组件交互。在传统的实现方式中,订单服务可以创建订单仓库组件和用户通知组件对象,虽然这么做没有什么错,但是它会导致难于维护、难于测试和高耦合性。利用依赖注入,开发者可以委托Spring Framework管理模块间的依赖关系,所以在上面的场景中,Spring Framework可以创建订单仓库组件和用户通知组件,并注入到订单服务中。这样订单服务就不用创建管理订单仓库组件和用户通知组件,非常方便测试、维护,以及替换订单仓库组件和用户通知组件的实现方式。
AOP
AOP实现了横切逻辑,像日志、事务、监控、安全都属于横切逻辑。AOP提供了切面在一个集中的地方来完成这些横切逻辑,而不是将这些横切逻辑遍布业务代码各处。Spring Framework采用代理的方式实现AOP,当目标bean被调用时,代理会中断调用并执行横切逻辑,最后才执行目标bean的方法。Spring提供了JDK动态代理和CGLIB代理方式,如果目标对象实现了接口,Spring会使用JDK动态代理创建AOP代理,反之会使用CGLIB代理实现。
Spring Web MVC概要
Spring Web MVC是基于MVC的架构,提供了丰富的注解和组件。经过近几年的发展,Spring Web MVC支持了试图解析和丰富的数据绑定功能。
Model View Controller Pattern

Spring Web MVC Architecture

Spring Web MVC Components
Controller
控制器可用 @Controller注解声明。
Model
Model用于保持模型的属性,可用addAttribute和addAttributes方法增加模型的属性。
public interface Model {
Model addAttribute(String attributeName, Object attributeValue);
Model addAttribute(Object attributeValue);
Model addAllAttributes(Collection<?> attributeValues);
Model addAllAttributes(Map<String, ?> attributes);
Model mergeAttributes(Map<String, ?> attributes);
boolean containsAttribute(String attributeName);
Map<String, Object> asMap();
}
View
Spring Web MVC支持JSP、Velocity、Freemarker和XSLT等视图技术,通过View接口完成这个功能。
View Interface API:
public interface View
{
String getContentType();
void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception;
}
View Interface的核心功能是负责呈现响应内容,这个功能需要重载render方法实现,getContentType方法返回内容类型。Spring Web MVC内置了MappingJackson2JsonView、XsltView等实现View接口的类。
@RequestParam
@RequestParam用于绑定请求中的参数到控制器中的参数。
@RequestMapping
@RequestMapping将一个请求映射到控制器的一个方法。
@RequestMapping的参数:
Method:Restricts a mapping to a specific HTTP method such as GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE
Produces:Narrows mapping to media type that is produced by the method
Consumes:Narrows mapping to media type that the method consumes
Headers:Narrows mapping to the headers that should be present name Allows you to assign a name to the mapping
params:Restricts a mapping to the supplied parameter name and value
Path Variables
@PathVariable能够访问 @RequestMapping指定的路径中占位符参数。
View Resolver
View Resolver能够根据控制器返回的逻辑视图名,选择合适的视图解析器呈现视图。
public interface ViewResolver
{
View resolveViewName(String viewName, Locale locale) throws Exception;
}
ContentNegotiatingViewResolver、BeanNameViewResolver、InternalResourceViewResolver、TilesViewResolver等实现了ViewResolver接口。
Exception Handler
@Controller
public class HomeController {
@ExceptionHandler(SQLException.class)
public Object handleSQLException() {
}
@RequestMapping("/stream")
public void streamMovie(HttpServletResponse response) throws SQLException {
}
}
@ExceptionHandler注解表示在HomeController控制器中的方法抛出SQLException未处理的异常,都由handleSQLException来进行处理。但是此方式有个缺陷,就是只能处理HomeController及其子类的方法抛出的未处理异常。为解决这个问题,Spring提供了 @ControllerAdvice注解,在应用中凡是用 @RequestMapping注解标记的方法抛出未处理的异常都可以由 @ControllerAdvice注解标注的类中的相应异常处理方法进行处理。
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(SQLException.class)
public Object handleSQLException() {
}
}
Interceptors
Interceptors可以执行一些处理器关注的横切点业务。
HandlerInterceptor API
public interface HandlerInterceptor{
void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex);
void postHandle(HttpServletRequest request, HttpServletResponse response, Object
handler, ModelAndView modelAndView);
boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object
handler);
}
HandlerInterceptorAdapter实现HandlerInterceptor接口中的方法的默认实现,自定义的拦截器可以继承HandlerInterceptor类,覆盖自己关注的方法即可。
Spring Web MVC Interceptor例子:
public class SimpleInterceptor extends HandlerInterceptorAdapter {
private static final Logger logger = Logger.getLogger(SimpleInterceptor.class);
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
logger.info("Inside the prehandle");
return false;
}
}
拦截器注册例子:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.apress.springrest.web" })
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LocaleChangeInterceptor());
registry.addInterceptor(new SimpleInterceptor()).addPathPatterns("/auth/**");
}
}
Spring REST实践之Spring Web MVC的更多相关文章
- Spring REST实践之Spring Boot
Spring Boot基本描述 可以利用http://start.spring.io网站的进行Spring Boot的初始化构建.这个初始化构建器允许你输入工程基本信息.挑选工程支持的功能,最后会生成 ...
- Spring Boot 实践 :Spring Boot + MyBatis
Spring Boot 实践系列,Spring Boot + MyBatis . 目的 将 MyBatis 与 Spring Boot 应用程序一起使用来访问数据库. 本次使用的Library spr ...
- Features of Spring Web MVC
21.1.1 Features of Spring Web MVC Spring Web Flow Spring Web Flow (SWF) aims to be the best solution ...
- Spring与web MVC的整合——Spring的应用上下文管理
问题1 如何让web容器加载你的web MVC框架 对于基于servlet的web容器来说,遵循的是servlet规范,入口配置文件是web.xml.这类web容器会在启动的时候会而且仅会加载如下三种 ...
- spring web mvc中遇到的错误以及学习小记(持续记录)
错误:cvc-complex-type.2.4.a: 发现了以元素 'init-param' 开头的无效内容.应以 '{"http://java.sun.com/xml/ns/javaee& ...
- Spring Framework------>version4.3.5.RELAESE----->Reference Documentation学习心得----->Spring Framework中的spring web MVC模块
spring framework中的spring web MVC模块 1.概述 spring web mvc是spring框架中的一个模块 spring web mvc实现了web的MVC架构模式,可 ...
- Spring 4 官方文档学习(十一)Web MVC 框架之配置Spring MVC
内容列表: 启用MVC Java config 或 MVC XML namespace 修改已提供的配置 类型转换和格式化 校验 拦截器 内容协商 View Controllers View Reso ...
- Spring 4 官方文档学习(十一)Web MVC 框架之HTTP caching support
一个良好的HTTP缓存策略可以显著地增进web应用的性能和其客户端的体验.主要使用"Cache-Control" HTTP response header来完成,配合conditi ...
- 菜鸟学习Spring Web MVC之二
有文章从结构上详细讲解了Spring Web MVC,我个菜鸟就不引据来讲了.说说强悍的XP环境如何配置运行环境~~ 最后我配好的环境Tomcat.Spring Tool Suites.Maven目前 ...
随机推荐
- HDU5463 Clarke and minecraft
解题思路:此题刚开始,觉得好繁琐,好混乱,理清思路后,发现很简单. 具体见代码分析. #include<cstdio> #include<cstring> #include ...
- 【转】为eclipse安装python、shell开发环境和SVN插件
原文网址:http://www.crazyant.net/1185.html eclipse是一个非常好用的IDE,通常来说我们都用eclipse来开发JAVA程序,为了让开发python.shell ...
- C# winform 自定义控件
近来因为项目的问题,开始研究winform自定义控件,这篇主要是将自定义控件的属性在属性编辑器中可编辑,如果你对自定义控件比较了解的,就不用继续往下看了 首先,我创建了一个类UserButton,继承 ...
- php5.2转向 PHP 5.3 的 PHP 开发
PHP 5.3 开始,为了更好的向 PHP 的未来版本(PHP6) 过渡,将未来不再支持的函数标记为 DEPRECATED.在代码中使用这些函数,将毫不留情的在页面中显示警告信息:“使用了过时的函数… ...
- 嵌入式 Linux线程同步读写锁rwlock示例
读写锁比mutex有更高的适用性,可以多个线程同时占用读模式的读写锁,但是只能一个线程占用写模式的读写锁.1. 当读写锁是写加锁状态时,在这个锁被解锁之前,所有试图对这个锁加锁的线程都会被阻塞:2. ...
- Android应用开发学习—Toast使用方法大全
Toast 是一个 View 视图,快速的为用户显示少量的信息. Toast 在应用程序上浮动显示信息给用户,它永远不会获得焦点,不影响用户的输入等操作,主要用于 一些帮助 / 提示. Toast 最 ...
- -Xbootclasspath参数、java -jar参数运行应用时classpath的设置方法
当用java -jar yourJarExe.jar来运行一个经过打包的应用程序的时候,你会发现如何设置-classpath参数应用程序都找不到相应的第三方类,报ClassNotFound错误.实际上 ...
- java解析properties文件
在自动化测试过程中,经常会有一些公用的属性要配置,以便后面给脚本使用,我们可以选择xml, excel或者json格式来存贮这些数据,但其实java本身就提供了properties类来处理proper ...
- 安装配置Apache
1.更新和升级系统 sudo apt-get update sudo apt-get upgrade 2.安装和配置apache 2.1.安装apache sudo apt-get install a ...
- Oracle 学习用
最近在学习Oracle数据库 ,公司用这个,学习到现在,唉!苦逼的程序员呀! 也只能在这里发发牢骚了,这个是转载的 ,发完睡觉! oracle sql语句 一.ORACLE的启动和关闭 .在单机环境下 ...