SpringMVC_Controller中方法的返回值
# 返回值的四种类型
1:ModelAndView
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。2:String
3:void
4:返回自定义类型
# ModelAndView
如果当前的Controller的方法执行完毕后,要跳转到其它jsp资源,又要传递数据,可以使用ModelAndView
package com.doaoao.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; public class HelloSpringMvc implements Controller { @Override public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception { ModelAndView mv = new ModelAndView(); mv.addObject("hello", "hello first spring mvc"); mv.setViewName("/WEB-INF/jsp/first.jsp"); return mv; } }
# String
如果当前的Controller中的方法执行完毕后,需要跳转到jsp或其它资源上,可以使用String返回值类型(不具备传递数据的能力)
// 跳转道内部资源 package com.monkey1024.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class ReturnStringController01 { @RequestMapping("/welcome.do") public String welcome() throws Exception{ //直接填写要跳转的jsp的名称 跳转到welcome.jsp上 return "welcome"; } }// 跳转到外部资源 1:配置springmvc.xml配置文件 <!-- 视图解析器 --> <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/> <!--定义外部资源view对象--> <bean id="monkey1024" class="org.springframework.web.servlet.view.RedirectView"> <property name="url" value="http://www.doaoao.com"/> </bean> // id为Controller方法的返回值 // view为要跳转的外部资源的地址 2:创建一个Controller @RequestMapping("/welcome.do") public String welcome() throws Exception{ //直接填写要跳转的jsp的名称 return "monkey1024"; }...
# Model对象和String返回值一起使用
1:创建Controller
@RequestMapping("/welcome1.do") public String welcome1(String name,Model model) throws Exception{ //这种写法spring mvc会自动为传入的参数取名 model.addAttribute(name); // 自定义名称 model.addAttribute("username", name); //直接填写要跳转的jsp的名称 return "welcome"; }2:添加显示输出的jsp文件 welcome.jsp
${username}<br> ${string}<br>
3:在浏览器中访问
http://localhost:8080/welcome1.do?name=jack# Model中的凄然方法
1:addAllAttributes(Collection<?> attributeValues); 会将传入的list中的数据对其进行命名,例如: List<Integer> integerList = new ArrayList<>(); integerList.add(1); integerList.add(5); integerList.add(3); model.addAllAttributes(integerList); 上面代码相当于: model.addAttribute("1", 1); model.addAttribute("5", 5); model.addAttribute("3", 3); 2:addAllAttributes(Map attributes);会将map中的key作为名字,value作为值放入到model对象中,例如: Map<String, Integer> integerMap = new HashMap<>(); integerMap.put("first", 1); integerMap.put("second", 2); integerMap.put("third", 3); model.addAllAttributes(integerMap); 上面代码相当于: model.addAttribute("first", 1); model.addAttribute("second", 2); model.addAttribute("third", 3);
...
# void

更多精彩