SpringMVC传值、转发、重定向例子
SpringMVC中的Model对象用法说明

SpringMVC中的Model对象⽤法说明模型对象的作⽤主要是保存数据,可以借助它们将数据带到前端。
常⽤的模型对象有以下⼏个:ModelAndView(顾名思义,模型和视图,既可以携带数据信息,也可以携带视图信息,常规⽤法如下)/*** ModelAndView 绑定数据到视图(ModelMap⽤于传递数据 View对象⽤于跳转)* @return* @throws Exception*/@RequestMapping(value="/case2")public ModelAndView case2() throws Exception {ModelAndView mav = new ModelAndView();mav.setViewName("/demo03/model.jsp");mav.addObject("sex", "boy");return mav;}Map,和modelAndView原理⼀样,同样是将数据⼀个⼀个放在requestScope中,前端取数据同样也是${模型数据} /*** ⽬标⽅法可以添加 Map 类型(实际上也可以是 Model 类型或 ModelMap 类型)的参数.* @param map* @return*/@RequestMapping("/case")public String case1(Map map) throws Exception{map.put("sex", "获取成功!!");return "/demo03/model.jsp";}@SessionAttributes(相当于创建session对象,往session对象⾥放数据,这⾥⽤⼀个注解完美解决)基本格式如下:/*** @SessionAttributes 除了可以通过属性名指定需要放到会话中的属性外(实际上使⽤的是 value 属性值),* 还可以通过模型属性的对象类型指定哪些模型属性需要放到会话中(实际上使⽤的是 types 属性值)* 注意: 该注解只能放在类的上⾯. ⽽不能修饰⽅法当于在map中和session中各存放了⼀个实体类,⼀个String类的字符串*/@SessionAttributes("user")@Controllerpublic class SessionController {@ModelAttribute("user")public User getUser(){User user = new User();return user;}/*** http://localhost:8080/s/s1?id=1* 请求转发 forward: 不需要任何处理* 请求重定向 redirect: 使⽤SessionAttribute⽅式⽤于在重定向中传⾄将值存储在session中【⽤完记住清除】* @return* @throws Exception*/@RequestMapping(value="/s1",method=RequestMethod.GET)public String case1(@ModelAttribute("user") User user) throws Exception{return "redirect:/s2";}@RequestMapping(value="/s2",method=RequestMethod.GET)public String case2(Map map,HttpServletResponse res,SessionStatus sessionStatus) throws Exception{User user=(User)map.get("user");res.getWriter().println(user.getId());sessionStatus.setComplete();return null;}}SpringMVC中的Model和ModelAndView的区别1.主要区别Model是每次请求中都存在的默认参数,利⽤其addAttribute()⽅法即可将服务器的值传递到jsp页⾯中;ModelAndView包含model和view两部分,使⽤时需要⾃⼰实例化,利⽤ModelMap⽤来传值,也可以设置view的名称2.例⼦1)使⽤Model传值@RequestMapping(value="/list-books")private String getAllBooks(Model model){logger.error("/list-books");List<Book> books= bookService.getAllBooks();model.addAttribute("books", books);return "BookList";}在jsp页⾯利${books}即可取出其中的值2)使⽤ModelAndView传递值有两种⽅法,不同⽅法在jsp页⾯的取值⽅式不同,同时设置了view的名称public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response,Object handler, Exception ex) {LibraryException le=null;if(ex instanceof LibraryException){le=(LibraryException)ex;}else{le=new LibraryException("系统未知异常!");}ModelAndView modelAndView=new ModelAndView();modelAndView.addObject("exception",le.getMessage());modelAndView.getModel().put("exception",le.getMessage());modelAndView.setViewName("error");return modelAndView;}jsp中${requestScope.exception1}可以取出exception1的值;jsp中${exception2}可以取出exception2的值以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。
springboot重定向传递参数

