1. Requirements for automatic login
① do not need to fill in the user name and password information, you can automatically log on to the system
②login.jsp hello.jsp
login.jsp
1 <%@ Page Language="Java"ContentType="text/html; Charset=utf-8"2 pageencoding="UTF-8"%>3 <!DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd ">4 <HTML>5 <Head>6 <Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8">7 <title>Insert Title here</title>8 </Head>9 <Body>Ten One A <formAction= "index.jsp"> -Name<inputtype= "text"name= "Name"/> - <inputtype= "Submit"value= "Submit"/> the - - </form> - + </Body> - </HTML>
hello.jsp
1 <%@ Page Language="Java"ContentType="text/html; Charset=utf-8"2 pageencoding="UTF-8"%>3 <!DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd ">4 <HTML>5 <Head>6 <Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8">7 <title>Automatic login Test</title>8 </Head>9 <Body>Ten One <% A //1If you can get to the request parameter name, print out the welcome message. Store the login information in a cookie and set the maximum age of the cookie to 30S - Stringname=Request.getparameter ("name"); - if(name! )= NULL &&!name.trim (). Equals ("")){ the - //Create and send cookies - Cookie Cookie= NewCookies ("LoginName", name); - Cookie.setmaxage ( -); + Response.addcookie (cookie); - }Else{ + //2read user information from a Cookie and print a welcome message if it exists A cookie[] Cookies=request.getcookies (); at if(cookies! )= NULL &&Cookies.length> 0){ - for(Cookie cookie:cookies) { - StringCookieName=cookie.getname (); - if("LoginName". Equals (CookieName)) { - Stringvalue=Cookie.getvalue (); - name=value; in - } to } + } - the * } $ if(name! )= NULL &&!name.trim (). Equals ("")){Panax Notoginseng Out.print ("Welcome to login" +name); - }Else{ the //3If there are no request parameters and no cookies, redirect to login.jsp + Request.getrequestdispatcher ("/app-1/login.jsp"); A } the + - $ $ - %> - </Body> the </HTML>
[Original]java Web learning note 29:cookie Demo automatic login