本人对springmvc前端交互不太懂,搜索了很多关于springmvc前端交互介绍,下面我来记录一下,有需要了解的朋友可参考。希望此文章对各位有所帮助。
Controller.java代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
@Controller public class DataController { //一、接收和通过ModelMap传出参数,不需要视图解析器,测试时加了解析器,顾返回值不需后缀 //普通参数 @RequestMapping ( "/data1" ) public String data1( @RequestParam ( "uname" )String name,ModelMap mm){ //接收数据 //1.页面提交的表单域名和参数名需相同 //2.非要与提交的表单域名不一样的时候,如上加@RequestParam("uname"),但提交的表单域名名必须和uname相同 // System.out.println(name); //传递数据到页面,添加ModelMap mm,类似request.setAttribute() mm.addAttribute( "uname" , name); return "data" ; } //对象参数 @RequestMapping ( "/data2" ) public String data2(User user,ModelMap mm){ //接收数据 //提交的表单域名需和对象里的属性名一致 // System.out.println(user); //传递数据到页面,添加ModelMap mm,类似request.setAttribute() mm.addAttribute( "user" , user); return "data" ; } //二、接收和通过ModelAndView传出参数,需要配置视图解析器 @RequestMapping ( "/data3" ) public ModelAndView data3(HttpServletRequest req,HttpServletResponse resp){ ModelAndView mv = new ModelAndView(); User user = new User(); //接收数据 user.setName(req.getParameter( "name" )); user.setPassword(req.getParameter( "password" )); //传递数据 req.setAttribute( "uname" , user.getName()); req.setAttribute( "user" , user); mv.setViewName( "data" ); return mv; } } |
springmvc.xml配置
1
2
3
4
5
6
7
8
9
10
11
12
|
< mvc:annotation-driven /> <!-- viewResolver --> < bean id = "viewResolver" class = "org.springframework.web.servlet.view.UrlBasedViewResolver" > <!-- 视图解析类型 --> < property name = "viewClass" value = "org.springframework.web.servlet.view.JstlView" /> <!-- 设置前缀 --> < property name = "prefix" value = "/" /> <!-- 设置后缀 --> < property name = "suffix" value = ".jsp" /> </ bean > < context:component-scan base-package = "com.xhx.controller" /> |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:http://www.cnblogs.com/xiaohongxin/p/6516629.html