1、前提是使用注解的工程
2、一个简单例子
package com.mvc.test;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/test")
public class TestController{
@RequestMapping(value="/find",method=RequestMethod.GET)
public ModelAndView test1(HttpServletRequest arg0,
HttpServletResponse arg1) throws Exception {
String message = "find";
ModelAndView view = new ModelAndView();
view.setViewName("annocation");
view.addObject("message", message);
return view;
}
@RequestMapping(value="/get",params={"flag=1","a=2"})
public ModelAndView test2(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap)
throws Exception{
String message = "get";
modelMap.put("message", message);
return new ModelAndView("annocation",modelMap);
}
@RequestMapping("/simple")
public String simple(HttpServletRequest request)throws Exception{
request.setAttribute("message", request.getParameter("message"));
return "/annocation";
}
@RequestMapping("/test2")
public String test2(@RequestParam String name,Model model){
model.addAttribute("message", "测试:"+name);
return "/annocation";
}
@RequestMapping("${username}")
public String show(@PathVariable String username,Model model)throws Exception{
model.addAttribute("message", "Welcome," + username + "!");
return "/annocation";
}
@RequestMapping("/login")
public String login(HttpServletRequest request)throws Exception{
String username = request.getParameter("username");
String password = request.getParameter("password");
request.setAttribute("message", "Welcome," + username + "!");
return "/annocation";
}
}
# 若干种写法,如上所示
# ModelAndView是Model(一种Map)和View(视图,String或Object类型)的合体,有两个属于不同包的类 org.springframework.web.portlet.ModelAndView : 是spring的加强类;如果请求是URL,则必须有这个URL.jsp,否则会报404
org.springframework.web.servlet.ModelAndView : 则不用,URL和return 的视图可以不同
# 接收的数据可以用request也可以写在方法参数中(如Test2方法),还可以是动态参数
# 回传参数可以放在Model,ModelMap里或者直接放在request里
# 若返回的是视图,可以返回的类型可以是
(1)、String
(2)、ModelAndView
3、ModelAndView类的方法
# new ModelAndView("视图",modelMap); //modelMap里放回传参数
# new ModelAndView("view", "modelName", modelObject) //只能传一个参数
# view.addObject("modelName", modelObject)// 添加值
# view.setViewName("view"); //设置视图名字