springboot重定向传递参数在Spring Boot中,重定向和传递参数是很常见的需求。
Spring Boot提供了多种方式来实现重定向并传递参数的功能。
一种常见的重定向和传递参数的方式是使用RedirectAttributes。
RedirectAttributes是Spring MVC提供的一种特殊的Model对象,它可以在重定向的过程中传递参数。
使用RedirectAttributes可以将参数添加到重定向的URL中,也可以将参数作为FlashAttribute传递。
首先,我们需要在处理重定向的方法中使用RedirectAttributes参数。
例如,我们有一个处理POST请求的方法,该方法在处理完请求后需要重定向到另一个页面,并传递参数:```javapublic String submitForm(Model model, RedirectAttributes redirectAttributes)//处理表单提交的数据//...//添加参数到重定向URLredirectAttributes.addAttribute("message", "成功提交表单");//重定向到另一个页面return "redirect:/result";```在上面的例子中,我们使用了addAttribute方法将参数"message"和它的值"成功提交表单"添加到重定向的URL中。
注意,这里的addAttribute方法是将参数添加到URL的查询字符串中。
```javamodel.addAttribute("message", message);return "result";```除了使用addAttribute方法将参数添加到URL的查询字符串中,我们还可以使用addFlashAttribute方法将参数作为FlashAttribute传递。
springboot实现转发和重定向

springboot实现转发和重定向1、转发⽅式⼀:使⽤ "forword" 关键字(不是指java关键字),注意:类的注解不能使⽤@RestController 要⽤@Controller1 2 3 4@RequestMapping(value="/test/test01/{name}", method = RequestMethod.GET)public String test(@PathVariable String name) {return"forword:/ceng/hello.html";}⽅式⼆:使⽤servlet 提供的API,注意:类的注解可以使⽤@RestController,也可以使⽤@Controller1 2 3 4@RequestMapping(value="/test/test01/{name}", method = RequestMethod.GET)public void test(@PathVariable String name, HttpServletRequest request, HttpServletResponse response) throws Exception { request.getRequestDispatcher("/ceng/hello.html").forward(request,response);}2、重定向⽅式⼀:使⽤ "redirect" 关键字(不是指java关键字),注意:类的注解不能使⽤@RestController,要⽤@Controller1 2 3 4@RequestMapping(value="/test/test01/{name}", method = RequestMethod.GET)public String test(@PathVariable String name) {return"redirect:/ceng/hello.html";}⽅式⼆:使⽤servlet 提供的API,注意:类的注解可以使⽤@RestController,也可以使⽤@Controller1 2 3 4@RequestMapping(value="/test/test01/{name}", method = RequestMethod.GET)public void test(@PathVariable String name, HttpServletResponse response) throws IOException { response.sendRedirect("/ceng/hello.html");}使⽤API进⾏重定向时,⼀般会在url之前加上:request.getContextPath()。
springMVC学习五参数传递(包括restful风格)

