HTTP请求获取和返回参数的方式

2019-07-05  本文已影响0人  账号已被注销

HTTP请求获取参数的方式:

//  使用HttpServletRequest获取参数
//  需要指定Runtime,即服务器,如tomcat7.0(准确的说是需要相关jar包)
 public String hello (HttpServletRequest requet){
    String name = request.getparameter("name");
    System.out.Println(name);
    return "index";
}
//  使用某个实体类获取参数
//  直接传入实体类即可,注:需要提供get、set方法
 public String hello (User user){
    System.out.Println(user);
    return "index";
}
//  使用某个实体类获取参数
//  直接传入实体类即可,注:需要提供get、set方法(Post请求)
 public String hello (@RequestBody User user){
    System.out.Println(user);
    return "index"; 
}
//  直接传入参数
//  参数名需要和表单提交时的name一致
 public String hello (String name){
    System.out.Println(name);
    return "index";
}
//  使用@RequestParam("param")注解获取参数
//  参数名需要和表单提交时的name可以不一致
 public String hello (@RequestParam("name")String name){
    System.out.Println(name);
    return "index";
}
//  使用@PathVariable("name")注解获取参数
//  restful风格:localhost:8080/XXX/name
 public String hello (@PathVariable("name")String name){
    System.out.Println(name);
    return "index";
}

HTTP请求返回参数的方式:

//  使用HttpServletResponse返回参数
//  需要指定Runtime,即服务器,如tomcat7.0(准确的说是需要相关jar包)
 public String hello (HttpServletResponse response){
    response.setAttribute("name","hello,world");
    return "index";
}
//  使用ModelAndView返回参数
//  需要new一个ModelAndView
 public ModelAndView hello (HttpServletResponse response){
    ModelAndView  modelAndView = new ModelAndView();
    modelAndView.setViewName("hello");
    modelAndView.addObject("name","hello,world");
    return modelAndView ;
}
//  使用ModelMap返回参数
//  在方法参数中传入一个ModelMap,使用setAttribut绑定参数名和参数值
 public ModelMap hello (ModelMap map){
    map.addAttribute("name","hello,world");
    return map;
}
//  使用HttpSession 返回参数
//  在方法参数中传入一个HttpSession ,使用setAttribut绑定参数名和参数值
 public String hello (HttpSession session){
    session.setAttribute("name","hello,world");
    return "hello";
}
上一篇 下一篇

猜你喜欢

热点阅读