SpringMVC其他功能
功能 | 需实现接口 |
---|---|
异常处理 | HandlerExceptionResolver |
拦截器 | HandlerInterceptor |
文件上传 | 无 |
1.异常处理
mvc可以统一处理异常,所有的异常均向上抛(包括Controller层)抛给异常处理器处理
自定义异常类
public class CustomeException extends Exception {
private String message;
}~
自定义异常处理器
public class CustomExceptionResovler implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
e.printStackTrace();
CustomeException customeException;
//抛出的异常:e是否是自定义异常
if(e instanceof CustomeException){
customeException = (CustomeException)e;
}else {
customeException = new CustomeException("运行异常");
}
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("message",customeException.getMessage());
modelAndView.setViewName("error");
return modelAndView;
}
}
~
mvc配置:
<!--异常处理器 -->
<bean id="handlerExceptionResovler" class="cn.itheima.exceptionResover.CustomExceptionResovler"></bean>~
2.拦截器
拦截器与filter过滤器相对应。
filter是Servlet规范中的一部分,任何java-web都可以使用:/* 拦截所有资源(包括静态资源);
拦截器是mvc自带的,只要使用了mvc框架才能使用拦截器。拦截器只拦截访问Controller的请求,静态资源(html,js)不拦截。拦截器和过滤器一样也有拦截器链。
定义拦截器实现登录验证,已登录放行,未登录转发至登录页面
public class CustomeInceperter implements HandlerInterceptor {
//在访问的Controller方法之前执行
ublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
//如果访问登录页面,则放行
String uri = request.getRequestURI();
if (uri.equals("/incepter/login")){
return true;
}
//如果已登录,放行
if (session.getAttribute("id")!=null){
return true;
}
//未登录,则转发到登录页面,拦截
request.getRequestDispatcher("/login.jsp").forward(request,response);
return false;
}
//Controller方法执行后执行该方法
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
}
//PostHandle执行后执行该方法
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
}
}
~
@RequestMapping("/login")
public String testIncepter(HttpSession session,User user){
session.setAttribute("id",user.getName());
return "forward:/send.jsp";
}~
mvc配置
<!--拦截器配置 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="cn.itheima.incepters.CustomeInceperter"></bean>
</mvc:interceptor>
</mvc:interceptors>~
拦截器链执行顺序
总之:逆序进行,谁放行,执行谁的afterCompletion()方法
3.文件上传
页面表单注意enctype
<form action="/test4/fileupload" enctype="multipart/form-data" method="post">
文件名称<input type="text" name="name"><br>
文件<input type="file" name="file">
<input type="submit" value="上传">
</form>~
@RequestMapping("/fileupload")
public String testFileupload(String name, MultipartFile file, HttpServletRequest request) throws IOException {
//获取文件原始名称
String originame = file.getOriginalFilename();
//获取文件拓展名
String extendName = originame.substring(originame.indexOf(".")+1,originame.length());
//为文件名加入编号,防止重名
String uuid = UUID.randomUUID().toString().replace("-","").toUpperCase();
String filename = "";
//给上传文件重命名
if (name!=null){
filename = uuid+"_"+name+"."+extendName;
}else {
filename = uuid+"."+extendName;
}
//获取文件位置
HttpSession session = request.getSession();
ServletContext context = session.getServletContext();
String basePath = context.getRealPath("/uploads");
System.out.println(basePath);
//防止一个文件夹存放文件过多,按照日期放置
String datePath = new SimpleDateFormat("yyyy-mm-dd").format(new Date());
File fileLocation = new File(basePath+"/"+datePath);
//stem.out.println(fileLocation);
//上传至指定位置
if (!fileLocation.exists()){
fileLocation.mkdirs();
}
file.transferTo(new File(fileLocation,filename));
//ystem.out.println(1/0);
return "success";
}~
mvc配置文件
<!--文件上传配置-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 最大允许上传大小5MB -->
<property name="maxUploadSize" value="5242880" />
<property name="maxInMemorySize" value="4096" />
<property name="defaultEncoding" value="UTF-8"></property>
</bean>~