springMVC学习五参数传递(包括restful风格)(⼀)SpringMVC Controller接受参数的⽅式(1)前端传递的参数,在springMVC的controller中使⽤基本数据类型或者String 类型进⾏接受在前端有⼀个form表单,需要传递姓名和年龄,在controller可以采⽤基本数据类型或者String进⾏接受,<form action="demo" method="post">名字:<input type="text" name="name"/><br/>年龄:<input type="text" name="age"/><br/><input type="submit" value="提交"/><br/></form>此时值需要接受参数的名称和传递的参数名称⼀致就⾏fun01(String name,int age)@Controllerpublic class DemoController {@RequestMapping("/demo")public String fun01(String name,int age) {//字符串的返回值代表代表要跳转的页⾯System.out.println(name);System.out.println(age);System.out.println("指定了demo");//返回值最好写全路径,全路径就是以"/"开头的路径,否则就是相对路径,//相对路径就是以相对当前⽅法的映射路径,例如如果返回值是"main.jsp",是相对路径,最后的绝对路径是//"demo/main.jsp"return "/main.jsp";}}(2)前端传递的参数,在springMVC的controller中使⽤类类型进⾏接受(⾛get/set⽅法)此时需要类类型的属性名称与前端传递参数的参数名称⼀致@Controllerpublic class DemoController {@RequestMapping("/demo")public String fun01(People peo) {//字符串的返回值代表代表要跳转的页⾯System.out.println(peo.getName());System.out.println(peo.getAge());System.out.println("指定了demo");//返回值最好写全路径,全路径就是以"/"开头的路径,否则就是相对路径,//相对路径就是以相对当前⽅法的映射路径,例如如果返回值是"main.jsp",是相对路径,最后的绝对路径是//"demo/main.jsp"return "/main.jsp";}}(3)前端传递的参数,在springMVC的controller中使⽤HttpServletRequest进⾏接受@Controllerpublic class DemoController {@RequestMapping("/demo")public String fun01(HttpServletRequest req) {//字符串的返回值代表代表要跳转的页⾯System.out.println("指定了demo");//返回值最好写全路径,全路径就是以"/"开头的路径,否则就是相对路径,//相对路径就是以相对当前⽅法的映射路径,例如如果返回值是"main.jsp",是相对路径,最后的绝对路径是//"demo/main.jsp"System.out.println(req.getParameter("name"));System.out.println(req.getParameter("age"));return "/main.jsp";}}(4)前端传递的参数,在springMVC的controller中同时使⽤上述三中⽅法进⾏接受@Controllerpublic class DemoController {@RequestMapping("/demo")public String fun01(People peo, String name,int age,HttpServletRequest req) {//字符串的返回值代表代表要跳转的页⾯System.out.println(name);System.out.println(age);System.out.println(peo.getName());System.out.println(peo.getAge());System.out.println("指定了demo");//返回值最好写全路径,全路径就是以"/"开头的路径,否则就是相对路径,//相对路径就是以相对当前⽅法的映射路径,例如如果返回值是"main.jsp",是相对路径,最后的绝对路径是//"demo/main.jsp"System.out.println(req.getParameter("name"));System.out.println(req.getParameter("age"));return "/main.jsp";}}(⼆)@RequestParam()注解(1)如果请求参数名和⽅法参数名不对,使⽤value属性@RequestMapping("demo")public String demo(@RequestParam(value="name1") String name,@RequestParam(value="age1")int age){System.out.println("执⾏ demo"+" "+name+""+age);return "main.jsp";}(2)如果接受参数是基本类型,且接受参数类型与null⽆法进⾏兼容,此时可以采⽤包装类型或者采⽤默认值,使⽤defaultValue属性@RequestMapping("page")public String page(@RequestParam(defaultValue="2")int pageSize,@RequestParam(defaultValue="1") int pageNumber){ System.out.println(pageSize+" "+pageNumber); return "main.jsp";}(3)如果强制要求必须有某个参数,使⽤required属性@RequestMapping("demo2")public String demo2(@RequestParam(required=true) String name){ System.out.println("name 是 SQL 的查询条件,必须要传递 name 参数"+name); return "main.jsp";}(4)传递List类型的参数使⽤value属性,因为在前端传递过来的list都会放⼊⼀个参数名称中,只要把这个参数名称和⼀个List类型变量进⾏绑定@RequestMapping("demo5")public String demo5(String name,int age,@RequestParam("hover")List<String> abc){ System.out.println(name+" "+age+" "+abc); return "main.jsp";}(5)请求参数中对象.属性格式jsp中的代码如下<input type="text" name=""/><input type="text" name="peo.age"/>此时需要创建⼀个类,类中要有⼀个属性是peo,且这个属性的类型必须是包含name,age这个两个属性的类,两个类都要有get/set⽅法,Demo类型public class Demo {private People peo;public People getPeo() {return peo;}public void setPeo(People peo) {this.peo = peo;}@Overridepublic String toString() {return "Demo [peo=" + peo + "]";}}People 类型public class People {private String name;private Integer age;public String getName() {return name;}public void setName(String name) { = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}@Overridepublic String toString() {return "People [name=" + name + ", age=" + age + "]";}}controller 的接受参数@RequestMapping("demo6")public String demo6(Demo demo){ System.out.println(demo); return "main.jsp";}(三) restful风格的参数⾸先请求参数的格式⼀定的要求,⽼的⽅式是<a href="demo8?name=张三&age=23">跳转</a>,⽽restful格式是:<a href="demo8/123/abc">跳转</a>在控制器中:在@RequestMapping 中⼀定要和请求格式对应{名称} 中名称⾃定义名称@PathVariable 获取@RequestMapping 中内容,默认按照⽅法参数名称去寻找. @RequestMapping("demo8/{id1}/{name}")public String demo8(@PathVariable String name,@PathVariable("id1") int age){ System.out.println(name +" "+age); return "/main.jsp";}。
SpringMVC向页面传递参数的4种方式

SpringMVC向页面传递参数的4种方式1、使用HttpServletRequest和Session 然后setAttribute(),就和Servlet 中一样request.setAttribute(“user”,user_data);2、使用ModelAndView对象@RequestMapping("/login.do")publicModelAndView login(String name,String pass){User user = userService.login(name,pwd);Map<String,Object> data = new HashMap<String,Object>();data.put("user",user);return newModelAndView("success",data);}3、使用ModelMap对象ModelMap数据会利用HttpServletRequest的Attribute传值到success.jsp中@RequestMapping("/login.do")public String login(String name,String pass ,ModelMapmodelMap){User user =userService.login(name,pwd);modelMap.addAttribute("user",user);modelMap.put("name",name);return "success";}Session存储,可以利用HttpServletReequest的getSession()方法@RequestMapping("/login.do")Public String login (String name,Stringpwd,ModelMapmodel,HttpServletRequest request) {User user = serService.login(name,pwd);HttpSession session = request.getSession();session.setAttribute("user",user);model.addAttribute("user",user);return "success";}4、使用@ModelAttribute注解@ModelAttribute数据会利用HttpServletRequest的Attribute传值到success.jsp中@RequestMapping("/login.do")public String login(@ModelAttribute("user") User user){return "success";}@ModelAttribute("name")public String getName(){return name;}Spring MVC 默认采用的是转发来定位视图,如果要使用重定向,可以如下操作A、使用RedirectViewpublicModelAndView login(){RedirectView view = new RedirectView("regirst.do");return newModelAndView(view);}B、使用redirect:前缀public String login(){return "redirect:regirst.do";}。
转发和重定向的区别与联系

转发和重定向的区别与联系作为⼀名Java Web开发的程序员,在使⽤Servlet/JSP的时候,我们必须要知道实现页⾯跳转的两种⽅式的区别和联系:即转发和重定向的区别。
什么是转发客户⾸先发送⼀个请求到服务器端,服务器端发现匹配的Servlet,并指定它去执⾏。
当这个Servlet执⾏完之后,它要调⽤getRequestDispacther()⽅法,把请求转发给指定的JSP,整个流程都是在服务器端完成的,⽽且是在同⼀个请求⾥⾯完成的,因此Servlet和JSP共享的是同⼀个Request,在Servlet⾥⾯放的所有东西,在JSP中都能取出来,因此,JSP能把结果getAttribute()出来,getAttribute()出来后执⾏完把结果返回给客户端。
整个过程是⼀个请求,⼀个响应。
request.getRequestDispatcher("/yanggb.jsp").forword(request, response);什么是重定向客户⾸先发送⼀个请求到服务器端,服务器端发现匹配的Servlet,并指定它去执⾏。
当这个Servlet执⾏完之后,它就会调⽤sendRedirect()⽅法,⽴即向客户端返回这个响应,响应告诉客户端你必须要再发送⼀个请求,去访问JSP。
紧接着客户端收到这个请求后,就会⽴刻发出⼀个新的请求,去请求JSP,这⾥的两个请求互不⼲扰,相互独⽴。
这就意味着,在前⾯Request⾥⾯setAttribute()的任何东西,在后⾯的request⾥⾯都获得不了。
由此可见,在sendRedirect()⾥⾯是两个请求,两个响应(服务器向浏览器发送⼀个302状态码以及⼀个location消息头,浏览器收到请求后会向再次根据重定向地址发出请求)。
response.sendRedirect("/yanggb.jsp");区别与联系1.RequestDispatcher.forward()⽅法只能将请求转发给同⼀个WEB应⽤中的组件;⽽HttpServletResponse.sendRedirect()⽅法不仅可以重定向到当前应⽤程序中的其他资源,还可以重定向到同⼀个站点上的其他应⽤程序中的资源,甚⾄是使⽤绝对URL重定向到其他站点的资源。
SpringMVC(三)控制器获取页面请求参数以及将控制器数据传递给页面和实现重定向的方式

SpringMVC(三)控制器获取页⾯请求参数以及将控制器数据传递给页⾯和实现重定向的⽅式⾸先做好环境配置在mvc.xml⾥进⾏配置 1.开启组件扫描 2.开启基于mvc的标注 3.配置试图处理器1 <?xml version="1.0" encoding="UTF-8"?>2 <beans xmlns="/schema/beans"3 xmlns:xsi="/2001/XMLSchema-instance"4 xmlns:context="/schema/context"5 xmlns:lang="/schema/lang"6 xmlns:mvc="/schema/mvc"7 xmlns:util="/schema/util"8 xmlns:task="/schema/task"9 xmlns:aop="/schema/aop"10 xsi:schemaLocation="/schema/mvc /schema/mvc/spring-mvc-4.1.xsd11 /schema/task /schema/task/spring-task-4.1.xsd12 /schema/beans /schema/beans/spring-beans.xsd13 /schema/context /schema/context/spring-context-4.1.xsd14 /schema/lang /schema/lang/spring-lang-4.1.xsd15 /schema/aop /schema/aop/spring-aop-4.1.xsd16 /schema/util /schema/util/spring-util-4.1.xsd">17 <!-- 开启组件扫描 -->18 <context:component-scan base-package="com.xcz"></context:component-scan>19 <!-- 开启mvc标注 -->20 <mvc:annotation-driven></mvc:annotation-driven>21 <!-- 配置视图处理器 -->22 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">23 <property name="prefix" value="/WEB-INF/"></property>24 <property name="suffix" value=".jsp"></property>25 </bean>26 </beans>mvc.xml在web.xml配置 1.配置请求参数如⼊⼝ 2.配置初始化参数1 <?xml version="1.0" encoding="UTF-8"?>2 <web-app xmlns:xsi="/2001/XMLSchema-instance" xmlns="/xml/ns/javaee" xsi:schemaLocation="/xml/ns/javaee /xml/ns/javaee/web-app_3_1.xsd" version="3.1">3 <display-name>SpringMVC-03</display-name>4 <welcome-file-list>5 <welcome-file>index.html</welcome-file>6 <welcome-file>index.htm</welcome-file>7 <welcome-file>index.jsp</welcome-file>8 <welcome-file>default.html</welcome-file>9 <welcome-file>default.htm</welcome-file>10 <welcome-file>default.jsp</welcome-file>11 </welcome-file-list>12 <!-- 配置请求⼊⼝ -->13 <servlet>14 <servlet-name>SpringMVC</servlet-name>15 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>16 <!-- 配置初始化参数 -->17 <init-param>18 <param-name>contextConfigLocation</param-name>19 <param-value>classpath:mvc.xml</param-value>20 </init-param>21 <load-on-startup>1</load-on-startup>22 </servlet>23 <servlet-mapping>24 <servlet-name>SpringMVC</servlet-name>25 <url-pattern>*.do</url-pattern>26 </servlet-mapping>27 </web-app>web.xml控制器获取页⾯请求参数⽅式如下: 1.使⽤HttpServletRequest获取直接定义 HttpServletRequest参数 2.直接把请求参数的名字定义成控制器的参数名 3.当页⾯参数和控制器参数不⼀致可以使⽤ @RequestParam("页⾯参数名"),加在控制器⽅法对应的参数上1package com.xcz.controller;23import javax.servlet.http.HttpServletRequest;45import org.springframework.stereotype.Controller;6import org.springframework.ui.Model;7import org.springframework.ui.ModelMap;8import org.springframework.web.bind.annotation.RequestMapping;9import org.springframework.web.bind.annotation.RequestParam;10import org.springframework.web.servlet.ModelAndView;1112 @Controller13public class LoginController {14// 获取参数⽅式⼀15 @RequestMapping("/login.do")16public String login(HttpServletRequest request) {17 String username = request.getParameter("username");18 String password = request.getParameter("password");19 System.out.println(username + ":" + password);20return "login";21 }2223// 获取参数⽅式⼆24 @RequestMapping("/login2.do")25public String login2(String username, String password) {26 System.out.println(username + ":" + password);27return "login";2930// 获取参数⽅式三31 @RequestMapping("/login3.do")32public String login3(@RequestParam("username") String uname, @RequestParam("password") String pwd) {33 System.out.println(uname + ":" + pwd);34return "login";35 }36 }LoginController1 <%@ page language="java" contentType="text/html; charset=utf-8"2 pageEncoding="utf-8"%>3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd">4 <html>5 <head>6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">7 <title>Insert title here</title>8 </head>9 <body>10 <form action="${pageContext.request.contextPath }/login8.do"> <!--${pageContext.request.contextPath }动态获取路径 --> 11账号:<input type="text" name="username" ><br>12密码:<input type="text" name="password" ><br>13 <input type="submit" value="登录"><br>14 </form>15 </body>16 </html>login.lsp控制器中数据传递给页⾯的⽅式如下: 1.使⽤ request session application 这些域对象传输 2.使⽤ModelAndView来传输数据 //mav.getModel().put("username", username); mav.getModelMap().addAttribute("username", username); 3.使⽤ Model 来传输数据 4.使⽤ModelMap 进⾏传参1package com.xcz.controller;23import javax.servlet.http.HttpServletRequest;45import org.springframework.stereotype.Controller;6import org.springframework.ui.Model;7import org.springframework.ui.ModelMap;8import org.springframework.web.bind.annotation.RequestMapping;9import org.springframework.web.bind.annotation.RequestParam;10import org.springframework.web.servlet.ModelAndView;1112 @Controller13public class LoginController {14// 將控制器中的数据传给页⾯⽅式⼀15 @RequestMapping("/login4.do")16public String login4(@RequestParam("username") String uname, @RequestParam("password") String pwd,17 HttpServletRequest request) {18 System.out.println(uname + ":" + pwd);19 request.setAttribute("username", uname);20return "main";21 }2223// 將控制器中的数据传给页⾯⽅式⼆24 @RequestMapping("/login5.do")25public ModelAndView login5(@RequestParam("username") String uname, @RequestParam("password") String pwd) {26 System.out.println(uname + ":" + pwd);27 ModelAndView mav = new ModelAndView();28 mav.setViewName("main");29 mav.getModel().put("username", uname);30return mav;31 }3233// 將控制器中的数据传给页⾯⽅式三34 @RequestMapping("/login6.do")35public ModelAndView login6(@RequestParam("username") String uname, @RequestParam("password") String pwd,36 ModelAndView mav) {37 System.out.println(uname + ":" + pwd);38 mav.setViewName("main");39 mav.getModelMap().addAttribute("username", uname);40// mav.getModelMap().put("username", uname);41return mav;42 }4344// 將控制器中的数据传给页⾯⽅式四45 @RequestMapping("/login7.do")46public String login7(@RequestParam("username") String uname, @RequestParam("password") String pwd, Model model) {47 System.out.println(uname + ":" + pwd);48 model.addAttribute("username", uname);49return "main";50 }5152//將控制器中的数据传给页⾯⽅式五53 @RequestMapping("/login8.do")54public String login8(@RequestParam("username") String uname, @RequestParam("password") String pwd,ModelMap map) {55 System.out.println(uname + ":" + pwd);56 map.put("username", uname);57return "main";58 }59 }LoginController1 <%@ page language="java" contentType="text/html; charset=utf-8"2 pageEncoding="utf-8"%>3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd">4 <html>5 <head>6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">7 <title>Insert title here</title>8 </head>9 <body>10 <form action="${pageContext.request.contextPath }/login8.do"> <!--${pageContext.request.contextPath }动态获取路径 --> 11账号:<input type="text" name="username" ><br>12密码:<input type="text" name="password" ><br>13 <input type="submit" value="登录"><br>14 </form>15 </body>16 </html>1 <%@ page language="java" contentType="text/html; charset=utf-8"2 pageEncoding="utf-8"%>3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd">4 <html>5 <head>6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">7 <title>Insert title here</title>8 </head>9 <body>10 <h1>欢迎${username }来访</h1>11 </body>12 </html>main.jsp实现重定向⽅式如下: 1.当控制器⽅法返回String时return"redirect:路径"; 默认是转发,转发的结果直接交给ViewResolver可以通过加forward:来继续处理,⽽不交给ViewResolver 2.当控制器⽅法返回 ModelAndView 时使⽤RedirectView 完成重定向(/代表项⽬名前⾯的部分不包含项⽬名)1package com.xcz.controller;23import javax.servlet.http.HttpServletRequest;4import org.springframework.stereotype.Controller;5import org.springframework.web.bind.annotation.RequestMapping;6import org.springframework.web.bind.annotation.RequestParam;7import org.springframework.web.servlet.ModelAndView;8import org.springframework.web.servlet.view.RedirectView;910 @Controller11public class LoginController {12private static final String URL = "toMain.do";13 @RequestMapping("/toLogin.do")14public String toLogin() {15return "login";16 }17 @RequestMapping("/toMain.do")18public String toMain() {19return "main";20 }21// 实现重定向⽅式⼀22 @RequestMapping("/login.do")23public String login(@RequestParam("username") String uname,@RequestParam("password") String pwd,HttpServletRequest request) {24 System.out.println(uname + ":" + pwd);25 request.setAttribute("usernameq", uname);26 request.setAttribute("password", pwd);27//return "redirect:/toMain.do"; //使⽤redirect: 直接重定向,导致数据丢失,所以页⾯⽆法获取28return "forward:/toMain.do"; //使⽤forward: 先转发后跳转到main.jsp,不会导致数据丢失,所以页⾯可以获取控制器数据29 }30// 实现重定向⽅式⼆31 @RequestMapping("/login1.do")32public ModelAndView login1(@RequestParam("username") String uname,@RequestParam("password") String pwd,HttpServletRequest request) {33 System.out.println(uname + ":" + pwd); //打印后台数据34 String path = request.getServletContext().getContextPath(); //获取项⽬名前⾯的路径35 ModelAndView mView = new ModelAndView();36 RedirectView rView = new RedirectView(path + "/" + URL); //将路径和项⽬名进⾏拼接起来37 mView.setView(rView);38 mView.getModelMap().addAttribute("username", uname); //将控制器的数据传给页⾯39return mView;40 }41 }LoginController1 <%@ page language="java" contentType="text/html; charset=utf-8"2 pageEncoding="utf-8"%>3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd">4 <html>5 <head>6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">7 <title>Insert title here</title>8 </head>9 <body>10 <form action="${pageContext.request.contextPath }/login1.do"> <!--${pageContext.request.contextPath }动态获取路径 -->11账号:<input type="text" name="username" ><br>12密码:<input type="text" name="password" ><br>13 <input type="submit" value="登录"><br>14 </form>15 </body>16 </html>login.jsp1 <%@ page language="java" contentType="text/html; charset=utf-8"2 pageEncoding="utf-8"%>3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd">4 <html>5 <head>6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">7 <title>Insert title here</title>8 </head>9 <body>10 <h1>欢迎${ername }来访</h1>11 </body>12 </html>main.jsp。
Springmvc中的转发重定向和拦截器的示例

Springmvc中的转发重定向和拦截器的⽰例本⽂介绍了Springmvc中的转发重定向和拦截器的⽰例,分享给⼤家,具体如下:可变参数在设计⽅法时,使⽤数据类型... 来声明参数类型,例如:public static void function(int... numbers)在实现⽅法体时,可变参数是作为数组来处理public class Test{public static void main(String[] args){System.out.println(Test.sum(1,2,3));System.out.println(Test.sum(1,2,3,4,54));}public static int sum(int... numbers){int sum=0;for(int i=0;i<numbers.length;i++){sum+=numbers[i];}return sum;}}注意:每个⽅法中,最多只允许存在1个可变参数,并且,如果存在可变参数 ,那么必须是最后⼀个参数转发和重定向forward:默认的⽅式,但是也是可以使⽤ return "forward:login"返回的⼀定是⼀个 view ,经过视图解析器之后会转发到指定的视图redirect:重定向: return "redirect:login.do"返回的是⼀个Controller⽅法的路径,⽽不是⼀个view,这个不会经过视图解析器,⽽是直接跳转实例@RequestMapping(value="/handle_reg.do", method=RequestMethod.POST)public String handleReg(User user,ModelMap map){try {userService.reg(user);System.out.println("注册成功!");return "redirect:login.do"; //重定向到login.do这个控制⽅法,login.do对应的就是转发到login.jsp} catch (UsernameConflictException e) {System.out.println(e.getMessage());map.put("errorMessage", e.getMessage());return "error";}}@RequestMapping(value="login.do")public String handleLogin(){return "login";}拦截器基本概念1. 拦截器( interceptor )是springmvc中的⼀个组件,是运⾏在 DispatcherServlet 之后,运⾏在 Controller 之前的2. 拦截器可以决定对某些符合条件的进⾏拦截或者放⾏,所以,通常⽤于对⼀些具有相同运⾏条件的功能进⾏约束使⽤拦截器⾃定义拦截器类创建⼀个拦截类( DemoInterceptor ),实现 HandlerInterceptor 接⼝public class DemoInterceptorimplements HandlerInterceptor{/*** 处理器执⾏之前调⽤* @param request HttpServletRequest对象,可以获取请求参数等等* @param response HttpServletResponse对象* @param Handler 拦截器的Controller对象* @return 如果返回false,就会中断处理流程,不会处理后续的拦截器和Controller。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
1.练习接收页面参数值1.使用request2.使用@RequestParam注解3.使用实体对象2.练习向页面传出数据1.使用HttpServletRequest和session2.使用ModelAndView对象(内部为利用HttpServletRequest的Attribute传递数据到页面)3.使用ModelMap对象(内部为利用HttpServletRequest的Attribute传递数据到页面)4.使用@ModelAttribute注解(内部为利用HttpServletRequest的Attribute传递数据到页面)3.练习使用session1.在Controller方法参数上直接声明HttpSession即可使用4.练习重定向1.使用RedirectView2.使用redirect:package web;import java.util.HashMap;import java.util.Map;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import org.springframework.stereotype.Controller;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.servlet.ModelAndView;import org.springframework.web.servlet.view.RedirectView;import er;//非注解方式//public class HelloController implements Controller {//// public ModelAndView handleRequest(HttpServletRequest request, // HttpServletResponse response) throws Exception {// System.out.println("Hello, Controller.");// return new ModelAndView("jsp/hello");// }////}@Controller@RequestMapping("/demo")publicclass HelloController{private Integer age=22;@RequestMapping("hello.do")public ModelAndView hello(HttpServletRequest request,HttpServletResponse response) throws Exception{ returnnew ModelAndView("jsp/hello");}/*** 测试request接收参数*/@RequestMapping("test1.do")public ModelAndView test1(HttpServletRequest req){String userName = req.getParameter("userName");String password = req.getParameter("password");System.out.println(userName);System.out.println(password);returnnew ModelAndView("jsp/hello");}/*** 测试sping会自动将表单参数注入到方法参数* 最好每个形参前都添加@requestparameter* 通过反射只能得到方法参数类型不能等到方法参数名称没有加注解能成功获得为编译器自动添加*/@RequestMapping("test2.do")public ModelAndView test2(String userName,@RequestParam("password") String pwd){System.out.println(userName+","+pwd);returnnew ModelAndView("jsp/hello");}/*** 测试对象接收参数*/@RequestMapping("test3.do")public ModelAndView test3(User user){System.out.println(user);returnnew ModelAndView("jsp/hello");}/*** 使用ModelAndView传出参数内部 HttpServletRequest的Attribute 传递到jsp页面* ModelAndView(String viewName,Map data)data是处理结果*/@RequestMapping("test4.do")public ModelAndView test4(User user){Map<String, Object> data = new HashMap<String, Object>();data.put("user", user);returnnew ModelAndView("jsp/hello",data);}/*** 使用ModelMap传出参数内部HttpServletRequest的Attribute传递到jsp页面*/@RequestMapping("test5.do")public ModelAndView test5(User user,ModelMap modelMap){modelMap.put("user", user);returnnew ModelAndView("jsp/hello");}/*** 使用ModelAttribute 内部HttpServletRequest的Attribute传递到jsp页面* 在Contoller的参数部分或者bean属性方法上使用*/@RequestMapping("test6.do")public ModelAndView test6(@ModelAttribute("user")User user){ returnnew ModelAndView("jsp/hello");}@ModelAttribute("age")public Integer getAge(){return age;}/*** session存储可以使用HttpServletRequest的getSession方法访问 */@RequestMapping("test7.do")public ModelAndView test7(HttpServletRequest req){HttpSession session = req.getSession();session.setAttribute("salary", 6000.0);returnnew ModelAndView("jsp/hello");}//返回String 转发@RequestMapping("/test8.do")public String test8(User user, ModelMap model) {model.addAttribute("user", user);return "jsp/hello";}/*** 错误页面*/@RequestMapping("test9.do")public String test9(){return "error/error";}/***使用RedirectView重定向*/@RequestMapping("test10")public ModelAndView test10(User user){if(user.getUserName().equals("123")){returnnew ModelAndView("jsp/hello");//test10.do 转发}else{returnnew ModelAndView(new RedirectView("test9.do"));//test9.do?age=22 重定向}}/*** 使用redirect重定向*/@RequestMapping("test11")public String test11(User user){if(user.getUserName().equals("123")){ return "jsp/hello";}else{return "redirect:test9.do";}}}user实体package com.tarena.entity;import java.io.Serializable;publicclass User implements Serializable { private Integer id;private String userName;private String password;public Integer getId() {return id;}publicvoid setId(Integer id) {this.id = id;}public String getUserName() {return userName;}publicvoid setUserName(String userName) { erName = userName;}public String getPassword() {return password;}publicvoid setPassword(String password) { this.password = password;}}。