关于SpringMVC请求域对象的数据共享问题

网友投稿 646 2022-11-02

关于SpringMVC请求域对象的数据共享问题

关于SpringMVC请求域对象的数据共享问题

SpringMVC支持路径中的占位符。

可以通过路径的方式来传参。restful风格。使用{}做占位符在路径中指定参数,使用@PathVariable注解在参数列表中指定。

传了参数

@RequestMapping("/test/{id}")

public String test(@PathVariable("id")Integer id){

System.out.println(id);

return "index";

}

如果使用了占位符则请求地址必须有值,否则会报404错误。

获取请求参数

使用ServletAPI获取(基本不用)

@RequestMapping("/testParam")

public String Param(HttpServletRequest request){

String userName = request.getParameter("userName");

String password = request.getParameter("password");

return "index";

}

通过控制器的形参获取(保证参数名相同的情况下)牛逼

传了参数

@RequestMapping("/testParam")

public String testParam(String username,String password){

System.out.println("username:"+username+",password:"+password);

return "index";

}

RequestParam

请求参数和控制器形参创建映射关系。

ValueRequiredDefaultValue

使用实体类接受请求参数

@RequestMapping("/testPojo")

public String testPojo(User user){

System.out.println(user);

return "index";

}

配置过滤器,处理乱码问题

CharacterEncodingFilter

org.springframework.web.filter.CharacterEncodingFilter

encoding

UTF-8

forceResponseEncoding

true

CharacterEncodingFilter

/*

域对象共享数据

使用原生ServletAPI向request域对象共享数据(不用)

@RequestMapping("/test")

public String test(HttpServletRequest request){

request.setAttribute("hello","hello");

return "index";

}

使用ModelAndView对象

返回值类型为ModelAndView

//使用ModelAndView对象的方式

@RequestMapping("/")

public ModelAndView toIndex(HttpServletRequest request){

ModelAndView mav = new ModelAndView();

//设置共享数据

mav.addObject("result","mavResult");

//设置视图名称

//视图名称=逻辑视图名称。

mav.setViewName("index");

return mav;

}

使用Model对象

Model是一个接口,因此不能像ModelAndView那样去new。

//使用Model对象的方式

@RequestMapping("/")

public String toIndexModel(Model model){

//设置共享数据

model.addAttribute("result","ModelResult");

return "index";

}

使用Map集合

//使用Map对象的方式

@RequestMapping("/")

public String toIndexModel(Map map){

//设置共享数据

map.put("result","MapResult");

return "index";

}

使用ModelMap

ModelMap的实例是由mvc框架自动创建并作为控制器方法参数传入,无需也不能自己创建。

如自己创建,则无法共享数据。

//使用ModelMap对象的方式

@RequestMapping("/")

public String toIndexModel(ModelMap modelMap){

//设置共享数据

modelMap.addAttribute("result","ModelMapResult");

return "index";

}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:God - Ruby编写的一个易于配置,易于扩展的监测框架
下一篇:vue-think是一套基于Vue全家桶+ ThinkPHP5的前后端分离框架
相关文章

 发表评论

暂时没有评论,来抢沙发吧~