SpringMVC默认访问首页配置及web.xml配置

本文记录了在SpringMVC中如何配置web.xml,以便访问首页时能直接跳转到controller处理,而不显示index.htm等具体后缀。通过避免在<welcome-file>标签内使用后缀名,或者直接使用/作为默认路径,可以实现无后缀的首页访问。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以前在使用SpringMVC时一直没注意到在web.xml中默认首页直接转到controller的问题,这两天在进行配置时才发现没我想的那么简单,不过其实也不难,查的各种资料因为不合适傻乎乎的绕了点弯路,但也算是解决了,所以记录下来,留个备忘。

之前访问主页地址为:http://xxxxxxx/xxxx/index.htm 但由于要求,需要去掉index.htm,直接访问地址就转到主页(index.htm是配置的controller地址)

<!--web.xml默认配置-->
<welcome-file-list>  
   <welcome-file>/index.html</welcome-file>  
</welcome-file-list>
//controller配置
@RequestMapping({"/index.htm"})
public ModelAndView  indexCore(HttpServletRequest request, HttpServletResponse response){
    ModelAndView mv = new JModelAndView("/core/index.html", request, response);
    return mv;  
}

开始想着这不简单嘛,,直接把web.xml的默认主页写为controller访问地址不就行了,所以就改成了这样:

<!--web.xml默认配置-->
<welcome-file-list>
   <welcome-file>/index.htm</welcome-file>  
</welcome-file-list>

访问后果然报了404。o(╯□╰)o
查资料才知道<welcome-file>标签内不能写有后缀名!!!不然就会当做普通的静态页面文件去访问,所以就不会找到相应的controller。(谁把controller访问地址写成/index.htm的,粗来我不打死你╭∩╮(︶︿︶)╭∩╮)

所以修改如下:

<!--web.xml默认配置-->
<welcome-file-list>  
   <welcome-file>index</welcome-file>  
</welcome-file-list>

<servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/index</url-pattern>
</servlet-mapping>
//controller配置
@RequestMapping({"/index"})
public ModelAndView  indexCore(HttpServletRequest request, HttpServletResponse response){
    ModelAndView mv = new JModelAndView("/core/index.html", request, response);
    return mv;  
}

然后直接输入http://xxxxxxx/xxxx 访问成功。

不过还有一种简单直接粗暴的:

<!--web.xml默认配置-->
<welcome-file-list>  
   <welcome-file>/</welcome-file>  
</welcome-file-list>
//controller配置
@RequestMapping({"/"})
public ModelAndView  indexCore(HttpServletRequest request, HttpServletResponse response){
    ModelAndView mv = new JModelAndView("/core/index.html", request, response);
    return mv;  
}

直接都使用\,这样也能达到目的。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值