[spring 3 mvc] 如何在controller类中获取到 request , session 对象?

在 controller类中,获得request 或是 session 对象,在网上查了下,没看到比较清晰的示例,贴段代码在下面:

package net.ly.controllers;

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

import javax.servlet.http.HttpServletRequest;

import org.springframework.ui.Model;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ContextLoaderListener;

@Controller
public class HelloWorldController {
	
		@RequestMapping("/helloworld")
		public ModelAndView helloWord(){
			String message = "Hello World, Spring 3.0! 你好!";
			return new ModelAndView("helloworld", "message",message);
		}

	   
		@RequestMapping(value="/hello",method=RequestMethod.GET)
		public ModelAndView hello(HttpServletRequest request){
			String  s = request.getParameter("oo");
			System.out.println("-----------------------:"+s);
			String message = "Hello, Spring 3.0! 你好!";
			Map <String, String> mymap = new HashMap(); 
			mymap.put("a1", "ab11");
			mymap.put("a2", "ab22");
			//return new ModelAndView("hello", "message", message);
			return new ModelAndView("hello",mymap);
		}
	   
		@ModelAttribute
		void beforeInvokingHandlerMethod(HttpServletRequest request) {
			request.setAttribute("foo", "bar");
		}
	   
		@RequestMapping("/hello2")
		public @ResponseBody String home() {
			return "hello liuy"; //页面上显示 hello liuy
		}
		
		/**
		 * 测试好的示例 (着重看那这个哈)
		 * */
		@ModelAttribute() //加上才能将request的内容带过来
		@RequestMapping("/hello3")
		public ModelAndView hello3(HttpServletRequest request) {
			//request 
			String s = request.getParameter("oo");
			//session
			request.getSession().setAttribute("cc","testsession");
			request.setAttribute("liuy", s);
			return new ModelAndView("hello3");
		}
  }






    加上@ModelAttribute()才可以将内容传输过来。当放置在方法参数中,@ModelAttribute将模型映射到具体属性; 也可以用他在方法级别上提供参考模型的数据. 

[spring 3 mvc] 如何在controller类中获取到 request , session 对象?》上有 13 条评论

  1. 。。。。。。。。。。。。   楼主好好研究了在下结论哦

发表评论

电子邮件地址不会被公开。

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>