Simple Application of servlet--session (2)

Source: Internet
Author: User
Tags set background

Application of Session technology 1. Prevent users from illegally logging on to a page

For example, our user management system, must be logged in successfully to jump to the main page, and not directly bypass the login page directly to the main page, this application is a very common application.
At this time, we need to use the session technology, such as the following, when the user's controller Loginclservlet.java Verify that the user is successful, the current user information is saved in the Session object:

// 把user对象保存在sessionHttpSession session = request.getSession();session.setAttribute("login-user", user);

Then in the main page Mainframe.java the first place, take out the session of the login user information, if the information is empty, then for illegal access, jump directly to the login page, and prompted the relevant information:

// 取出login-user这个sessionUser login_user = (User)request.getSession().getAttribute("login-user");ifnull){    // 说明用户没有登录,让他跳转到登录页面    request.setAttribute("error""请登录!");    request.getRequestDispatcher("/LoginServlet").forward(request,response);    // 这个return很重要!    return;}

Then there is a problem here, a website will have many need to prevent illegal access to the page, if this method is not very troublesome?

There are two ways to solve this problem:
The first is to encapsulate the code of the authenticated user into a function, each call
The second is the use of filters (described later)

2. Verify that the verification code entered is correct when the user logs in

Principle: using the drawing technology to Java
Suppose we write the login page login, verify the user's loginclservlet, and generate the Createcode of the verification code, as follows:

When the user accesses the login page login, the login page requests Createcode to generate a verification code, which is then displayed on its own page and then submitted to Loginclservlet for verification. Obviously, access to login and request Createcode This is two different requests from the browser, so the Createcode generated verification code string must be placed in the session in order for Loginclservlet to get, and then verify.

So how to let login page login display verification code? In fact, it is very simple, direct img SRC point to createcode this servlet can, as follows:

