JavaWeb——JSP_06 study notes

Posted by Audiotech on Sun, 30 Jan 2022 22:24:51 +0100

JSP_06

Preface: JSP_05. I have a general understanding of cookie s and session s. Now I start to apply them in practice.

 

1, Review

Deepen your understanding of cookie s and session s.

 

2, Use of cookies

1. Seven day login free

dologin.jsp

<%@page import="com.dao.impl.UserDao"%>
<%@page import="java.net.URLEncoder"%>
<%@page import="java.net.URLDecoder"%>
<%@page import="oracle.jdbc.driver.OracleDriver"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
​
    <-- jsp The label will be supplemented later-->
    <jsp:useBean id="u" class="com.entity.Users"></jsp:useBean>
    <jsp:setProperty property="uname" name="u"/>
    <jsp:setProperty property="pwd" name="u"/>
    
<%
//Set encoding method
request.setCharacterEncoding("UTF-8");
​
//Get form information
String name=u.getUname();
String pwd=u.getPwd();
        
//Determine whether to remember the password
String jzmm=request.getParameter("jzmm");
        
//If login verification is successful
if(new UserDao().login(name, pwd)){
    //Add a value to the session -- object u
    session.setAttribute("user", u);
    //Create a cookie and save it in utf-8 encoding
    Cookie c=new Cookie("uname",URLEncoder.encode(name,"utf-8"));
    //Set save time 7 days
    c.setMaxAge(60*60*24*7);
    //Respond to the browser and save to the hard disk
    response.addCookie(c);
    
    //Create a cookie that remembers the password
    Cookie c1=null;
    if(jzmm!=null){
        //If you remember the password, save the user password
        c1=new Cookie("upwd",URLEncoder.encode(pwd,"utf-8"));
    }else{
        //Otherwise save ''
        c1=new Cookie("upwd","");
    }
    c1.setMaxAge(60*60*24*7);
    response.addCookie(c1);
    
    //Online application 
    //Number of people online
    Object count=application.getAttribute("online");
    //If it is not empty, + 1 on the original basis
    if(count!=null){
    application.setAttribute("online",((Integer)application.getAttribute("online"))+1);
    }else{
    //Otherwise, initialize the application
        application.setAttribute("online", 1);
    }
    response.sendRedirect("/Web_01/news/index.jsp");
}else{
    out.print("<script>alert('Login failed');location.href='/Web_01/login.jsp'</script>");
}
​
%>

Take another look at the login interface login jsp

<%
//The user is not logged in for the first time and the saved cookie has not expired. You can get the cookie of this page every time you come in
String name="";
String pwd=""; 
//Obtain cookie s through request
Cookie []cs=request.getCookies();
if(cs!=null){
for(Cookie c:cs){
    if(c.getName().equals("uname")){
        //utf-8 decode and assign value to name
        name=URLDecoder.decode(c.getValue(),"utf-8");
    }
    if(c.getName().equals("upwd")){
        pwd=URLDecoder.decode(c.getValue(),"utf-8");
    }
}
}
​
//If the user chooses to remember the password, that is, pwd is not "", then create a session and log in automatically
if(!pwd.equals("")){
session.setAttribute("username", name);
out.print("<script>alert('Automatically logged in');location.href='/Web_01/news/index.jsp'</script>");
}
%>
​
​
<-- The form part takes the information we got cookie Value is assigned to the input box. Remember the password. A ternary operator is used for the check box
    pwd==""?"":"checked" If the password is not empty, it will be output checked The default check box is selected
-->
<form action="dologin.jsp" method="get" onsubmit="return checkForm()">
                   <div id="user">    User
                     <input value="<%=name %>" id="a1" type="text" name="uname" />
                   </div>
                   <div id="password">dense   code
                     <input value="<%=pwd %>" id="a2" type="password" name="pwd" />
                   </div>
                   <div id="yzm">     Verification Code
                     <input id="a3" type="text" name="yzm" /><sapn id="a4">XXXX</sapn>
                   </div>
                   <div>              Remember the password
                     <input <%=pwd==""?"":"checked" %> type="checkbox" name="jzmm" />
                   </div>
                   <div id="btn">
                        <button type="submit">Sign in</button>
                        <button type="reset">empty</button>
                   </div>
              </form>

Sort out the order,

First, enter. Login JSP, if the user visits for the first time, the browser does not save his cookie, and the value assigned to the input box is empty, which does not have the effect of remembering the password.

After logging in (requesting to access the main interface with only the cookie with the session ID saved), the web server will generate a cookie and respond to the browser for saving. You will visit dologin JSP, the server compiles dologin JSP, compiling the sentence session setAttribute("user", u); When, the server finds the corresponding session assignment according to the carried sessionid. Then create a cookie and respond to the browser. Then enter the main interface (access the main interface index.jsp), and the server compiles index JSP <% = session Getattribute ("user")% > will also take the corresponding session value according to the sessionid brought by the request. When the session expires, it will get null and let the user log in again to re-establish contact.

