spring -- @RequestAttribute注解

注解@RequestAttribute可以被用于访问由过滤器或拦截器创建的、预先存在的请求属性

例1:请求预先存在的属性。

先用@ModelAttribute定义预先存在的属性

@ModelAttribute
	void beforeInvokingHandlerMethod(HttpServletRequest request) {
		request.setAttribute("foo", "hello world");
	}
@RequestAttribute 去请求数据:

@ModelAttribute
	void beforeInvokingHandlerMethod(HttpServletRequest request) {
		request.setAttribute("foo", "hello world");
	}
	
	@RequestMapping(value="/data/custom", method=RequestMethod.GET)
	public @ResponseBody String custom(@RequestAttribute("foo") String foo) {
		return "Got 'foo' request attribute value '" + foo + "'";
	}
在HTML页面中请求数据:

Custom Resolvable Web Arguments

用ajax请求数据:

$("a.textLink").click(function() {
		var link = $(this);
		$.ajax({
			url: link.attr("href"),
			dataType: "text",
			success: function (text) {
				alert(text)
			}
		})
	})
运行结果:

spring -- @RequestAttribute注解_第1张图片

例2:请求拦截器创建的属性。

创建一个拦截器类 TestFilter

@WebFilter(filterName = "myFilter",description = "测试过滤器",urlPatterns = {"/*"})
public class TestFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
          System.out.println(" 我是过滤器类 ");
          servletRequest.setAttribute("test","you got it ");
          filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
请求创建的属性:

@RequestMapping(value="/data/custom", method=RequestMethod.GET)
	public @ResponseBody String custom(@RequestAttribute("foo") String foo,
									   @RequestAttribute("test") String test) {
		System.out.println("Got 'foo' request attribute value '" + foo + "'------"+test);
		return "Got 'foo' request attribute value '" + foo + "'------"+test;
	}
运行结果:






你可能感兴趣的:(spring,注解,spring)