使用Spring MVC 的表单控制器SimpleFormController
@ControllerAdvice,是spring3.2提供的新注解,从名字上可以看出大体意思是控制器增强。让我们先看看@ControllerAdvice的实现:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface ControllerAdvice { }
使用 @ControllerAdvice,不用任何的配置,只要把这个类放在项目中,Spring能扫描到的地方。就可以实现全局异常的回调。
没什么特别之处,该注解使用@Component注解,这样的话当我们使用<context:component-scan>扫描时也能扫描到。
其javadoc定义是:
/**
* Indicates the annotated class assists a "Controller".
*
* <p>Serves as a specialization of {@link Component @Component}, allowing for
* implementation classes to be autodetected through classpath scanning.
*
* <p>It is typically used to define {@link ExceptionHandler @ExceptionHandler},
* {@link InitBinder @InitBinder}, and {@link ModelAttribute @ModelAttribute}
* methods that apply to all {@link RequestMapping @RequestMapping} methods.
*
* @author Rossen Stoyanchev
* @since 3.2
*/
@ControllerAdvice是一个@Component,用于定义@ExceptionHandler,@InitBinder和@ModelAttribute方法,适用于所有使用@RequestMapping方法。
Spring4之前,@ControllerAdvice在同一调度的Servlet中协助所有控制器。Spring4已经改变:@ControllerAdvice支持配置控制器的子集,而默认的行为仍然可以利用。
在Spring4中, @ControllerAdvice通过annotations(), basePackageClasses(), basePackages() 方法定制用于选择控制器子集。
即把@ControllerAdvice注解内部使用@ExceptionHandler、@InitBinder、@ModelAttribute注解的方法应用到所有的 @RequestMapping注解的方法。非常简单,不过只有当使用@ExceptionHandler最有用,另外两个用处不大。
先看一个示例:
定义一个业务异常,这个异常交给@ControllerAdvice中的@ExceptionHandler处理。
package com.dxz.web.controller.excepion; /**
* 业务异常
*/
public class BusinessException extends Exception { private static final long serialVersionUID = 1L; // 业务类型
private String bizType;
// 业务代码
private int bizCode;
// 错误信息
private String message; public BusinessException(String bizType, int bizCode, String message) {
super(message);
this.bizType = bizType;
this.bizCode = bizCode;
this.message = message;
} public BusinessException(String message) {
super(message);
this.bizType = "";
this.bizCode = -1;
this.message = message;
} public BusinessException(String bizType, String message) {
super(message);
this.bizType = bizType;
this.bizCode = -1;
this.message = message;
} public BusinessException(int bizCode, String message) {
super(message);
this.bizType = "";
this.bizCode = bizCode;
this.message = message;
} public String getBizType() {
return bizType;
} public void setBizType(String bizType) {
this.bizType = bizType;
} public int getBizCode() {
return bizCode;
} public void setBizCode(int bizCode) {
this.bizCode = bizCode;
} public String getMessage() {
return message;
} public void setMessage(String message) {
this.message = message;
} }
用@ControllerAdvice为@RequestMapping注解的方法的提供@ExceptionHandler、@InitBinder、@ModelAttribute的功能。
package com.dxz.web.controller.excepion; import java.beans.PropertyEditor;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView; import com.dxz.web.model.User; /**
* @ModelAttribute用于属性注入
* @InitBinder用于参数的统一处理
* @ExceptionHandler用于捕获异常统一处理
*/
@ControllerAdvice
public class GlobalExceptionHandler { private final static String EXPTION_MSG_KEY = "message"; @ModelAttribute
public User newUser() {
System.out.println("============应用到所有@RequestMapping注解方法,在其执行之前把返回值放入Model");
return new User();
} @InitBinder
public void dataBinder(WebDataBinder binder) {
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
PropertyEditor propertyEditor = new CustomDateEditor(dateFormat, true); // 第二个参数表示是否允许为空
binder.registerCustomEditor(Date.class, propertyEditor);
} @ExceptionHandler(BusinessException.class)
@ResponseBody
public void handleBizExp(HttpServletRequest request, Exception ex) {
System.out.println("Business exception handler " + ex.getMessage());
request.getSession(true).setAttribute(EXPTION_MSG_KEY, ex.getMessage());
} @ExceptionHandler(SQLException.class)
public ModelAndView handSql(Exception ex) {
System.out.println("SQL Exception " + ex.getMessage());
ModelAndView mv = new ModelAndView();
mv.addObject("message", ex.getMessage());
mv.setViewName("sql_error");
return mv;
} }
测试的controller:
package com.dxz.web.controller; import java.io.IOException;
import java.io.Writer;
import java.sql.SQLException;
import java.util.Date; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping; import com.dxz.web.controller.excepion.BusinessException; @Controller
@RequestMapping("/user")
public class UserController { @RequestMapping("login")
public String login() {
return "login";
} @RequestMapping("login2")
public String login2() throws Exception {
throw new SQLException("数据库出错");
} @RequestMapping("login3")
public String login3() throws Exception {
throw new BusinessException("业务执行异常");
} @RequestMapping("dataBinder/{date}")
public void testDate(@PathVariable Date date, Writer writer) throws IOException {
System.out.println("date:" + date);
writer.write(String.valueOf(date.getTime()));
} // 此方法抛出的异常不是由GlobalExceptionHandler处理
// 而是在catch块处理
@RequestMapping("login4")
public String login4() {
try {
throw new BusinessException("业务执行异常");
} catch (BusinessException e) {
System.out.println("自己消化异常");
}
return "login";
} }
@ExceptionHandler演示,分别访问:
http://localhost:8080/SpringWebTraining/user/login4.do
http://localhost:8080/SpringWebTraining/user/login3.do
http://localhost:8080/SpringWebTraining/user/login2.do
测试结果:
@InitBinder演示,分别访问:
http://localhost:8080/SpringWebTraining/user/dataBinder/20171023
1、@ModelAttribute注解的方法作用请参考SpringMVC Controller 介绍
2、@InitBinder注解的方法作用请参考SpringMVC Controller 介绍
3、@ExceptionHandler,异常处理器,此注解的作用是当出现其定义的异常时进行处理的方法,其可以使用springmvc提供的数据绑定,比如注入HttpServletRequest等,还可以接受一个当前抛出的Throwable对象。可以参考javadoc或snowolf的Spring 注解学习手札(八)补遗——@ExceptionHandler。
该注解非常简单,大多数时候其实只@ExceptionHandler比较有用,其他两个用到的场景非常少,这样可以把异常处理器应用到所有控制器,而不是@Controller注解的单个控制器。
使用Spring MVC 的表单控制器SimpleFormController的更多相关文章
- spring mvc form表单提交乱码
spring mvc form表单submit直接提交出现乱码.导致乱码一般是服务器端和页面之间编码不一致造成的.根据这一思路可以依次可以有以下方案. 1.jsp页面设置编码 <%@ page ...
- Spring MVC与表单日期提交的问题
Spring MVC与表单日期提交的问题 spring mvc 本身并不提供日期类型的解析器,需要手工绑定, 否则会出现非法参数异常. org.springframework.beans.BeanIn ...
- Spring MVC 验证表单
在实际工作中,得到数据后的第一步就是检验数据的正确性,如果存在录入上的问题,一般会通过注解校验,发现错误后返回给用户,但是对于一些逻辑上的错误,比如购买金额=购买数量×单价,这样的规则就很难使用注 ...
- spring mvc 接收表单 bean
spring MVC如何接收表单bean 呢? 之前项目中MVC框架一直用struts2,所以我也就按照struts2 的思维来思考 页面loginInput.jsp: <?xml versio ...
- Spring MVC 3 表单中文提交post请求和get请求乱码问题的解决方法
在spring mvc 3.0 框架中,通过JSP页面.HTML页面以POST方式提交表单时,表单的参数传递到对应的servlet后会出现中文显示乱码的问题.解决办法可采用spring自带的过滤技术, ...
- spring:设置映射访问路径 或 xml配置访问路径 (spring mvc form表单)
项目hello, 在src/main/java下面建一个目录: charpter2 一.xml配置访问路径 web.xml <web-app> <display-name>Ar ...
- spring mvc 提交表单的例子
1. 构建MAVEN项目,然后转换成web格式,结构图如下: 2. 通过@RequestMapping来进行配置,当输入URL时,会以此找到对应方法执行,首先调用setupForm方法,该方法主要是生 ...
- spring mvc防止表单重复提交的代码片段
1.定义一个token接口 package com.bigbigrain.token; import java.lang.annotation.Documented; import java.lang ...
- spring mvc 提交表单汉字乱码
修改web.xml添加如下信息 <filter> <filter-name>characterEncodingFilter</filter-name> <fi ...
随机推荐
- one makefile file
#gcc test.cpp -L. -Wl,-Bdynamic -ltestlib -Wl,-Bstatic -ltestlib -Wl,-Bdynamic #make clean; make ini ...
- HTMLImageElement类型的简便利用
这个是我在复习书籍的时候看见的,当时一个同学想通过页面发送请求,但是数据量不是太大,所以用的get方式,但是页面用表单提交请求的话会让页面进行跳转,当时我在网上查了一点资料,发现基本上都是通过ajax ...
- mysql---多表关联
首先要介绍一下集合的概念:集合具有无序性.唯一性. 无序性:指集合内部元素没有相对顺序的概念,对于两个集合而言,只要元素值和元素个数相同则两个集合相等. 唯一性:指集合内部元素不存在值相等的元素. 上 ...
- R语言的一些笔记
(1)包中函数必须在NAMESPACE中进行标记导出,否则就不认识了: 例如叫做rtest.Model.LogisticreRression 就能识别,而叫做Model.LogisticreRress ...
- FatFsVersion0.01源码分析
目录 一.API的函数功能简述 二.FATFS主要数据结构 1.FAT32文件系统的结构 2.FATFS主要数据结构 ① FATFS ② DIR ③ FIL ④ FILINFO ⑤ wi ...
- 利用 runtime,解决多次点击相同 button,导致重复跳转的问题-b
当app有点卡的时候,多次点击相同的button,经常出现,跳转了N次相同的界面(比如闲鱼) 解决办法 用运行时和分类,替换 UIControl 响应事件,根据响应的间隔时间来判断是否执行事件. 详细 ...
- 应该知道的25个非常有用的CSS技巧
在我们的前端CSS编码当中,经常要设置特殊的字体效果,边框圆角等等,还要考虑兼 容性的问题, CSS网页布局,说难,其实很简单.说它容易,往往有很多问题困扰着新 手,在中介绍了非常多的技巧,这些小技巧 ...
- explain 用法详解
explain显示了mysql如何使用索引来处理select语句以及连接表.可以帮助选择更好的索引和写出更优化的查询语句. 使用方法,在select语句前加上explain就可以了: 如: expla ...
- Cocos2d-x内存自动释放机制--透彻篇
首先在架构里面需要明白,如果使用new创建对象的话,我们需要自己释放内存,如果直接用引擎提供的警静态方法,我们可以不做内存管理,引擎自动处理,因为引擎背后有一个自动释放池.通过查看源码可以知道,每个静 ...
- jacob访问ocx控件方法和遇到的问题
最近在进行摄像机的二次开发,摄像机厂商提供了使用C++开发的ocx控件:所以尝试使用jacob来进行访问. 操作步骤如下: 1, 从官网(http://sourceforge.net/projects ...