Cookie, session, and Java filters

Source: Internet
Author: User

Basic Knowledge Understanding:

Cookies, sessions, and filters are often used in Web applications, where cookies and sessions are used to hold certain data, and filter filters occur after a request is made by the browser and before the platform executes a specific request. The reason for putting these three together is because there are many times when they are used together, such as some landing procedures.
Cookies are the mechanism of the browser, the session is the mechanism of the server, but in fact the cookie is generated by the server, and then returned to the browser, not the browser itself generated. When a browser sends a request, the cookie is brought together if it has a valid cookie.
The use of cookies is due to the fact that the HTTP protocol is a stateless protocol, that is, through the HTTP protocol itself, the server cannot determine whether the browser has previously been accessed.
The filter is similar to the servlet, and it is necessary to implement the filter interface and override the associated method when writing the relevant code, often changing the Dofilter method. When the filter code is written, it needs to be configured in Web. XML like a servlet if it needs to be effective.
Here is a simple login sample code that combines cookies, sessions, Servlets, and filter:
Define a user entity class that acts as a database data, where singleton mode is used to ensure that only one instance object exists:
Package models;/** * User Information entity class *  * @author tuzongxun123 * */public class Usermodel {    private String userName;    private String password;    Singleton mode, guaranteeing only one user object instance public    static Usermodel getinstance () {        Usermodel user = new Usermodel ("Zhangsan", "123456" );        return user;    }    Private Usermodel (String userName, String pasword) {        this.username = userName;        This.password = pasword;    }    Public String GetUserName () {        return userName;    }    Public String GetPassword () {        return password;    }}



The user logs in the input information index.jsp interface, using the JSP feature in the form form action to get the project path:
<%@ page language= "java" import= "java.util.*" contenttype= "text/html"; Charset=utf-8 "    pageencoding=" Utf-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >



the corresponding background servlet:
Package Servlettest;import Java.io.ioexception;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 Javax.servlet.http.httpsession;import models. Usermodel;public class Loginservlet extends HttpServlet {@Override protected void doget (HttpServletRequest req, Htt    Pservletresponse resp) throws Servletexception, IOException {this.dopost (req, resp); } @Override protected void DoPost (HttpServletRequest req, HttpServletResponse resp) throws Servletexcepti        On, IOException {String userName = Req.getparameter ("UserName");        String Password = req.getparameter ("password");        Analog database data Usermodel user = Usermodel.getinstance ();        String dbusername = User.getusername ();        String Dbpassword = User.getpassword (); if (Dbusername.equals (userName) && Dbpassword.Equals (password)) {//username and password all match, prove login successful, set session and cookie HttpSession session = Req.getsession ();            Session.setattribute ("UserName", userName);            Session.setattribute ("password", password);            Cookie cookie = new Cookie ("UserName", userName);            Cookie cookie2 = new Cookie ("password", password);            Set the storage duration of the cookie cookie.setmaxage (60);            Cookie2.setmaxage (60);            Send cookies to browser resp.addcookie (cookies);            Resp.addcookie (COOKIE2);        Forward the request to the user list req.getrequestdispatcher ("/userlist"). Forward (req, resp);        } else {//forwards the request to the landing page Req.getrequestdispatcher ("index.jsp"). Forward (req, resp);    }        ; }}



request to jump after landing:
Package Servlettest;import Java.io.ioexception;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import models. Usermodel;public class Userlistservlet extends HttpServlet {    @Override    protected void doget ( HttpServletRequest req, HttpServletResponse resp)            throws Servletexception, IOException {        this.dopost (req, RESP);    }    @Override    protected void DoPost (HttpServletRequest req, HttpServletResponse resp)            throws Servletexception, IOException {        Usermodel user = Usermodel.getinstance ();        Print the user list book data in the browser        resp.getwriter (). Write (                "userName:" + user.getusername () + "," + "Password:"                        + User.getpassword ());}    }



Project Web. XML configuration:
<?xml version= "1.0" encoding= "UTF-8"? ><web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns= "Http://java.sun.com/xml/ns/javaee" xmlns:web= "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi: schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id= "Webapp_ ID "version=" 2.5 "> <!--Access project name--<display-name>cookieAndFilterTest</display-name> <!-- Servlet configuration-<servlet> <servlet-name>login</servlet-name> <servlet-class>servlettest. loginservlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>login</ servlet-name> <url-pattern>/loginServlet</url-pattern> </servlet-mapping> <servlet> & Lt;servlet-name>userlist</servlet-name> <servlet-class>servlettest.userlistservlet</ servlet-class> </servlet> <servlet-mapping> <servlet-Name>userlist</servlet-name> <url-pattern>/userList</url-pattern> </servlet-mapping> & lt;! --Filter settings, browse its sending request first will go here--<filter> <filter-name>loginFilter</filter-name> <filter-class >filterTest.FilterTest</filter-class> </filter> <filter-mapping> <filter-name> Loginfilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- Enter the default page for project name Access-<welcome-file-list> <welcome-file>index.jsp</welcome-file> </ Welcome-file-list></web-app>


Java Filter Code:
Package Filtertest;import Java.io.ioexception;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 models. Usermodel;public class Filtertest implements Filter {@Override public void Destroy () {} @Override Public void DoFilter (ServletRequest request, servletresponse response, Filterchain chain) throws IOException, Servlete        xception {//Login request, initial request Direct release httpservletrequest req = (httpservletrequest) request;        HttpServletResponse resp = (httpservletresponse) response;        String uri = Req.getrequesturi (); if ("/cookieandfiltertest/loginservlet". Equals (URI) | | "/cookieandfiltertest/". Equals (URI)) {//release Chain.dofilter (reqUest, response);        Return        }//is not a login request, to determine if there is a Cookie cookie[] cookies = req.getcookies ();            if (cookie = null && cookies.length > 0) {String userName = null;            String password = null; Determine if the user name and password in the Cookie are consistent with the database, or if it is consistent, then forward the request to the landing page for (Cookie cookie:cookies) {if ("UserName"                . Equals (Cookie.getname ())) {userName = Cookie.getvalue ();                } if ("Password". Equals (Cookie.getname ())) {password = Cookie.getvalue ();            }} Usermodel user = Usermodel.getinstance ();                if (User.getusername (). Equals (UserName) && User.getpassword (). Equals (password)) {                Chain.dofilter (request, response);            Return                } else {//redirect to login interface Req.getrequestdispatcher ("/index.jsp"). Forward (req, resp);Return            }} else {req.getrequestdispatcher ("/index.jsp"). Forward (req, resp);        Return }} @Override public void init (Filterconfig arg0) throws servletexception {}}


Cookie, session, and Java filters

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.