SpringMVC默认访问首页配置及web.xml配置
以前在使用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;
}
直接都使用,这样也能达到目的。
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
- 上一篇:没有了
- 下一篇:没有了