springMvc请求路径解析

别等时光非礼了梦想. 提交于 2019-12-05 02:27:50

一开始我的代码是:

//index.jsp<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>Hello World!</h2>
<%--href="some"时是到发布的项目目录下找:访问网址是http://localhost/springmvc/some
href="/some"是直接到服务器下找:访问网址是http://localhost/some--%>
    <a href="some.do">请求</a>

</body>
</html>

web.xml内部分

  <!--中央调度器-->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <!--写的那个servlet-->
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
     <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:springmvc.xml</param-value>
      </init-param>
  </servlet>
<servlet-mapping>
  <servlet-name>springmvc</servlet-name>
  <!--servlet的映射路径 :是jsp通过这个路径请求后,再通过springmvc找servlet-class是谁-->
    <!--写”/“会把所有的静态请求都交给中央调度器,所以如果ggg.html也会给handler,会发生找不到404的错误,不建议使用-->
    <!--如果写”/*“的话,会把所有的请求都交给中央调度器,包括动态index.jsp,所以不能使用-->
    <!--用*.do或者*.go可以解决这个问题:1.让提交请求的路径后面加上.do 例如:<a href="some.do">
    2.在注册的时候也写上"/请求路径.do"
    3.<url-pattern>*.do</url-pattern>
    即所有后缀为.do的请求都可以被中央调度器接收了,不加就不用接收了-->
    <!---->
  <url-pattern>*.do</url-pattern>
</servlet-mapping>

springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--注册处理器:bean的id必须以"/"开头,因为id是一个路径-->
<bean id="/some.do" class="com.abc.handler.SomeHandler"/><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">     <property name="prefix" value="/WEB-INF/jsp/"/>     <property name="suffix" value=".jsp"/>
    </bean></beans>
//someHandler.java   public ModelAndView handleRequest(javax.servlet.http.HttpServletRequest httpServletRequest, javax.servlet.http.HttpServletResponse httpServletResponse) throws Exception {
        ModelAndView mv = new ModelAndView();
        //setViewName:响应视图叫什么名字,这个名字应该写相对于webapp路径下的名称(发布到服务器时项目的根目录)
        mv.setViewName("welcome");
        mv.addObject("message","helloSpringMvc");

        return mv;

    }
}

现在修改的是index.jsp里的<a href="some.do">,修改为<a href="/some.do">,发现访问网址是http://localhost/some,

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!