Java EE -------- use filters to enable automatic user logon, secure logon, and disable automatic logon.

Source: Internet
Author: User

Java EE -------- use filters to enable automatic user logon, secure logon, and disable automatic logon.

In our life, automatic login to an account is very common, so this function is implemented using filters.

This section describes how to automatically log on to and cancel Automatic Logon, and enable one-day Automatic Logon or n-day Automatic Logon. When the user's ip address is added to the blacklist, a warning page is directly returned using the filter.

The filter function is very powerful. We only need to add the servlet after the prepared foreground to implement this function.

Ps: This is just a demonstration. The database access section in it is simulated at will, mainly to highlight the function of automatic login.

Front-end code:

Whether the front-end code is successful or not is displayed on this page. Technology used: jstl tag application, session read value

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%@taglib uri="http://java.sun.com/jsp/jstl/core"  prefix="c"%>
Your password or user name is incorrect. This is the logon page Welcome, $ {sessionScope. user}. login successful Module 1 module 2 cancel Automatic Login

 

Servlet implementation code: Like the previous code, it is only responsible for interaction with the front-end: the technology used in it includes url encoding, values in cookies, sessions, page Jump (forwarding)
Public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String name = request. getParameter ("name"); String pwd = request. getParameter ("pwd"); String time = request. getParameter ("time"); if (name! = Null & pwd! = Null & name. equals (pwd) {// you can write it here. You should go to servvice --> dao to access the database. // assume that the logon is successful. we store the information in the session for a request. getSession (). setAttribute ("user", name); // compatible with Chinese characters. We need to encode name = URLEncoder. encode (name, "UTF-8"); pwd = URLEncoder. encode (pwd, "UTF-8"); Cookie c = new Cookie ("autologin", name + "," + pwd); // This value cannot be used, for security, we must know that encryption or secondary encryption is used. int _ time = 60*60*24 * Integer. valueOf (time); c. setMaxAge (_ time); response. addCookie (c); res Ponse. sendRedirect (request. getContextPath () + "/index. jsp "); // in the filter, the default setting is to intercept redirection, and forward is internal direct forwarding, but the filter is not easy to handle, but only needs to be in the web. configure in xml .} Else {request. getSession (). setAttribute ("error", "1"); response. sendRedirect (request. getContextPath () + "/index. jsp ");}}
So far, I have no idea about any technology. I am using the previous Code. Now it is the function of Filter.
Secure Login: We have used dynamic import for secure login to prevent users from logging on to the project without having to log on. you can enter the interface if you enter it at will. Dynamic import can achieve this function. However, it is better to use a filter. Generally, dofilter () is written in the filter. You only need to judge whether the session container is null. If it is null, this indicates that there is no logon. You can directly return to the logon interface. If it is not, the system will allow access.
Code submission:
Public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {HttpServletRequest req = (HttpServletRequest) request; incluresp = (response) response; String session = (String) req. getSession (). getAttribute ("user"); if (session = null) {System. out. println ("unusual Logon"); resp. sendRedirect (req. getContextPath () + "/index. jsp ");} else {System. out. println ("successfully logged on"); chain. doFilter (req, resp );}}

Character encoding:Character encoding problem. In the past, you had to manually enter the request in the servlet dopost. setCharacterEncoding ("UTF-8"); every servlet needs to be input, which is too troublesome. We use a filter to implement it; Code submission:
Public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {request. setCharacterEncoding (character); // encode response received by the client. setContentType ("text/html; charset = UTF-8"); // you can specify the output encoding chain. doFilter (request, response) ;}@ Overridepublic void init (FilterConfig config) throws ServletException {character = config. getInitParameter ("character"); // set aharacter to a global variable ,}
The above character is defined as a global variable and the initial value is configured in web. xml.
The web. xml code is presented as follows:
   
  
   character
    
  
   cn.hncu.Filter.CharacterFilter
    
    
   
    character
     
   
    UTF-8
     
    
 

Automatic Logon: Main Ideas: Automatic Logon requires you to determine that all values exist in the session. If yes, you have logged on. If no value exists, go to the local cookie to find the value. If yes, go to the database to match the value. If yes, add the session container value.
Code submission:
Public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {// Automatic Logon. You must set the values in the session. If yes, you have logged on, no, you need to access the data in the cookie. The data in the cookie // matches the data in the database. Yes, set the value of the session here. No, release HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; String session = (String) req. getSession (). getAttribute ("user" ); If (session = null) {// indicates that no Cookie cs [] = req. getCookies () has been logged on currently; if (cs! = Null) {for (Cookie c: cs) {if (c. getName (). equals ("autologin") {String value = c. getValue (); // This is encrypted, but we only use commas to connect. String [] strs = value. split (","); // In logserlvet, encoding is used first, and then comma-separated connections are used. here we need to reverse String name = URLDecoder. decode (strs [0], "UTF-8"); String pwd = URLDecoder. decode (strs [1], "UTF-8"); // get the name and pwd data to the background to access the database. Here we just write if (name. equals (pwd) {req. getSession (). setAttribute ("user", name); // set the parameter break ;}}} chain in the session. doFilter (req, resp); // you must release it ..}

The blacklist user is blacklisted, and logon is not allowed. The result code is displayed as follows:
Public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {HttpServletRequest req = (HttpServletRequest) request; incluresp = (response) response; String ip = req. getRemoteAddr (); // obtain the accessed ip address; System. out. println (ip + "IIPP"); if (set. contains (ip) {// System in the blacklist. out. println ("set"); resp. getWriter (). print ("You are in the blacklist .. return "); // The returned result is not acceptable because the index directly blocks} else {chain when requesting from the server. doFilter (req, resp );}}

The type returned by the blacklist is the best. I manually add the blacklist here. I should have read it from the database by writing a tool class, not only for query, but also for deletion and modification-blacklist. Code submission: Hashset is defined as a global variable. The set contains contain, which is highly efficient.
Public void init (FilterConfig arg0) throws ServletException {// The Blacklist list is retrieved from the database. Here is just a simple simulation of set. add ("192.132.0.12"); // This is a black IP, which is obtained from the background database. Set. add ("localhost"); set. add ("192.132.32.4"); set. add ("127.0.0.1 ");}


Cancel automatic login

 

When automatic logon is always considered insecure, we set that automatic logon is not performed.

Previously, we knew that automatic login relies on the technology stored in cookies, so here we only need to delete the cookies.

Because canceling automatic logon is a hyperlink, servlet is written.

Code submission:

 

Public void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {Cookie cc = new Cookie ("autologin", ""); // Method for deleting a cookie, create a connkie with the same name, and set setmaxage = 0; cc of the cookie. setMaxAge (0); cc. setPath (req. getContextPath (); resp. addCookie (cc); resp. sendRedirect (req. getContextPath () + "/index. jsp ");}

The above will be able to implement these simple answer functions.

For specific resources, I have uploaded and clicked to open the link. You are welcome to discuss and learn together.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.