The next time the user visits, login free can be realized.

Cookies are saved in clear text. It is the best policy for all user passwords to be encrypted by irreversible encryption algorithm.

Java comes with a package: security shares an encryption algorithm I learned (from a blogger). After I opened the source code and translated it, I wrote notes to help you understand.

•import java.security.MessageDigest;
​
    //Define char array
    private static char[] hex={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    
    /**
     * The encryption algorithm encrypts the password with the following operators:
     * @param bytes 
     * @return  
     */
    private static String byte2str(byte []bytes) {
        int len=bytes.length;
        StringBuffer result=new StringBuffer();
        for (int i = 0; i < len; i++) {
            byte byte0=bytes[i];
            result.append(hex[byte0 >>> 4 & 0xf]);
            result.append(hex[byte0 & 0xf]);
        }
        return result.toString();
    }
    
    /**
     * Encryption method
     * @param pwd Encrypted password required
     * @return Encrypted password
     */
    public String myMd5(String pwd) {
        String str="";
        try {
            //Creates an information summary object for the specified algorithm
            MessageDigest md5 =MessageDigest.getInstance("MD5");
            //Updating the summary with the specified byte array (pwd) can be understood as assigning a value to the summary of the information summary object
            md5.update(pwd.getBytes());
  //md5.digest() returns a byte array of hash values that complete the hash calculation by performing a final operation such as padding, and then updates the summary
  //It is understood that after the summary is calculated, a byte array is returned, and then the summary is initialized
            //Call encryption algorithm encryptor
            str=byte2str(md5.digest());
            return str;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

2. Browse records

Cookies can be used to save information according to program requirements.

Idea: after performing an operation, the user can use a cookie to save information. If necessary, use request to take out the corresponding cookie. You can try it yourself.

3, application level object

A tomcat has only one value, which is shared globally, and the whole tomcat is an application. You can use application to do the online number function. dologin.jsp is used.

 

4, jsp tag

1. 6 common jsp tags.

1. < jsp: include page = "page" > include

2. < jsp: param name = "name" value = "VA" > pass parameters

3. < jsp: forward page = "page" > forward

4. < jsp: usebean id = "U" class = "com. Entity. Users" > is equivalent to an instantiated class

5. < jsp: setproperty property = "uname" name = "U" / > set the value of useBean property

6. < jsp: getproperty property = "uname" name = "U" / > value

Note: when using userBean, the format of class is required

Practice shows that the name of setProperty should be consistent with the attribute in the entity class, and the name applied to form submission should also be consistent with the name of the input tag in the form, otherwise the value is null or an error is reported.

The above cookie has been used in the seven day login free.

< jsp: usebean id = "U" class = "com. Entity. Users" > equals Users u=new Users();

< jsp: setproperty property = "uname" name = "U" / > equal to u.setUname("Zhang San");

< jsp: getproperty property = "uname" name = "U" / > equal to u.getUname();

 

2. The difference between jsp containing tags and containing instructions:

<%@include file="../yz.jsp"%>:

  • Not for YZ JSP. After running, you can check whether there is a compilation yz.jsp in the work directory of tomcat JSP file.

  • Cannot pass parameters

< jsp: include page = "page" >

  • The page is compiled

  • Can transmit parameters

The following is a classification example:

type.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
//Set encoding method
request.setCharacterEncoding("utf-8");
​
//Get type id
String ntid=request.getParameter("ntid");
​
//Richter substitution principle instantiation UserBiz()
IUserBiz iub=new UserBiz();
​
//Find news by category id
List<News> li=iub.getByT(ntid);
//facilitate
if(li!=null){
%>
 <h1> <img src="/Web_01/images/title_<%=ntid %>.gif" /> </h1>
 <div class="side_list">
 <ul>
<% 
    for(News n:li){
%>
        <li> <a href='/Web_01/news/read.jsp?nid=<%=n.getNid() %>'><b><%=n.getNtitle() %> </b></a> </li>
<%
    }
}
%>
 </ul>
    </div>

index.jsp

<div class="sidebar">
    <jsp:include page="type.jsp">
        <jsp:param value="1" name="ntid"/>
    </jsp:include>
    <jsp:include page="type.jsp">
        <jsp:param value="2" name="ntid"/>
    </jsp:include>
    <jsp:include page="type.jsp">
        <jsp:param value="3" name="ntid"/>
    </jsp:include>
  </div>

If you don't use the include tag, do you want to carry out three convenience collections in the main interface? It's troublesome to operate. Here, you can only use the label. The type on the label JSP will compile. The effect is as follows

5, Summary

Deepen the understanding of the difference and use of cookie s and session s. Theoretical knowledge helps to understand, and knocking is the truth. Everyone has a successful study and a smooth work!!!

Topics: Web Development JSP Session cookie