您的位置:首页 > 其它

Servlet------(声明式)异常处理

2016-03-30 16:22 441 查看
Test.java

其他方法不变,重写

protected void service()方法


public void init(ServletConfig config) throws ServletException {
// Put your code here
super.init(config);
}

@Override
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
// TODO Auto-generated method stub
//super.service(arg0, arg1);
String method=req.getMethod();
if(method.equals("POST")){
doPost(req,res);
}
else if(method.equals("GET")){
doGet(req,res);
}

res.setContentType("text/html;charset=gb2312");
PrintWriter out=res.getWriter();

Integer status_code=(Integer) req.getAttribute("javax.servlet.error.status_code");

out.print("<html><head><title>错误处理页面</title></head>");
out.print("<body>");

switch(status_code){
case 401:
break;
case 404:
out.print("<h2>HTTP转态代码: "+status_code+"</h2><br>");
out.print("您正在搜索的页面已删除<>br");
break;
default:
break;
}
out.print("</body>");
out.print("</html>");
out.close();
}


web.xml

其他代码不变,加入下面代码

<web-app>
........

<error-page>
<error-code>401</error-code>
<location>/errorPage.jsp</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/errorPage.jsp</location>
</error-page>
</web-app>


errorPage.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'welcome.jsp' starting page</title>
</head>

<body>
401,405错误处理页面
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: