
局部异常:在 controller 层直接配置
@PostMapping("dologin")
public String dologin(User user, HttpSession session) {
if(!"zs".equals(user.getUsername())) {
throw new MyException("用户名错误!"); // 自定义异常类
//throw new RuntimeException("用户名错误!");
}
if(!"zs".equals(user.getPassword())) {
throw new MyException("密码错误!"); // 自定义异常类
//throw new RuntimeException("密码错误!");
}
return "redirect:/user/list";
}
// 局部异常处理,只对当前类生效
@ExceptionHandler(value = {MyException.class}) // 自定义异常类
//@ExceptionHandler(value = {RuntimeException.class})
public String handlerException(MyException exception, HttpServletRequest request) {
request.setAttribute("exception", exception);
return "error"; // 返回到error.jsp页面
}
全局异常配置:在 spring-context.xml 配置
<!-- 配置全局异常,对整个项目都有效 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!-- 配置具体的异常,可配置多个 -->
<!-- <prop key="java.lang.RuntimeException">error</prop> -->
<!-- 使用自定义异常类,返回到error.jsp页面 -->
<prop key="com.ssm.exception.MyException">error</prop>
<!-- <prop key="java.lang.NullPointerException">null</prop> -->
</props>
</property>
</bean>
自定义异常类:MyException.java文件
package com.ssm.exception;
public class MyException extends RuntimeException {
private static final long serialVersionUID = 1L;
public MyException() {
super();
}
public MyException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public MyException(String message, Throwable cause) {
super(message, cause);
}
public MyException(String message) {
super(message);
}
public MyException(Throwable cause) {
super(cause);
}
}