4)Filter与Session配合的简单过渡例子
马克-to-win:因为下一个登录例子太难,我先给出一个过度的例子,便于大家理解下一个例子。这里也有个轶事,当我在做下一个登 录的例子时,发现一个非常隐晦的bug。那就是,我本应写成:response.sendRedirect("http: //localhost:8080/ServletHello/home.jsp")。但我实际写成了:response.sendRedirect ("http://localhost:8080//ServletHello/home.jsp");多写了一个/,跳转没出现问题。严重的问题就是 filter当中怎么也取不出session了。我当时还以为是tomcat出现问题了或是机器出现毛病。这个Bug的隐晦之处是,url写错后,不是跳 转出现毛病,而是Filter当中session取不出来。我曾经一度怀疑,是sun公司整个filter机制设计有问题?后来经过仔细思考,我的结论 是,当url只是简单错误时(比如home.jsp写成home1.jsp),会跳转失败。马克-to-win:但如果只是机器名后多加了一个/,sun 公司会认为你要跳转去别的web应用,于是就把session清空了。但是filter不管是一个斜杠还是两个斜杠,还是会照常过滤。跳转去别的web应 用,所以取不到session。(请参考我的Session部分:跨应用取session)看来,sun公司的filter大的方面设计没问题,只是还是 有一点点bug。应该在下一个版本把这个问题解决一下。(应该两个斜杠就不过滤了)
例 1.2.4
package com;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
public class MarkToWinFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
response.setCharacterEncoding("GBK");
HttpServletRequest hsr=(HttpServletRequest)request;
HttpSession hs=hsr.getSession();
String me=(String)hs.getAttribute("me");
System.out.println("me in filter is " me);
PrintWriter out = response.getWriter();
out.println("之前 filterChain.doFilter");
System.out.println("之前 filterChain.doFilter");
chain.doFilter(request, response);
System.out.println("之后 filterChain.doFilter");
out.println("之后 filterChain.doFilter");
me=(String)hs.getAttribute("me");
System.out.println("me in filter is " me);
}
public void init(FilterConfig fConfig) throws ServletException {
}
}
package com;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class ServletHello1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("GBK");
HttpSession hs=request.getSession();
hs.setAttribute("me", "马克-to-win");
System.out.println("in servlet");
response.sendRedirect("http://localhost:8080/ServletHello/home.jsp");
}
更多请看:https://blog.csdn.net/qq_44638460/article/details/104079545