spring组件接收页面传来的参数和向页面传输数据方式

JAVA Spring页面传值和接收参数


    ---------------接收页面参数值有3种方式
  • 使用request

  •    例子:
    @Controller
    @RequestMapping("/demo")
    public class HelloController {
       
        //使用request接收参数
        @RequestMapping("/test1.do")
        public ModelAndView test1(HttpServletRequest request) {
            String userName = request.getParameter("userName");
            String password = request.getParameter("password");
            System.out.println(userName);
            System.out.println(password);
            return new ModelAndView("jsp/hello");
        }
  • 使用@RequestParam注解:

  • @RequestMapping("/test2.do")
        public ModelAndView test2(String userName,
                @RequestParam("password") String pwd) {
            System.out.println(userName);
            System.out.println(pwd);
            return new ModelAndView("jsp/hello");
        }
  • 使用实体对象:

  • //使用对象接收参数
        @RequestMapping("/test3.do")
        public ModelAndView test3(User user) {
            System.out.println(user.getUserName());
            System.out.println(user.getPassword());
            return new ModelAndView("jsp/hello");
        }
    --------------向页面传出数据有3种方式
  • 使用ModelAndView对象:

  • //使用ModelAndView传出数据
        @RequestMapping("/test4.do")
        public ModelAndView test4() {
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("success", true);
            data.put("message", "操作成功");
            return new ModelAndView("jsp/hello", data);
        }
  • 使用ModelMap对象:
  • //使用ModelMap传出数据
        @RequestMapping("/test5.do")
        public ModelAndView test5(ModelMap model) {
            model.addAttribute("success", false);
            model.addAttribute("message", "操作失败");
            return new ModelAndView("jsp/hello");
        }
  • 使用@ModelAttribute注解:
  • //使用@ModelAttribute传出bean属性
        @ModelAttribute("age")
        public int getAge() {
            return 25;
        }
       
        //使用@ModelAttribute传出参数值
        @RequestMapping("/test6.do")
        public ModelAndView test6(
                @ModelAttribute("userName") String userName,
                String password) {
            return new ModelAndView("jsp/hello");
        }
  • 在Controller方法参数上直接声明HttpSession即可使用


---------------附(spring组件重定向):

重定向有2种方式
使用RedirectView
使用redirect:
//使用RedirectView重定向
    @RequestMapping("/test10.do")
    public ModelAndView test10(User user) {
        if(user.getUserName().equals("tarena")) {
            return new ModelAndView("jsp/hello");
        } else {
            return new ModelAndView(new RedirectView("test9.do"));
        }
    }
   
    //使用redirect重定向
    @RequestMapping("/test11.do")
    public String test11(User user) {
        if(user.getUserName().equals("tarena")) {
            return "jsp/hello";
        } else {
            return "redirect:test9.do";
        }
    }   
   
}

猜你喜欢

转载自alendera.iteye.com/blog/2247961