1. 程式人生 > >spring-mvc 異常處理

spring-mvc 異常處理

頁面處理異常處理方法:

方法一:@ControllerAdvice + @ExceptionHandler

@ControllerAdvice
public class MyExceptionController {

	@ExceptionHandler(value={Exception.class})
	public ModelAndView excepationHadler(Exception ex){
		ModelAndView mv	= new ModelAndView();
		
		StringWriter writer = new StringWriter();
		PrintWriter s = new PrintWriter(writer);
		ex.printStackTrace(s);
		mv.addObject("exception",writer.toString());
		mv.setViewName("error");
		return mv;
	}
}

方法二:SimpleMappingExceptionResolver,採用spring-mvc 自帶的異常處理,需要在xml配置bean注入。

	<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
		<property name="exceptionMappings">
			<props>
				<prop key="java.lang.NullPointerException">error</prop>
			</props>
			
		</property>
	</bean>

方法三:繼承HandlerExceptionResolver +配置自定義實現的類

public class MyExcetionHandler implements HandlerExceptionResolver{

	@Override
	public ModelAndView resolveException(HttpServletRequest httpservletrequest,
			HttpServletResponse httpservletresponse, Object obj,
			Exception exception) {

		ModelAndView mv	= new ModelAndView();
		
		StringWriter writer = new StringWriter();
		PrintWriter s = new PrintWriter(writer);
		exception.printStackTrace(s);
		mv.addObject("exception",writer.toString());
		mv.setViewName("error");
		return mv;
	}

}


<bean class="com.mobile263.exception.MyExcetionHandler"></bean>