out.println("<font color=white>验证码:<input type=‘text‘ name=‘checkcode‘/>);

You can see the results of the operation:

This login form is submitted to Loginclservlet for verification, it needs to obtain the user input verification code from the parameters, and then remove the Createcode the servlet into the session in the correct verification code, and then compare the two, The key code for its Doget method is as follows:

//gets the verification code of the user's id/password/input  String id = Request.getparameter ( "id" ); String passwd = request.getparameter ( "passwd" ); //user-entered verification code  String Input_checkcode = request.getparameter ( "Checkcode" ); //Correct verification code  String checkcode = (string) request.getsession (). getattribute ( "Checkcode" ); //first see the verification code right  if  (Input_checkcode.tolowercase (). Equals (Checkcode)) {//verification code OK, to database validation ID and passwd }else  {request.setattribute (,  "wrong Captcha"  ); Request.getrequestdispatcher ( "/login" ). Forward (request, response);} 

The most important thing here is to generate the Servlet,servlet code of the verification code as follows :

ImportJava.awt.Color;ImportJava.awt.Font;ImportJava.awt.Graphics;ImportJava.awt.image.BufferedImage;ImportJava.io.IOException;ImportJava.util.Random;ImportJavax.imageio.ImageIO;ImportJavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;ImportJavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse; Public  class createcode extends httpservlet {     Public void Doget(HttpServletRequest request, httpservletresponse response)throwsServletexception, IOException {//7. Prevent browser from caching random imagesResponse.setdateheader ("Expires", -1); Response.setheader ("Cache-control","No-cache"); Response.setheader ("Pragma","No-cache");//6. Notifies the client to open a picture to send past dataResponse.setheader ("Content-type","Image/jpeg");//1. Create a picture in memoryBufferedImage image =NewBufferedImage ( the, -, BUFFEREDIMAGE.TYPE_INT_BGR);//2. Write data to the pictureGraphics g = image.getgraphics ();//Set background colorG.setcolor (Color.White); G.fillrect (0,0, the, -); String Checkcode ="";//Draw 5 Verification Code characters         for(intI=0;i<5; i++) {G.setcolor (Generatecolor ());            G.setfont (Generatefont ());            String str = GENERATESTR ();            Checkcode + = str; g.DrawString (str, -*i, -); }//Draw interference points         for(intI=0;i< -; i++) {Random random =NewRandom ();intx = Random.nextint ( the);inty = Random.nextint ( -);            G.setcolor (Generatecolor ()); G.filloval (x, Y,2,2); }//Draw interference lines         for(intI=0;i<5; i++) {Random random =NewRandom ();intX1 = Random.nextint ( the);intY1 = Random.nextint ( -);intx2 = Random.nextint ( the);inty2 = Random.nextint ( -);            G.setcolor (Generatecolor ());        G.drawline (x1, y1, x2, y2); }//The phrase is to save the randomly generated verification code to the session        //The CAPTCHA is not case-sensitive, so it is lowercaseRequest.getsession (). SetAttribute ("Checkcode", Checkcode.tolowercase ());//5. Export the picture of the data to the browserImageio.write (Image,"JPG", Response.getoutputstream ()); }/** * Generate random font * @return  */     PublicFontGeneratefont() {string[] Font_names =NewString[] {"Broadway","founder Yao Body","Footlight MT Light","Sitka Text","founder Shu Body","The Young Circle","Colonna MT"};int[] Font_styles =New int[]{font.bold, Font.Italic, font.bold|        Font.Italic}; Random random =NewRandom ();intName_index = Random.nextint (font_names.length);intStyle_index = Random.nextint (font_styles.length);return NewFont (Font_names[name_index],font_styles[style_index], -); }/** * Generate random color * * @return  */     PublicColorGeneratecolor() {Random random =NewRandom ();return NewColor (Random.nextint ( the), Random.nextint ( the), Random.nextint ( the)); }/** * Generate random number [0-9a-za-z] * * @return  * *     PublicStringGeneratestr() {string[] Nums =Newstring[ +];//Add 0-9 of these 10 numbers         for(inti =0; I <Ten;        i++) {Nums[i] = string.valueof (i); }//Add a-Z to these 26 uppercase letters         for(inti = $; I < the; i++) {nums[i- -] = Character.tostring ((Char) (i); }//Add a-Z to these 26 lowercase letters         for(inti = the; I <123; i++) {nums[i- A] = Character.tostring ((Char) (i); }//Generate a random numberRandom random =NewRandom ();intindex = Random.nextint ( +);returnNums[index]; } Public void DoPost(HttpServletRequest request, httpservletresponse response)throwsServletexception, IOException { This. doget (Request, response); }}
3. Implement a simple shopping cart

Suppose we want to buy books Online, then how do you add to the shopping cart, and can see the function of the shopping cart? Be sure to use the session.
First of all, we first write a book class, which encapsulates the book of related information, here for simplicity, mainly have ID number, title, and purchase of the number. Then emulate a database, as follows:

ImportJava.util.HashMap;ImportJava.util.LinkedHashMap;/** * Simulation database * /Final  Public  class DB {    Private StaticHashmap<string, book> HM =NULL;Private DB(){    }Static{HM =NewLinkedhashmap<string, book> (); Book Book1 =NewBook ("1","Java Basics",0); Book Book2 =NewBook ("2","Oracle Database",0); Book BOOK3 =NewBook ("3","C Language",0); Book BOOK4 =NewBook ("4","python core tutorial",0); Book Book5 =NewBook ("5","Web Technology",0);        Hm.put (Book1.getid (), Book1);        Hm.put (Book2.getid (), BOOK2);        Hm.put (Book3.getid (), BOOK3);        Hm.put (Book4.getid (), BOOK4);    Hm.put (Book5.getid (), BOOK5); }/** * Get all the books in the database * @return  * *     Public StaticHashmap<string, book>Getbooks(){returnHm }/** * Get the book by ID * @param ID * @return * *     Public StaticBookGetbookbyid(String ID) {if(Hm.containskey (ID)) {returnHm.get (ID); }return NULL; }}

Then in our showbook this servlet read all the books in the database information, displayed on the page, its Doget method is:

 Public void Doget(HttpServletRequest request, httpservletresponse response)throwsServletexception, IOException {response.setcontenttype ("Text/html;charset=utf-8");    PrintWriter out = Response.getwriter (); Out.println ("); Out.println ("<table border=1>");    hashmap<string, book> books = Db.getbooks (); Iterator it = Books.keyset (). Iterator (); while(It.hasnext ())        {Book book = Books.get (It.next ()); Out.println ("<tr><td>"+book.getname () +"</td><td><a href= '/mycart/buybookcl?id="+book.getid () +"> Click to buy </a></td></tr>"); } out.println ("</table>");}

As you can see, when the user clicks on the purchase link, jumps to buybookcl this servlet for processing, and passes the past parameters together as the ID number of the book, let's see how BUYBOOKCL writes:

 Public void Doget(HttpServletRequest request, httpservletresponse response)throwsServletexception, IOException {response.setcontenttype ("Text/html;charset=utf-8");//Receive the name of the user's purchase bookString id = request.getparameter ("id");    String name = Db.getbookbyid (ID). GetName (); HttpSession session = Request.getsession ();//Easy to use HashMap    //books purchased from the sessionhashmap<string,book> books = (hashmap<string,book>) Session.getattribute ("Books");if(Books = =NULL) {books =NewLinkedhashmap<string,book> (); }if(Books.containskey (ID))        {Book book = Books.get (ID); Book.setnum (Book.getnum () +1); }Else{Book book =NewBook (ID, name,1);    Books.put (ID, book); } session.setattribute ("Books", books);//forward to Showmycart view shopping cartRequest.getrequestdispatcher ("/showmycart"). Forward (request, response);}

After we receive the ID of the book, and then remove the HashMap from the session to save the CART information, if the HashMap is empty, create a new HashMap; if the hashmap is not empty, go to find out if there is a book ID number, if it already exists, Note that the book has been purchased before, the number of the book will be added 1, the new purchase of the book, instead, and the number is set to 1.

Look at the results of the operation:
Page of 1.ShowBook:

2. Click on purchase to jump to the shopping cart page:

The above is the three simple example of the application session, in the actual project, certainly more than that simple, such as shopping cart, and ultimately must be stored in the database.

Simple Application of servlet--session (2)

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.