码迷,mamicode.com
首页 > 编程语言 > 详细

四、Springmvc异常处理器

时间:2018-11-05 19:01:12      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:autowire   err   地方   item   name   control   springmvc   message   异常类   

springmvc.xml

添加异常处理器

<!-- Springmvc异常处理器 -->
<bean class="com.itheima.springmvc.exception.CustomExceptionResolver"></bean>

CustomExceptionResolver

package com.itheima.springmvc.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

/**
 * 异常处理器的自定义的实现类
 * @author mjl
 *
 */
public class CustomExceptionResolver implements HandlerExceptionResolver{

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object obj,
			Exception e) {
		//obj 发生异常的地方  包名+类名+方法名(形参) 字符串
		ModelAndView mv = new ModelAndView();
		
		//判断异常类型
		if(e instanceof MessageException){
			//预期异常
			MessageException me = (MessageException)e;
			mv.addObject("errorPage", me.getMsg());
		}else{
			mv.addObject("errorPage","未知异常");
		}
		
		mv.setViewName("showError");
		
		return mv;
	}

}

MessageException

package com.itheima.springmvc.exception;

public class MessageException extends Exception{

	private String msg;

	public MessageException(String msg) {
		super();
		this.msg = msg;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}
	
}

ItemController

@Controller
public class ItemController {

	@Autowired
	private ItemService itemService;
	
	/**
	 * void-
	 * @throws MessageException 
	 */
	@RequestMapping(value="/item/itemList.action")
	public void itemList(Model model,HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException, MessageException{
		
		//已知的异常类型
	//	Integer i =1/0;
		
		List<Items> list = itemService.selectItemList();
		
		//自定义的异常类型
		if(null == null){
			throw new MessageException("商品信息不能为空");
		}
		
		model.addAttribute("itemList", list);
		request.getRequestDispatcher("/itemList").forward(request, response);
	}
}

  

  

  

四、Springmvc异常处理器

标签:autowire   err   地方   item   name   control   springmvc   message   异常类   

原文地址:https://www.cnblogs.com/syj1993/p/9910318.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!