org.springframework.web.servlet.DispatcherServlet
DispatcherServlet負責將客戶的請求分派給對應於請求的控制物件
DispatcherServlet需要設定在web.xml中
以下是web.xml設定
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Website</display-name> <servlet> <servlet-name>Website</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/mvc-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Website</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/WEB-INF/jsp/login.jsp</welcome-file> </welcome-file-list> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> </web-app>
其中init-param有個屬性contextConfigLocation是用來設定讀取的xml放哪個位置
預設是/WEB-INF/(servlet-name)-servlet.xml
這邊設定是/WEB-INF/mvc-config.xml
servlet-mapping mapping中設定了spring管理的網頁路徑
此範例設定將所有路徑為.do的交給spring mvc管理
以下為mvc-config.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" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"> <aop:aspectj-autoproxy /> <context:component-scan base-package="website" /> <!-- viewResolver setup --> <context:component-scan base-package="website.controller" /> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
ViewResolver是管理view的工具
prefix(此範例值為/WEB-INF/jsp/)表示的是view存放的路徑
suffix(此範例值為.jsp)表示的是檔案的副檔名
若是你的java程式有這段程式碼
@RequestMapping("/test.do") public ModelAndView test(HttpServletRequest req, HttpServletResponse resp) throws Exception { return new ModelAndView("demo"); }
那麼/test.do這隻程式就會將網頁導向/WEB-INF/jsp/demo.jap
(檔名式依照ModelAndView內的參數決定)
沒有留言:
張貼留言