spring自定义MVC与自定义处理异常

一、spring自定义MVC

       MVC,我们都知道是model、view、controller的首字母缩写,今天来讲讲自定义的MVC,可能会对MVC有更好的理解。

1、view

      view就是我们所说的视图层,用来渲染数据的。在spring中,可以实现接口View来自定义一个view,参考代码如下:

package my.app;

import java.util.Map;

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

import org.springframework.web.servlet.View;

public class ExampleView implements View
{

	private String message;
	public ExampleView(String message)
	{
		this.message = message;
	}
	@Override
	public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/plain");
		response.getWriter().print(this.message);
		
	}

}

定义好view如何使用呢,其实很简单,跟普通类的使用是一样的,如下:

	public View Hello(Model model)
	{
		View view = new ExampleView("Hello world");
		return view;
	}

然后页面访问得到如下:

spring自定义MVC与自定义处理异常_第1张图片

2、model

上面已经定义一个view,现在要有数据,很简单,代码如下:

	public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String str = (String) model.get("message");
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/plain");
		response.getWriter().print(this.message +"   "+ str);
		
	}

我们只想在调用的时候传入参数就好,调用的时候如下:

	public View Hello(Model model)
	{
		model.addAttribute("message", "this is a test!");
		View view = new ExampleView("Hello world");
		return view;
	}

此时,我们看到的页面是:

spring自定义MVC与自定义处理异常_第2张图片

二、定义异常

链接找不到会报404,但是Handler报错会报500,此时我们只需实现接口HandlerExceptionResolver,来获取handler跑出的异常然后进行处理,参考代码:

package my.spring.exeption;

import java.util.HashMap;
import java.util.Map;

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

import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;


//当注册多个 异常处理器时,@Order决定顺序,Order越低的越先执行
@Order(-100)
public class ExceptionResolver implements HandlerExceptionResolver
{

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object obj, Exception e)
	{
		
		Map model = new HashMap();
		
		View view = new RestErorr("测试而已");
		return new ModelAndView(view, model);
	}

}

 注意:在spring-mvc.xml需要添加如下配置:

	   	
   	

 

你可能感兴趣的:(spring学习之旅)