SpringMVC:结果跳转方式(重定向,转发)

一,利用视图解析器(InternalResourceViewResolver),实现页面的跳转、

  具体实现方式:

    设置ModelAndView对象,根据View的名称,和是图解析器的操作跳到指定页面

    页面:(视图解析器,配置)前缀+ViewName+(视图解析器,配置)后缀

    <!--视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          id="internalResourceViewResolver">

        <!--前缀-->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!--后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>

    

    对应的控制类(mv)

@Controller
public class RestfulController {

    @GetMapping("hello/{a}/{b}")
    public String restful(@PathVariable int a,@PathVariable int b, Model model){
        System.out.println("成功了");
        int res = a+b;
        model.addAttribute("msg","结果为:"+res);
        return "hello";

    }

注意:利用视图解析器可以实现转发,但重定向不必使用,直接利用重定向指明路径就可以实现

例子:

@Controller
public class HelloController {

    //请求映射器
    @RequestMapping("/h1")
    public String hello(Model model){
        //封装数据
        model.addAttribute("msg","hello,springmvc");

        return "redirect:index.jsp";//页面跳转


    }

}

注意:重定向是不能走WEB-INFO这个文件夹的,

   原因:WEB-INFO文件夹是应用的安全目录,是不允许客户的直接的访问的,只有服务端才能访问,

      通过服务端的转发,客户端才能间接的访问里面的页面(jsp,html)

原文地址:https://www.cnblogs.com/CL-King/p/13947614.html