I use code to teach you: Filter for login interception
1 Introduction
When you first started to learn Java Web, I believe that the first person you will come across must be JSP + Servlet to develop web applications. Here we talk about the use of Filter in Servlet and the corresponding actual development scenarios.
2.What is Filter?
2.1 The official definition of Filter
A filter (Filter) is an object that performs filtering tasks on resource (servlet or static content) requests or resource responses, or on both. ——Excerpt from the JavaEE6 documentation
2.2 View the Filter document
Java EE6 documentation: https://tool.oschina.net/apidocs/apidoc?api=javaEE6
3.Filter execution flowchart solution
4. Filter in actual development scenarios
4.1 Unicode processing
4.1.1 Business scenario
In our development of Java Web, form forms often need to be filled in Chinese and passed to the server for storage. Therefore, we need to deal with the garbled problem.
If the registration form has Chinese parameters, the registered servlet needs to deal with the Chinese garbled problem; if the login form has Chinese parameters, the servlet that handles the login needs to deal with the Chinese garbled problem; if the two forms have Chinese, it needs to be processed twice, then 10 form forms, 100 form forms? ? ?
Therefore, it is very sour and refreshing to handle all the Chinese garbled problems requested by Filter. Below we demonstrate with code:
4.1.2 Project structure
PS: At this time we have achieved such an effect: write two forms, login.jsp and register.jsp, fill in Chinese to submit the form. Use filter to uniformly handle the Chinese garbled problem of multiple forms.
4.1.3 Servlet processing form
RegisterServlet:
@WebServlet(name = "RegisterServlet",urlPatterns = "/register.do")
public class RegisterServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//接收参数
String username = request.getParameter("username");
String pwd = request.getParameter("pwd");
System.out.println("username:"+username+",pwd:"+pwd);
request.getRequestDispatcher("login.jsp").forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
LoginServlet:
@WebServlet(name = "LoginServlet",urlPatterns = "/login.do")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String pwd = request.getParameter("pwd");
System.out.println("username:"+username+",pwd:"+pwd);
request.getRequestDispatcher("index.jsp").forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
4.1.4 JSP page for registration and login
Login form:
Registration form:
4.1.5 Use Filter to process all requested Chinese garbled characters
@WebFilter(filterName = "CommonFilter",urlPatterns = "*.do")
public class CommonFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
System.out.println("--------公共拦截器--start----------");
//当每个表单中都有中文提交时,此时Servlet都需要进行乱码处理
req.setCharacterEncoding("UTF-8");
chain.doFilter(req, resp);//放行
System.out.println("--------公共拦截器--end----------");
}
public void init(FilterConfig config) throws ServletException {
}
}
4.1.6 Demonstration effect
After filling in Chinese on the login page or registration page, the Servlet can receive Chinese even without Chinese garbled processing. Because Filter helped us deal with Chinese garbled characters
as shown below:
4.2 User login interceptor
4.2.1 Business scenario
In actual development, there are many requests that require users to log in before they can access them. For example: when we log in to Taobao, you will be prompted to log in when you check the shopping cart or check the order list. Let me tell you the code below, how to achieve it? ? ?
4.2.2 Project structure
PS: At this time, we have achieved an effect. When the user jumps to the "Order List" in index.jsp, the filter is intercepted to determine whether the user is logged in, and if not, jump to the login page for the user to log in.
4.2.2 On the basis of the previous example, make the following preparations:
Order list: Order.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>订单列表</title>
</head>
<body>
<h1>订单列表</h1>
</body>
</html>
Homepage: index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>主页</title>
</head>
<body>
<h1>welcome to index.jsp!</h1>
<a href="login.jsp">登录</a>
<a href="register.jsp">注册</a>
<a href="${pageContext.request.contextPath}/order/showOrder.do">查看订单列表</a>
</body>
</html>
OrderServlet:
@WebServlet(name = "OrderServlet",urlPatterns = "/order/showOrder.do")
public class OrderServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("------------展示订单列表-------------");
request.getRequestDispatcher("index.jsp").forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
4.2.3 Writing a login interceptor
@WebFilter(filterName = "LoginFilter",urlPatterns = "/order/*")
public class LoginFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
System.out.println("--------登录拦截器--start----------");
//涉及到4个作用域
HttpServletRequest request = (HttpServletRequest)req;
HttpSession session = request.getSession();
String userName = (String) session.getAttribute("session_user");
if(userName!=null&!"".equals(userName)){
//说明用户登录了
chain.doFilter(req, resp);//放行
}else{
//说明用户未登录
//跳转到登陆页面
request.setAttribute("tip","请先登录!");
request.getRequestDispatcher("/login.jsp").forward(request,resp);
}
System.out.println("--------登录拦截器--end----------");
}
public void init(FilterConfig config) throws ServletException {
}
}
4.2.4 Demonstration effect
1) Directly access "View Order List" on the index.jsp page
2) Jump to the login page and prompt because the user is not logged in
3) View the console print data, observe and think about the return process between multiple interceptors.
4.3 Application in other scenarios
1) Authentication filter
2) Log and audit filter
3) Image conversion filter
4) Data compression filter
5) Encrypted filter
This blog post uses two examples to familiarize yourself with the role of Filter in the actual development scenario. After you are familiar with these two examples, the application of other business scenarios will be implemented later.