`

springmvc测试2

 
阅读更多
@Controller
@RequestMapping("/hello")
public class TestController3 {
   
	@RequestMapping  //如果访问路径是/hello, 就调用此方法
	public String toIndex(){
		return "index";
	}
	
	@RequestMapping("/index")    //访问路径为:..../hello/index
	public String hello(){
		return "index";
	}
	
	
	@RequestMapping(value="/path{id}",method=RequestMethod.GET)  //访问路径例如:hello/path2  personId就是2
	 //@PathVariable指定该变量值是从url中传递过来的(该变量名id和路径中变量id({id})一样)  
	public ModelAndView testPath(@PathVariable("id") String personId){
		System.err.println("personId=" + personId);  
		ModelAndView mav = new ModelAndView("index");
		mav.addObject("test1", "aaaa");
		mav.addObject("test2", "bbbb");
		return mav;
	}
	
	@RequestMapping("/show")
	@ResponseBody  //@ResponseBody修饰,用于显示信息,它不会转到jsp页面 ,只是把响应输出,ajax中经常用,一般将显示对象,转换成json
    public String showMessage() {   
        return "Hello,SpringMVC";   
    } 
	
	@RequestMapping("/show2")
	public @ResponseBody User showMessage2(){
		System.err.println("show2");
		User u = new User();
		u.setName("a");
		u.setAddress("c");
		return u;
	}
	
	
	//其中对象(user)属性会自动装载,  
	@RequestMapping(value="/save",method=RequestMethod.POST)
	public String save(User user,String zipcode){  
	    System.out.println(user.getName());  
	    System.out.println("zipCode:" + zipcode);  
	    return "redirect:/success.jsp";//重定向只需要加"redirect:"  
	}
	
	@RequestMapping("/testParam2")  
	//可以省略@RequestParam,用@RequestParam只是为了补加说明该变量如name,
	//取请求参数中的name的值,只要保证变量名与路径中的一样就不要用@RequestParam, 注解可以理解成是一种补加说明
	public String testParam(@RequestParam("name") String name, @RequestParam("id")String id, String test){
		System.err.println("name=" + name);
		System.err.println("id=" + id);
		System.err.println("test=" + test);
		return "display";
	}
	
	
	//使用request、response、session(只需要传进来即可)
	@RequestMapping("/testRequest")  
	public String methodA(HttpServletRequest request, HttpServletResponse response,HttpSession session){  
	    session.setAttribute("session", "Hello,Session!");  
	    return "display";   
	} 
	
	@RequestMapping("/model")   
	public String testModel(Model model){   
	    model.addAttribute("message", "model");   
	    return "display";   
	} 
	
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics