一開始我的代碼是:
//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,待續。