4.SpringMVC请求转发forward和请求重定向redirect

package com.gzcgxt.erp;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/user")
public class UserController {

    /**
     * 请求转发
     * <p>
     * Title: forward
     * </p>
     * <p>
     * Description: 请求转发 地址栏地址不会发生改变,则可以共享数据信息
     * 原理:request.getRequestDispatcher("/list.html").forward(request, response);
     * </p>
     * 
     * @return
     */
    public String forward(Model m)
    {
        //前台则可以使用 ${integer}
        m.addAttribute(100);   
        return "forward:/list.html";
    }
    
    
    /**
     * 请求重定向
     * <p>Title: redirect</p>
     * <p>Description: 
     *         请求重定向,地址栏连接地址会发改变,则是两个不同的请求对象,所以无法共享请求数据信息
     *      原理:response.sendRedirect("/list.html");
     * </p>
     * @return
     */
    public String redirect()
    {
        return "redirect:/list.html";
    }
}

注:不管理请求转发还是重定向 都使用 / 来查找方法

 

 

解决SpringMVC 请求重定向无法共享数据问题

package com.gzcgxt.erp;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * 请求重定向共享数据信息
 * <p>Title: DataController</p>
 * <p>Description: </p>
 * <p>Company: www.baidu.com</p> 
 * @author    刘诗华 微信:15390725037
 * @date    2019-7-16下午3:50:38
 * @version 1.0
 */

@Controller
public class DataController {

    /**
     * 
     * <p>Title: 第一个方法</p>
     * <p>Description: </p>
     * @return
     */
    @RequestMapping("/one")
    public String one(RedirectAttributes ra)
    {
        //通过隐藏数据的方式进行传参
        ra.addFlashAttribute("name","刘诗华");
        return "redirect:/two";
    }
    
    @RequestMapping("/two")
    public String two(@ModelAttribute("name")String name)
    {
        System.out.println(name);//可以取出两个方法中共享数据
        return "";
    }
    
    
    @RequestMapping("/three")
    public String three(RedirectAttributes ra)
    {
        //能过url地址  ?name=刘诗华 显式传参的方式
        ra.addAttribute("name","刘诗华");
        return "redirect:/two";
    }

}

 

posted @ 2019-07-16 15:49  往事只能回味---  阅读(905)  评论(0)    收藏  举报