SpringMVC-前段后台传递数据
Controller.java代码:
@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配置
<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" />