1. 程式人生 > >四、Springmvc異常處理器

四、Springmvc異常處理器

else pack springmvc item 地方 類名 add 添加 emc

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異常處理器