请问一下在java中自定义异常拦截器(不要使用其他框架,如spring),怎么拦截?
展开全部
public class MyException extends Exception{
public MyExceprion(){
System.out.println("自定义异常");
}
}
try catch(MyException e){
}
当然 你也可以定义一个拦截器放在web.xml
那你就要继续实现 filter 接口了 继承Exception 实现 Filter 接口 那不就完了
implements Filter
public class CharFilter implements Filter {
private String encode;
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain fc) throws IOException, ServletException {
HttpServletRequest request=(HttpServletRequest)req;
HttpServletResponse response=(HttpServletResponse)resp;
request.setCharacterEncoding(this.encode);
response.setCharacterEncoding(this.encode);
fc.doFilter(request,response);
}
public void init(FilterConfig arg0) throws ServletException {
this.encode=arg0.getInitParameter("encode");//��xml��init-param
}
}
web.xml中 配置拦截器
<filter>
<filter-name>CharFilter</filter-name>
<filter-class>neusoft.team101.dms.common.filter.CharFilter</filter-class>
<init-param>
<param-name>encode</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
public MyExceprion(){
System.out.println("自定义异常");
}
}
try catch(MyException e){
}
当然 你也可以定义一个拦截器放在web.xml
那你就要继续实现 filter 接口了 继承Exception 实现 Filter 接口 那不就完了
implements Filter
public class CharFilter implements Filter {
private String encode;
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain fc) throws IOException, ServletException {
HttpServletRequest request=(HttpServletRequest)req;
HttpServletResponse response=(HttpServletResponse)resp;
request.setCharacterEncoding(this.encode);
response.setCharacterEncoding(this.encode);
fc.doFilter(request,response);
}
public void init(FilterConfig arg0) throws ServletException {
this.encode=arg0.getInitParameter("encode");//��xml��init-param
}
}
web.xml中 配置拦截器
<filter>
<filter-name>CharFilter</filter-name>
<filter-class>neusoft.team101.dms.common.filter.CharFilter</filter-class>
<init-param>
<param-name>encode</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
更多追问追答
追问
请问一下,我不做web项目,就建一个简单的java项目,没有web.xml 文件,又该怎么实现呢?
谢谢!
追答
既然你要用拦截器 那就只能在你的java 文件里调用实例这个拦截器异常类了
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询