Filter: implement the function module of automatic website login

Source: Internet
Author: User

Analysis of automatic website login operations. I use the CSDN user login function as an example to describe how,

1. Enter the csdn logon interface address: The CSDN User Logon interface is as follows:


2. Enter the correct user name and password, and check the next Automatic Logon function.

3. Click "Log On". If you log on successfully, the logon page is displayed.


4. If you click the CSDN User Logon interface again to see what the effect will be, you will find that the logon interface cannot be opened and will jump directly to the interface such:

 

5. You can see that the automatic login function module has been completed.



Based on the above analysis, I combined the Filter and Cookie in Java Web to complete a function module for automatic website login.

1. Write the logon Interface

<% @ Page language = "java" import = "java. util. *" pageEncoding = "UTF-8" %> <! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN"> 

The effect is as follows:

2. servlet class processed on the logon interface.

Package www.csdn.net. day56.servlet; import java. io. IOException; import java. security. messageDigest; import java. security. noSuchAlgorithmException; import javax. servlet. servletException; import javax. servlet. http. cookie; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import sun. misc. BASE64Encoder; import com. sun. mail. util. BAS E64EncoderStream; import www.csdn.net. day56.bean. admin; import www.csdn.net. day56.dao. adminDao; import www.csdn.net. day56.dao. impl. adminDaoImpl; import www.csdn.net. day56.service. adminService; import www.csdn.net. day56.service. impl. adminServiceImpl; public class AdminServlet extends HttpServlet {private AdminService adminService = new AdminServiceImpl (); private long expires = 24*60*60; // 1 day public v Oid doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String method = request. getMethod (); System. out. println ("request method:" + method); // obtain the identifier String response = request in the request parameter. getParameter ("parameter"); if ("login ". equals (LOGIN) {// process login // obtain the username and password String name = request. getParameter ("name"); String pass = request. getParameter ("pass"); // get the flag for Automatic Logon identifier String mark = Request. getParameter ("mark"); // verify that the user name and password are correct Admin entity = adminService. checkLogin (name, pass); if (entity! = Null) {// determines if ("mark ". equals (mark) {// get the default days remembered String day = request. getParameter ("day"); // converts it to a valid time expires = Integer. valueOf (day) * expires; // declare cookieCookie autoCookie = null; // obtain all cookieCookie cookies [] = request. getCookies (); // traverse cookiefor (Cookie cookie: cookies) {// determine whether an automatic logon record if ("autologin") exists ". equals (cookie. getName () {autoCookie = cookie; // value assignment // when the cookie exists, I need to reset the value long time = (System. currentTimeMillis () + expires * 1000); // The value of cookie concatenation (which can be designed based on your own ideas) String newValue = name + ":" + time + ": "+ md5Value (name +": "+ pass +": "+ time); // set the value of autoCookie. setValue (newValue);} else {// creation does not exist // name + ":" + time + ":" + md5 (name: pass: time) long time = System. currentTimeMillis () + expires * 1000; // The value of cookie concatenation (which can be designed based on your own ideas) String cookieValue = name + ":" + time + ": "+ md5Value (name +": "+ pass +": "+ time); // create cookieautoCookie = new Cookie (" autologin ", cookieValue);} autoCookie. setMaxAge (int) expires); autoCookie. setPath ("/day56"); // Add cookieresponse. addCookie (autoCookie);} // admin saves it to sessionrequest. getSession (). setAttribute ("admin", entity); // operation request after successful login. getRequestDispatcher (". /SC. jsp "). forward (request, response);} else {request. setAttribute ("msg", "incorrect user name or password"); request. getRequestDispatcher (". /index. jsp "). forward (request, response) ;}} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this. doGet (request, response);}/*** md5 encryption processing * @ param value * @ return */public String md5Value (String value) {try {MessageDigest digest = MessageDigest. getInstance ("md5"); byte result [] = digest. digest (value. getBytes (); BASE64Encoder encoder = new BASE64Encoder (); return encoder. encode (result);} catch (NoSuchAlgorithmException e) {// TODO Auto-generated catch blocke. printStackTrace ();} return "";}}

3. The code for automatically completing the logon filter is as follows:

Package www.csdn.net. day56.filter; import java. io. IOException; import java. security. messageDigest; import java. security. noSuchAlgorithmException; 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. cookie; import javax. servlet. Http. httpServletRequest; import javax. servlet. http. httpServletResponse; import sun. misc. BASE64Encoder; import www.csdn.net. day56.bean. admin; import www.csdn.net. day56.service. adminService; import www.csdn.net. day56.service. impl. adminServiceImpl; public class AutoLoginFilter implements Filter {@ Overridepublic void doFilter (ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, Se RvletException {// styling object HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; // 1. first, check whether the sesion contains adminObject object = request. getSession (). getAttribute ("admin"); // if the session contains the user if (object! = Null) {// jump to the successful login interface request. getRequestDispatcher (". /SC. jsp "). forward (request, response); return;}/* --------------------------- The following is the processing when the session does not contain admin information ----------------------------- * // 2. determine whether the cookie contains a cookie object with the autologin identifier // declare cookieCookie autoCookie = null; // obtain all cookieCookie cookies [] = request. getCookies (); // if there is no cookie information, continue to execute login. do, jump to login. jsp page if (cookies! = Null) {// If yes, it traverses cookiefor (Cookie cookie: cookies) {// It determines whether the cookie contains cookieif ("autologin") with the autologin identifier ". equals (cookie. getName () {autoCookie = cookie; // assign a value to the Temporary Variable autoCookie if any} // 3. determine whether autoCookie is equal to nullif (autoCookie = null) {// if it is equal to null, continue to execute login. jsp page chain. doFilter (request, response); return;} // 3. if autoCookie is not null, determine the cookie value // obtain the cookie value String value = autoCookie. getValue (); // The cookie shard value S. Tring temp [] = value. split (":"); System. out. println (temp. length); // determine whether the length is equal to the length of your stitching if (temp. length! = 3) {// if it is not 3, continue to execute login. jsp page chain. doFilter (request, response); return;} // obtain each cookie split value String name = temp [0]; // username String time = temp [1]; // obtain the validity period String service_md5Value = temp [2]; // obtain the encrypted md5 character // 4. determine whether the cookie is invalid if (Long. valueOf (time) <= System. currentTimeMillis () {// if it is invalid, continue to execute login. jsp page chain. doFilter (request, response); return;} // 5. if the cookie does not expire, query the user information AdminService adminService = new based on the user name. AdminServiceImpl (); // query the user information Admin entity = adminService. checkLogin (name); System. out. println (entity + "0000"); // determine whether the user is nullif (entity = null) {// if the user is not queried, continue to execute login. jsp page chain. doFilter (request, response); return;} // Concatenates the md5 encrypted String md5Temp = entity based on the server concatenation character. getName () + ":" + entity. getPass () + ":" + time; // checks whether the characters encrypted with md5 are equal to those encrypted on the server if (! (Md5Value (md5Temp ). equals (service_md5Value) {// if not equal, continue to execute login. jsp page chain. doFilter (request, response); return;} // if all results meet the cookie value judgment, the logon interface is displayed. request. getSession (). setAttribute ("admin", entity); request. getRequestDispatcher (". /SC. jsp "). forward (request, response);} else {// when no cookie information is available, continue login. jsp page chain. doFilter (request, response); return ;}// md5 encrypted String public String md5Value (String value) {try {MessageDigest digest = MessageDigest. getInstance ("md5"); byte result [] = digest. digest (value. getBytes (); BASE64Encoder encoder = new BASE64Encoder (); return encoder. encode (result);} catch (NoSuchAlgorithmException e) {e. printStackTrace ();} return "" ;}@ Overridepublic void init (FilterConfig arg0) throws ServletException {// TODO Auto-generated method stub} @ Overridepublic void destroy () {// TODO Auto-generated method stub }}

4. Configure the filter in the web. xml file

  <filter>    <filter-name>AutoLoginFilter</filter-name>    <filter-class>www.csdn.net.day56.filter.AutoLoginFilter</filter-class>  </filter>  <filter-mapping>    <filter-name>AutoLoginFilter</filter-name>    <url-pattern>/login.jsp</url-pattern>  </filter-mapping>

5. The classes or interfaces involved in the above functional modules are as follows:

1. Admin. java class

package www.csdn.net.day56.bean;import java.io.Serializable;public class Admin  implements Serializable{/** *  */private static final long serialVersionUID = 1L;private Integer id;private String name;private String pass;public Admin() {super();// TODO Auto-generated constructor stub}public Admin(Integer id, String name, String pass) {super();this.id = id;this.name = name;this.pass = pass;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPass() {return pass;}public void setPass(String pass) {this.pass = pass;}}

2. BaseDao Interface

package www.csdn.net.day56.dao;public interface BaseDao<T, PK> {}

3. AdminDao Interface

Package www.csdn.net. day56.dao; import www.csdn.net. day56.bean. admin; public interface AdminDao extends BaseDao <Admin, integer> {/*** User Logon verification operation * @ param name * @ param pass * @ return */public Admin checkLogin (String name, String pass ); /***** @ param name * @ return */public Admin checkLogin (String name );}

4. Implementation class of the AdminDao Interface

package www.csdn.net.day56.dao.impl;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import util.DBConn;import www.csdn.net.day56.bean.Admin;import www.csdn.net.day56.dao.AdminDao;public class AdminDaoImpl implements AdminDao {private Connection conn;private PreparedStatement pstmt;private ResultSet rs;@Overridepublic Admin checkLogin(String name, String pass) {Admin entity = null;conn = DBConn.getConn();String sql = "select * from admin where name=? and pass=? ";try {pstmt = conn.prepareStatement(sql);int index = 1;pstmt.setString(index++, name);pstmt.setString(index++, pass);rs = pstmt.executeQuery();if (rs.next()) {entity = new Admin();entity.setId(rs.getInt("id"));entity.setName(rs.getString("name"));entity.setPass(rs.getString("pass"));}} catch (Exception e) {} finally {DBConn.release(rs, pstmt);}return entity;}@Overridepublic Admin checkLogin(String name) {Admin entity = null;conn = DBConn.getConn();String sql = "select * from admin where name=? ";try {pstmt = conn.prepareStatement(sql);int index = 1;pstmt.setString(index++, name);rs = pstmt.executeQuery();if (rs.next()) {entity = new Admin();entity.setId(rs.getInt("id"));entity.setName(rs.getString("name"));entity.setPass(rs.getString("pass"));}} catch (Exception e) {} finally {DBConn.release(rs, pstmt);}return entity;}}

5. BaseService Interface

package www.csdn.net.day56.service;public interface BaseService<T, PK> {}

6. AdminService Interface

Package www.csdn.net. day56.service; import www.csdn.net. day56.bean. admin; public interface AdminService extends BaseService <Admin, integer> {/*** User Logon verification operation * @ param name * @ param pass * @ return */public Admin checkLogin (String name, String pass ); /***** @ param name * @ return */public Admin checkLogin (String name );}

7. AdminService interface implementation class


package www.csdn.net.day56.service.impl;import www.csdn.net.day56.bean.Admin;import www.csdn.net.day56.dao.AdminDao;import www.csdn.net.day56.dao.impl.AdminDaoImpl;import www.csdn.net.day56.service.AdminService;public class AdminServiceImpl implements AdminService {private AdminDao adminDao = new AdminDaoImpl();@Overridepublic Admin checkLogin(String name, String pass) {Admin entity  = adminDao.checkLogin(name, pass);return entity;}@Overridepublic Admin checkLogin(String name) {return adminDao.checkLogin(name);}}

8. Tool

Package util; import java. io. inputStream; import java. SQL. connection; import java. SQL. driverManager; import java. SQL. preparedStatement; import java. SQL. resultSet; import java. SQL. SQLException; import java. util. properties; import org. apache. commons. io. fileUtils; public class DBConn {private static Connection conn; private DBConn () {} public static Connection getConn () {try {if (conn = null) {// create a set object Properti Es properties = new Properties (); // load properties. load (DBConn. class. getClassLoader (). getResourceAsStream ("db. properties "); // load the driver Class. forName (properties. getProperty ("driverClassName"); // obtain the connection object conn = DriverManager. getConnection (properties. getProperty ("url"), properties. getProperty ("user"), properties. getProperty ("pass"); // modify the transaction to the manual commit mode conn. setAutoCommit (false) ;}} catch (Exception e) {e. printSta CkTrace () ;}return conn;} public static void update (String SQL, Object params [], PreparedStatement pstmt) throws Exception {try {pstmt = getConn (). prepareStatement (SQL); for (int I = 0; I <params. length; I ++) {pstmt. setObject (I + 1, params0000i00000000000000000000pstmt.exe cuteUpdate (); conn. commit ();} catch (Exception e) {conn. rollback (); e. printStackTrace () ;}finally {release (null, pstmt) ;}} public static void release (Re SultSet rs, PreparedStatement pstmt) {if (rs! = Null) {try {rs. close ();} catch (SQLException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}} if (pstmt! = Null) {try {pstmt. close ();} catch (SQLException e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}}


The following shows the effect.

1. Open the logon interface, enter the correct user name and password, and select automatic logon.

2. Click "Log on" to go to the SC. jsp page after successful logon.

3. log on to the logon page again.

It is found that the function module of automatic logon is completed.


If you disable tomcat and restart it, you will find that, as long as the cookie is valid and the user name and password have not been modified, as long as you enter the logon interface. the user will automatically log on and jump to SC. jsp page. same effect.

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.