上一篇写到自定义错误处理,那么有这么个需求,如果每个模块需要错误处理页面不同,那么上面一篇写死为error.jsp就不合理了,所以就需要我们想跳哪个错误页面就哪个页面,这样就灵活多了,我采用自定义注解的方式了指定我们需求跳转的错误页面;
具体操作如下:
1)编写自定义注解类:
package com.cwh.springmvc.Annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({java.lang.annotation.ElementType.METHOD,java.lang.annotation.ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyErrorView {
String value() default "";//使用注解时不写则默认为value
}
@target为注解在那些位置有一下几种:
TYPE,FIELD, METHOD,PARAMETER,CONSTRUCTOR,LOCAL_VARIABLE,ANNOTATION_TYPE,PACKAGE
2)下面在自定义错误处理中来运用它
package com.cwh.springmvc.Exception;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import com.cwh.springmvc.Annotation.MyErrorView;
public class CommonExceptionResolver implements HandlerExceptionResolver {
private static final Log log = LogFactory.getLog(CommonExceptionResolver.class);
@Override
public ModelAndView resolveException(HttpServletRequest arg0,
HttpServletResponse arg1, Object arg2, Exception arg3) {
String errorViewJsp = "error";//默认错误处理页面
log.info(arg3);
arg3.printStackTrace();
HandlerMethod method = (HandlerMethod) arg2;
MyErrorView errorView = method.getMethodAnnotation(MyErrorView.class);
if(null != errorView&&StringUtils.isNotBlank(errorView.value())){
errorViewJsp = errorView.value();
}
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("message",arg3.getMessage());
modelAndView.setViewName(errorViewJsp);
return modelAndView;
}
}
这样在使用@MyErrorView时候我们就可以指定跳转的错误处理页面,当没有写时默认为error这个页面
3)下面我们再另加一个错误处理页面error1.jsp
<body>
This is another errorView page. <br>${message }
</body>
4)然后就可以在我们需要的地方加上这个注解即可:
//用户列表
@RequestMapping("/userlist")
@MyErrorView("error1")
public ModelAndView userlist(@RequestParam("currentpage")int currentpage,HttpSession session) throws Exception{
if(1 ==1)throw new Exception("this is a commonExceptionResolver");
//返回ModelAndView对象包含view名称和传递的对象
return new ModelAndView("UserManager","userlist","userList");
}
5)运行结果: