SpringMVC首頁訪問方式
Spring MVC首頁訪問的設(shè)置:
- tomcat中配置首頁
- spring mvc配置首頁
- DispatcherServlet配置的servlet映射
tomcat方式
- 配置tomcat的web.xml
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
- 添加項(xiàng)目到tomcat
- 啟動(dòng)tomcat
- 訪問項(xiàng)目
# http://${tomcat-ip}:${tomcat-port}/${project-name}
http://localhost/dintern
服務(wù)器在項(xiàng)目WebApp根目錄(例如:maven項(xiàng)目的webapp)尋找index.html/index.htm/index.jsp工窍,如果找到,就跳轉(zhuǎn)到這些頁面帝雇,如果沒有找到席函,就去項(xiàng)目中找首頁設(shè)置
spring mvc項(xiàng)目配置首頁
- 配置springmvc的web.xml,同tomcat
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
服務(wù)器找不到tomcat中配置的首頁误墓,會(huì)尋找項(xiàng)目中配置的首頁
DispatcherServlet配置的servlet映射
- web.xml配置DispatcherServlet
<servlet>
<servlet-name>springServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
- Controller設(shè)置首頁視圖
@RequestMapping(value="/", method=RequestMethod.GET)
public String index(){
return "index";
}
服務(wù)器會(huì)結(jié)合視圖配置尋找首頁弥锄,視圖配置如下:
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
服務(wù)器找到的首頁是:/WEB-INF/views/index.jsp
Notice
spring mvc項(xiàng)目的DispatcherServlet的地址映射/和/*的區(qū)別
- /表示攔截所有的路徑型url瑟曲,不會(huì)匹配到模式為.jsp這樣后綴型的url
- /* 表示攔截所有的路徑型和后綴型的url(包括/login, *.jsp, .js,.html等)
- Reference:(https://stackoverflow.com/questions/4140448/difference-between-and-in-servlet-mapping-url-pattern)
spring mvc首頁如何由controller處理
本文以spring mvc項(xiàng)目配置了<url-pattern>/</url-pattern>為例澡刹,說明如何讓首頁交給controller處理呢,下面提供兩種方案。
定義歡迎頁
- 在tomcat或者項(xiàng)目的web.xml添加首頁配置
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
- 在index.jsp中添加以下代碼叼丑,就會(huì)跳到指定的controller去處理
<%
response.sendRedirect(request.getContextPath()+"/login");
%>
項(xiàng)目中配置的路徑是/
前提條件是:tomcat和項(xiàng)目中沒有配置首頁资铡,或者配置的首頁不存在
- web.xml
<servlet>
<servlet-name>springServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
- controller
@RequestMapping(value="/", method=RequestMethod.GET)
public String index(){
return "login";
}