设置默认访问页面的三种方式
(1)在web.xml配置文件中的的<welcome-file-list>标签设置(不需要从后台获取数据时)
在welcome-file标签中写默认页面的路径。
若在welcome-file没有找到,则服务器会默认调用:index.html、index.htm、index.jsp(这些页面默认在WEB-INF路径下去找)。若都没有找到,则报404错误。三个页面的优先级依次:index.html、index.htm、index.jsp
<welcome-file-list>
<welcome-file>jsp/index.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
(2)使用springmvc-servlet.xml配置文件中的标签:
<mvc:view-controller path="/" view-name="index"/>
或者
<mvc:view-controller path="" view-name="index"/>
这种方法不需要在后台写controller。
(3)如果首页需要从后台获取数据时:在上边两个配置文件中不配置以上信息。直接写一个专门用于访问首页的controller:
package com.ssm.web.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller("indexController")
public class IndexController {
@RequestMapping("/") //或者为空("")
public String homePage(Model model) throws Exception {
model.addAttribute("key", "value"); //在页面上可以获得key的值 通过${key}
System.out.println("test");
return "index";
}
}
注:以上后两种方法要在springmvc-servlet.xml中配置视图解析器
<context:component-scan base-package="com.briup"/>
<context:annotation-config/>
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 让视图支持jstl标签库 注意 1.项目中要导入jstl1-1.2.jar -->
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!-- 后缀 -->
<property name="suffix" value=".jsp"/>
<property name="order" value="0"></property> <!--优先级-->
<property name="contentType" value="text/html;charset=UTF-8"></property>
</bean>
这样就可以直接在浏览器地址中输入:localhost:8080/AppName访问了。