nbsp;
spring mvc同时提供了很多特殊的注解,用于处理请求和渲染视图等。DispatcherServlet初始化的过程中会默认使用这些特殊bean进行配置。如果你想指定使用哪个特定的bean,你可以在web应用上下文WebApplicationContext中简单地配置它们。
特殊bean.png
其中,常用的ViewResolver的配置。以jsp作为视图为例
<!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
配置上传文件限制MultipartResolver
<!-- 上传限制 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传文件大小限制为31M,31*1024*1024 -->
<property name="maxUploadSize" value="32505856"/>
</bean>
applicationContext.xml中的标签
applicationContext.xml配置文件标签.png
文件上传
前面说到DispatcherServlet中有个特殊的Bean叫MultipartResolver,可用于限制文件的上传大小等。当解析器MultipartResolver完成处理时,请求便会像其他请求一样被正常流程处理。
<form method="post" action="/form" enctype="multipart/form-data">
<input type="text" name="name"/>
<input type="file" name="file"/>
<input type="submit"/>
</form>
@RequestMapping(path = "/form", method = RequestMethod.POST) public String handleFormUpload(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
byte[] bytes = file.getBytes();
// store the bytes somewhere
return "redirect:uploadSuccess";
}
return "redirect:uploadFailure";
}
异常处理
先来说下常见的异常处理有几种方式,如下图:
异常处理方式.png
Spring的处理器异常解析器HandlerExceptionResolver接口的实现负责处理各类控制器执行过程中出现的异常。也是上面提到的,是DispatcherServlet中的特殊bean,可以自定义配置处理。
某种程度上讲,HandlerExceptionResolver与你在web应用描述符web.xml文件中能定义的异常映射(exception mapping)很相像,不过它比后者提供了更灵活的方式。比如它能提供异常被抛出时正在执行的是哪个处理器这样的信息。
public interface HandlerExceptionResolver {
ModelAndView resolveException(
HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex);
}
@ExceptionHandler(Exception.class)
public Object exceptionHandler(Exception ex, HttpServletResponse response,
HttpServletRequest request) throws IOException {
String url = "";
String msg = ex.getMessage();
Object resultModel = null;
try {
if (ex.getClass() == HttpRequestMethodNotSupportedException.class) {
url = "admin/common/500";
System.out.println("--------毛有找到对应方法---------");
} else if (ex.getClass() == ParameterException.class) {//自定义的异常
} else if (ex.getClass() == UnauthorizedException.class) {
url = "admin/common/unauth";
System.out.println("--------毛有权限---------");
}
String header = req.getHeader("X-Requested-With");
boolean isAjax = "XMLHttpRequest".equalsIgnoreCase(header);
String method = req.getMethod();
boolean isPos