@Controller:用于处理http请求的
@RequestMapping:用于配置url映射
Controller接受参数
接受普通参数
<form action="user/login.do" method="post"> 账号:<input type="text" name="name"/><br /> 密码:<input type="text" name="password"/><br /> <input type="submit" value="登录" /> </form>
@Controller @RequestMapping("user") public class UserController { @RequestMapping("login.do") public String login(User user) { //User为实体类,可以直接用属性接受 System.out.println(user.getName()); System.out.println(user.getPassword()); return "index"; }
接受日期参数
<form action="user/login.do" method="post"> 日期:<input type="text" name="date"/><br /> <input type="submit" value="查看" /> </form>
@RequestMapping("login.do") public String login(Date date) { System.out.println(date); return "index"; } @InitBinder public void initBinder(ServletRequestDataBinder binder) { binder.registerCustomEditor(Date.class,new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true)); }
Controller数据保存
保存至request里
(1)ModelAndView
@RequestMapping("list.do") public ModelAndView list() { ModelAndView mv=new ModelAndView(); mv.addObject("name","hu"); //保存数据 mv.setViewName("index2"); //跳转页面 return mv; }
(2)Model
@RequestMapping("list.do") public String list(Model model) { model.addAttribute("name","zhu"); return "index2"; }
(3)map
@RequestMapping("list.do") public String list(Map<String,Object> map) { map.put("name","sheng"); return "index2"; }
(4)request
@RequestMapping("list.do") public String list(HttpServletRequest request) { request.setAttribute("name","wang"); return "index2"; }
保存至session里
(1)HttpSession
@RequestMapping("list.do") public String list(HttpSession session) { session.setAttribute("name","wang"); return "index2"; }
(2)@SessionAttributes
@SessionAttributes(names={"name"}) public class Student{ @RequestMapping("list.do") public String list(Model model) { model.addAttribute("name","zhu"); return "index2"; } }
保存至application里
@RequestMapping("list.do") public String list(HttpSession session) { session.getServletContext().setAttribute("name","wang"); return "index2"; }
Controller重定向跳转 Redirect
@RequestMapping("photo.do") public String photo() { return "redirect:photo1.do"; }