Spring MVC设置首页,403,404,500页面

一.设置首页

1.静态页面

设置静态页面相对简单,直接在项目的web.xml定义如下即可:

<web-app>
...
<welcome-file-list>
    <welcome-file>demo/pagefile.jsp</welcome-file>
</welcome-file-list>
...
</web-app>

这里的demo/pagefile.jsp指的就是项目根目录的page文件夹里面的pagefile.jsp
这样直接访问localhost:8080/YouProject/,即可访问到localhost:8080/YouProject/demo/pagefile.jsp

2.Spring MVC的控制器

有时候项目有这种需求,即访问项目时直接执行某个控制器,这样上面的方法就不起效果了,这时可以用一种变通的方式来实现

①web.xml页面如下配置

<web-app>
...
<welcome-file-list>
    <welcome-file>/</welcome-file>
</welcome-file-list>
...
</web-app>

②然后定义一个控制器

...
@Controller
//注意 这里不要定义@RequestMapping
public class RouteController(){
    ...
    @RequestMapping(value="/")
    public String indexPage(){
        //如果你的spring mvc配置文件中配置了跳转后缀则不需要加.jsp后缀
        //即直接return "demo/pagefile";
        return "demo/pagefile.jsp";
    }
...
}

这样,输入直接访问localhost:8080/YouProject/,即可访问到localhost:8080/YouProject/demo/pagefile.jsp,当然这个控制器怎么写取决于你 :-)

二.设置403,404,500页面

web.xml里如下配置:

<error-page>
    <error-code>403</error-code>
    <location>/common/403.jsp</location>
</error-page>
<error-page>
    <error-code>404</error-code>
    <location>/common/404.jsp</location>
</error-page>
<error-page>
    <error-code>500</error-code>
    <location>/common/500.jsp</location>
</error-page>

举个栗子: 如果出现404错误,默认的错误页面变成项目根目录下common/404.jsp,这样就可以自己定义404页面了.
不过500错误页面最好在生产模式下这样设置,debug环境调代码还得看错误提示嘛

猜你喜欢

转载自blog.csdn.net/Amayadream/article/details/50098767
今日推荐