SpringMVC跳转和URL相关问题

image.png

搞明白了url相对路径,根路径的问题,跳转的时候url到底该怎么写就容易理解和记忆了。

url路径的问题

1. 当前路径:

比如我现在地址栏是http://localhost:8080/SpringMVC/index.jsp

那么当前路径就是http://localhost:8080/SpringMVC,即去掉原始的最后一个路由后,剩下的路径。

如何使用它?有这么个约定:

直接写路径或者用./会把当前路径和它拼起来,形成真正的路径。

比如:<a href="hello/testServletAPI">test</a>

或者:<a href="./hello/testServletAPI">test</a>

最后拼出来都是http://localhost:8080/SpringMVC/hello/testServletAPI

而你上面写那两个超链接里的路径,叫做相对路径./是当前目录,../就是再向上一级。

2. 根路径:

在做不同请求时,根路径也不一样。

  • 服务器转发时:根路径为主机名/项目名,如http://localhost:8080/SpringMVC
  • 页面请求或者重定向时:根路径为主机名,如http://localhost:8080

如何使用根路径?

/hello即表示根路径+hello,比如

<a href="/hello/testServletAPI">test</a>,访问的是http://localhost:8080/hello/testServletAPI

跳转页面方式

1. 会经过视图解析器的跳转

直接返回string的;

@RequestMapping(path = "/testHello")
public String sayHello(){
    return "success";
}

返回ModelAndView的;

@RequestMapping("/testMav")
public ModelAndView testMav(){
    return new ModelAndView("success");
}

如果配置了视图解析器:

<!--        配置视图解析器-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/pages/"></property>
    <property name="suffix" value=".jsp"></property>
</bean>

那么会对success加上前缀和后缀。并且跳转方式是转发。

2. 不经过视图解析器的跳转

首先明确两个事啊,转发是发生在服务端的,因此你转发可以转发到服务器的内部目录下,就是WEB-INF下,去访问它目录下的页面。但是重定向只能访问webapp下除WEB-INF的路径。

image-20200208181726489.png

2.1 ServletAPI跳转

先把request和response拿进来。

@RequestMapping("/testServletAPI")
public void testServletAPI(HttpServletRequest request,HttpServletResponse response){

}

服务器内部转发的根路径是主机名/项目名,重定向的根路径是主机名。因此两者的url不太一样。

同样访问webapp下的newPage.jsp,重定向需要自己手动把项目名加上。

@RequestMapping("/testServletAPI")
public void testServletAPI(HttpServletRequest request,HttpServletResponse response) throws Exception {
    //1. 转发
    request.getRequestDispatcher("/newPage.jsp").forward(request,response);
    
    //2. 重定向
    response.sendRedirect(request.getContextPath()+"/newPage.jsp");
}

2.2 url的关键字跳转

同样访问webapp下的newPage.jsp:

<h1>testKeyword</h1>
<a href="hello/testKeyword">testKeyword</a>

@RequestMapping("/testKeyword")
    public String testKeyword(){
    //转发
//        return "forward:/newPage.jsp";

    //重定向
        return "redirect:../newPage.jsp";
    }

重定向一般用相对路径,因为省去自己写项目名。

此处../是因为当前路径是主机/项目名/hello,所以要再向上一级目录。形成主机/项目名/newPage.jsp

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • hello springmvc 什么是Spring MVC?Spring MVC 为展现层提供的基于 MVC 设计...
    piziyang12138阅读 419评论 0 0
  • 配置文件web.xml(WEB-INF下) 注意: classpath:springmvc.xml 用于配置sp...
    数据萌新阅读 146评论 0 0
  • 什么是Spring MVC?Spring MVC 为展现层提供的基于 MVC 设计理念的优秀的Web 框架,是目前...
    伍陆柒_阅读 673评论 0 0
  • hello springmvc 什么是Spring MVC?Spring MVC 为展现层提供的基于 MVC 设计...
    极课编程阅读 505评论 0 7
  • hello springmvc什么是Spring MVC?Spring MVC 为展现层提供的基于 MVC 设计理...
    G_慧慧阅读 275评论 0 0

友情链接更多精彩内容