异常处理
1. 未进行异常处理的异常传递流程
2. SpringMVC异常处理流程
3. SpringMVC异常处理开发步骤
- 编写自定义异常类(做提示信息的)
- 编写异常处理器
- 配置异常处理器(跳转到错误提示页面)
4. 实现
Controller中的方法
package cn.itcast.controller;
import cn.itcast.domain.User;
import cn.itcast.exception.TestException;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;
import java.util.UUID;
/**
* @author 商务小本本
*/
@Controller
@RequestMapping("/test")
public class HelloController {
@RequestMapping("/testException")
public String testException() throws TestException {
try {
int a = 10/0;
} catch (Exception e) {
e.printStackTrace();
throw new TestException("Controller报错!!!");
}
return "success";
}
}
- 编写自定义异常类(做提示信息的)
package cn.itcast.exception;
public class TestException extends Exception{
private String message;
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public TestException(String message) {
this.message = message;
}
}
- 编写异常处理器(跳转到错误提示页面)
package cn.itcast.exception;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ExceptionResolver implements HandlerExceptionResolver {
/**
* 需要实现HandlerExceptionResolver这个接口
* @param httpServletRequest
* @param httpServletResponse
* @param o
* @param e 此处的e就是Controller中testException方法抛出的异常,此处就是TestException的实例
* @return
*/
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
ModelAndView mv = new ModelAndView();
String message = e.getMessage();
mv.addObject("msg", message);
mv.setViewName("error");
return mv;
}
}
- 配置异常处理器
<bean class="cn.itcast.exception.ExceptionResolver" id="exceptionResolver"></bean>
标签:十一,系列,SpringMVC,springframework,import,org,message,servlet,public
From: https://www.cnblogs.com/wzzzj/p/18038911