Top 5 enhancements of Spring MVC 3.1
from http://blog.goyello.com/2011/12/16/enhancements-spring-mvc31/
After many months of development, Spring 3.1 has been finally released. The release is shipped with some exciting features like caching abstraction, bean profiles and container configuration simplifications. However, in this blog post I will describe my top 5 enhancements of Spring MVC 3.1.
1. Flash attributes support
Flash attributes are used to store attributes between requests and are used mostly in Post/Redirect/Get pattern. Prior to Spring 3.1 some additional (repeatable) steps were required to utilize flash attributes in Spring MVC based applications:
Create or copy FlashMap object to hold flash attributes
public class FlashMap implements Serializable {
// implementation omitted
}
Create or copy FlashMapFilter to your project
public class FlashMapFilter extends OncePerRequestFilter {
// implementation omitted
}
Include FlashMapFilter in web.xml
Put flash attributes in the controller when needed
@PreAuthorize("hasRole('ROLE_USER')")
@RequestMapping(value = Routing.SOME_ROUTING, method = RequestMethod.POST)
public String processForm(@Valid Form form, BindingResult result) {
// process the form
// ...
// add flash attribute
FlashMap.addAttribute("message", "Form processed");
// redirect
return RoutingHelper.redirect(Routing.SOME_OTHER_ROUTING);
}
With Spring 3.1 flash attributes support is enabled by default. No additional configuration is required. @Controller method accepts the argument of a type RedirectAttributes. RedirectAttributes is an interface that extends from standard Spring MVC Model interface and it may be used to store flash attributes that will be available after the redirection.
@PreAuthorize("hasRole('ROLE_USER')")
@RequestMapping(value = Routing.SOME_ROUTING, method = RequestMethod.POST)
public String processForm(@Valid Form form, BindingResult result, RedirectAttributes redirectAttributes) {
// process the form
// ...
// add flash attribute
redirectAttributes.addFlashAttribute("message", "Form processed");
// redirect
return RoutingHelper.redirect(Routing.SOME_OTHER_ROUTING);
}
2. @Validated annotation with support for JSR-303 validation groups
Spring MVC Bean Validation support has been extended with a new @Validated annotation that provides support of JSR 303 validation groups. A group defines a subset of constraints that is validated for a given object graph. Each constraint declaration may define the group or the list of groups it belongs to.
public class User {
@NotNull
private String name;
@NotNull(groups = { Simple.class })
private String address;
@NotNull(groups = { Simple.class, Extended.class })
private String licenceType;
@NotNull(groups = { Extended.class })
private String creditCard;
}
public interface Simple {
}
public interface Extended {
}
The example usage of the new @Validated annotation is shown in the following example:
@Controller
public class MyController {
@RequestMapping(value = "/user/default", method = RequestMethod.GET)
public String createDefaultUser(@Validated({ Default.class }) User user, BindingResult result) {
if(result.hasErrors()) {
// Validation on 'name'
}
return null;
}
@RequestMapping(value = "/user/simple", method = RequestMethod.GET)
public String createSimpleUser(@Validated({ Simple.class }) User user, BindingResult result) {
if(result.hasErrors()) {
// Validation on 'licenceType' and 'address'
}
return null;
}
@RequestMapping(value = "/user/extended", method = RequestMethod.GET)
public String createExtendedUser(@Validated({ Simple.class, Extended.class }) User user, BindingResult result) {
if(result.hasErrors()) {
// Validation on 'creditCard' and 'licenceType' and 'address'
}
return null;
}
}
The support for validation groups as added to Spring 3.1 is really handy. To read more about validation groups download and read the JSR 303 specification.
3. Support @Valid on @RequestBody method arguments
The @RequestMapping handler methods support @RequestBody annotated parameter for accessing the HTTP request body. The conversion is done through the available message converters, including FormHttpMessageConverter (application/x-www-form-urlencoded), MarshallingHttpMessageConverter (application/xml), MappingJacksonHttpMessageConverter (application/json) and others. But the @RequestBody annotated method argument could not be automatically validated. Manual validation was required:
@Controller
public class MyController {
@Autowired
private Validator validator;
@RequestMapping(value = "", method = RequestMethod.PUT)
@ResponseStatus(value = HttpStatus.CREATED)
@Secured("ROLE_ADMIN")
@Transactional
public void save(@RequestBody User user) {
validate(user);
dao.save(user);
}
private void validate(User user) {
// perfom validation using injected validator
}
}
In Spring 3.1 the @RequestBody method argument can be annotated with @Valid to invoke automatic validation. This makes the code can be simplified:
@Controller
public class MyController {
@RequestMapping(value = "/user", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.CREATED)
@Transactional
public void save(@Valid @RequestBody User user) {
dao.save(user);
}
@ExceptionHandler
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody
public String handleMethodArgumentNotValidException(
MethodArgumentNotValidException error) {
return "Bad request: " + error.getMessage();
}
}
In the above example, Spring automatically performs the validation and in case of error MethodArgumentNotValidException is thrown. Optional @ExceptionHandler method may be easily created to add custom behavior for handling this type of exception.
4. Supporting PUT request with form encoded data
The limitation of Servlet implementation is that it does not handle the encoded data of the HTTP PUT request properly. Introduction of the new HttpPutFormContentFilter solves that problem. With Spring 3.1 developing a RESTfull or RESTlike API became much simpler. See my previous post to read more about the usage of HttpPutFormContentFilter in a web application.
5. Java based configuration
The xml configuration of a Spring MVC application may be completely replaced by the Java based configuration. The simplest way to configure a web application is to use the @EnableWebMvc annotation:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.example" }, excludeFilters = @Filter(type = FilterType.ANNOTATION, value = Configuration.class))
@Import(PersistanceContextConfiguration.class)
public class ServletContextConfiguration extends WebMvcConfigurerAdapter {
@Bean
public TilesViewResolver configureTilesViewResolver() {
return new TilesViewResolver();
}
@Bean
public TilesConfigurer configureTilesConfigurer() {
TilesConfigurer configurer = new TilesConfigurer();
configurer.setDefinitions(new String[] { "/WEB-INF/tiles/tiles.xml",
"/WEB-INF/views/**/views.xml" });
return configurer;
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("login");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/").addResourceLocations(
"/recourses/**");
}
@Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
Extending from WebMvcConfigurerAdapter is not required, but it allows for the customization of the default Spring MVC configuration. The adapter enables us to register additional components like formatters, converters, custom validators, interceptors etc. This way the custom configuration can be done by Java code only. See my previous post about configuring a Spring MVC application with no xml in a Servlet 3.0 based environment.
Spring MVC 3.1 has a lot to offer
Spring MVC 3.1 brings many enhancements. The features mentioned in this blog post should have a positive impact on the application development with Spring MVC. They are not revolutionary, though. However, when I look at all the Spring features and enhancements shipped within the 3.1 release, I feel that the framework is going in the right direction. The caching abstraction, bean profiles, configuration simplifications and many other core features should allow to develop applications more efficiently.
References:
http://blog.springsource.org/2011/12/13/spring-framework-3-1-goes-ga/
http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/new-in-3.1.html
http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/
分享到:
相关推荐
这个“spring 3.1 mvc sample”提供了关于如何使用Spring MVC 3.1进行开发的实际示例。 首先,Spring MVC的核心概念包括DispatcherServlet、Controllers、Models、Views以及Handlers。DispatcherServlet作为入口点...
Spring 5 introduces many new features and enhancements from its previous version. We will discuss all this in the book. Spring 5 Design Patterns will give you in-depth insight about the Spring ...
5. **Caching Abstraction**:为了简化缓存管理,Spring 3.1提供了一个抽象层,支持多种缓存技术(如 Ehcache、Guava等),开发者可以方便地在应用中启用和配置缓存。 6. **AOP Enhancements**:在AOP(面向切面...
5. **Spring MVC**:4.1版本的Spring MVC引入了PathVariable注解的改进,支持了更为灵活的URL映射。同时,ModelAndView类也进行了优化,提高了与模板引擎的集成度。 6. **Integration with other technologies**:...
6. **MVC(Model-View-Controller)**:Spring MVC是Spring提供的Web应用程序开发模块,用于构建表现层。它提供了模型与视图解耦、控制器分离、请求参数绑定和验证等功能,支持多种视图技术如JSP、Thymeleaf等。 7....
Since then, we have certified further versions of Spring and WebLogic Server culminating in the combination of WebLogic Server 10.3 against Spring 2.5.3. Both these versions represent further ...
"SideBar Enhancements" 是一个针对Sublime Text编辑器的插件,主要目的是增强和扩展其默认侧边栏的功能。Sublime Text是一款流行的代码编辑器,因其轻量级、高效和高度可定制性而受到开发者喜爱。SideBar ...
The ASP.NET MVC Framework was the vision of Scott Guthrie in early 2007. With a prototype demonstration in late 2007 and a key hire of Phil Haack as the Senior Program Manager of the feature team, Mr....
SideBarEnhancements是一款针对Sublime Text 3的强大增强插件,它扩展了默认侧边栏的功能,提供了更多方便用户管理和操作文件及项目的选项。Sublime Text是一款广受欢迎的代码编辑器,以其轻量级、高性能和高度可...
5. Application Layer Enhancements 94 5.1. CIP Sync™ and CIP Motion™ 94 5.2. CIP Safety™ 99 6. Conformance Testing 121 7. Endnotes 123 8. Bibliography 126 9. Related Publications 126 10. ...
SideBarEnhancements是一款针对Sublime Text 3的强大增强插件,旨在扩展其侧边栏功能,提供更加便捷的文件和项目管理。Sublime Text 3是一款广受欢迎的文本编辑器,以其高性能、丰富的自定义性和多语言支持而受到...
SpringBatch是一个轻量级、全面的批处理框架,它是Spring框架的一部分,专注于提供企业级的批处理能力。SpringBatch的核心理念是提供一个可扩展的架构,支持处理大量数据时的性能和复杂性,无论数据来自何种数据源。...
个人汉化的sidebarenhancements目录,大部分的文字已翻译,替换相应的文件即可。
Sublime Text3文件右键增加插件 SideBarEnhancements汉化版 下载解压后放到插件packages目录重启Sublime Text3即可 文件右键出现添加文件 添加文件夹 复制 重命名 删除等操作 上传不了图片 如这链接所示...
SideBarEnhancements-st3 是专为Sublime Text3设计的一款强大插件,旨在增强原生侧边栏的功能,提供更为高效和便捷的文件管理体验。Sublime Text是一款广受欢迎的文本编辑器,以其轻量级、高度可定制化以及丰富的...
Sublime Text一个小插件——SideBarEnhancements 搜索“SideBarEnhancements”,还是第一个,直接回车确认。骚等一会儿就安装成功了。 如果无法在线安装,可以尝试通过下载安装包,放到Packages目录。...
SideBarEnhancements 是 sublime IDE 的一个侧边栏增强插件 , 安装方法详见:https://blog.csdn.net/PY0312/article/details/89529640
The Verilog 2001 Standard includes a number of enhancements that are targeted at simplifying designs improving designs and reducing design errors This paper details important enhancements that were ...
Sublime Text 2的插件SideBarEnhancements不好找,我找了好久的哦! 现在Sublime Text 2扩展安装包里没有SideBarEnhancements插件了,只好手动安装。 -------------------------- -------------------------- ...