1 , forwarding, and redirection httpservletresponse response forwarding: RequestDispatcher Dispatcher= Request.getrequestdispatcher ("/secondservlet");Request.setattribute ("pwd", "123");//The value set here can be obtained in the SecondservletDispatcher.forward (Request, response);the Doget method in Secondservlet is called when the forward method is called//Wait until the forward method finishes executing before executing the following code System.out.println ("Secondservlet is done");REDIRECT : String URL= "Http://www.baidu.com";Response.sendredirect (URL);* Comparison * When to use * redirection: You can specify the URL of the current Web project, or you can specify a different Web resource * Forwarding: You can only specify the current Web project URL * OK to use * Redirect: The value is set in the first request and cannot be obtained after redirection. Two requests, Tomcat created two request * to complete the jump function, select redirect * forward: The set value can be used in other servlets or resources. * Multiple servlets need to be forwarded when data is passed. * Summary: * Number of Requests * Redirect: Request 2 times, Tomcat creates two request object * forward: request 1 times, Tomcat creates 2 request objects * Copy the contents of the first request to the second request. Same value * The browser address bar is modified * Redirect: modify, see the content of the page after the jump * forward: no modification, see the content of the last servlet response after forwarding * Request set value, whether shared * Redirect: Data not shared * Forwarding: Data sharing2 , session: After you access a Web resource, continue to request resources for the current site through a connection, and then close the entire process of the browser. * Session Technology: Cookie, Session * Cookie: * request.getcookies ();get all cookie information for the current Web projectCookies[]cookies = Request.getcookies ();if (cookies!=null) {for (Cookie c:cookies) {System.out.println (C.getname () +":" +c.getvalue ());}} Cookie Cookie= new Cookie ("AA", "Aavalue");Cookie.setmaxage (60*60*24);//unit is secondsCookie.setpath ("/demo/");Response.addcookie (Cookie);* The access path of the cookie can be set via SetPath * In the Cookie store Chinese * encoding: String returndata= Urlencoder.encode (data, "UTF-8");* Decode: String value = Urldecoder.decode (C.getvalue (), "UTF-8");* The value of the cookie can be set how many characters: 4KB * Session: The server creates a memory area on the server that holds all the information for the current user and is associated with a cookie. * Prerequisite: Cookies must be used * Session: * Tomcat creation * Destruction: 30 mins//Get Session Object Httpsessi On session= Request.getsession ();//Save value Session.setattribute ("Number", "ABCD");//Get the saved value number String #= (String) session.getattribute ("number");//Remove value number Session.removeattribute ("Number");* URL Rewrite * General selection Encodeurl * Two methods The difference is that if the argument is an empty string, the returned result is different. public string encodeurl (string url) {string absolute= Toabsolute (URL);if (isencodeable (absolute)) {//Clearly said if (Url.equalsignorecase ("") {//**** URL= Absolute;} return (toencoded (URL, Request.getsessioninternal (). Getidinternal ()));} else {return (URL);}} public string Encoderedirecturl (string url) { if (isencodeable (Toabsolute (URL))) {return (toencoded (URL, Request.getsessioninternal (). Getidinternal ()));} else {return (URL);}} * Note: The parameter URL must be valid, otherwise return the URL without change * when using"/"start, relative to the Web site * Response.encodeurl ("/day07/urlsessionservlet2")//If SessionID is required, append */day07/urlsessionservlet2 to the address;JSESSIONID=F85DB5EFDDB9A6B170AF2B4959EFC4FC* Get the absolute path to the Web String absolute= Toabsolute (URL);* http://localhost:8080/day07/* Summary: * need to consider whether the user's cookie is disabled * All links are URL rewrite (filter) 3 . Verification Code Instance getimageservlet.javapackage Com.yxl.servlet;Import Java.awt.Color;Import Java.awt.Font;Import Java.awt.Graphics;Import Java.awt.image.BufferedImage;Import Java.io.IOException;Import Java.util.Random;Import Javax.imageio.ImageIO;Import Javax.servlet.ServletException;Import Javax.servlet.http.HttpServlet;Import Javax.servlet.http.HttpServletRequest;Import Javax.servlet.http.HttpServletResponse;Import Javax.servlet.http.HttpSession;Public class Getimageservlet extends HttpServlet {public void doget (HttpServletRequest request,httpservletresponse response) throws Servletexception,IOException {this.dopost (Request, response);} public void DoPost (HttpServletRequest request,httpservletresponse response) throws Servletexception,IOException {//Get a picture//create picture--in memory int width= 80;int height = 40;BufferedImage image = new BufferedImage (width, Height,bufferedimage.type_int_rgb);//Create layer, get artboard Graphics g= Image.getgraphics ();//Determine brush color G.setcolor (color.black);//Fill a rectangle G.fillrect (0, 0, width, height);//need only one border//Set color G.setcolor (color.white);//Fill a rectangle G.fillrect (1, 1, width-2, height-2);//padding character String data= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";//Set font G.setfont (new font ("Song Body", Font.Bold, 30));//cache randomly generated characters StringBuffer buf= new StringBuffer ();//Randomly get 4 characters of random random= new Random ();for (int i = 0;i < 4; i++) {//Set the random color G.setcolor (new color (Random.nextint (255), Random.nextint (255),Random.nextint (255)));//Get a random character int index= Random.nextint (62);//Intercept strings string str= data.substring (index, index + 1); // [)//need to put random characters, write to the picture in g.drawstring (str, * I, 30);//cache Buf.append (str);}//will get random string, save to session//* Get session HttpSession session= Request.getsession ();//* Save value Session.setattribute ("Number", buf.tostring ());//interference line for (int i= 0;I < i++) {//Set the random color G.setcolor (new color (Random.nextint (255), Random.nextint (255),Random.nextint (255)));//Random Draw line G.drawline (Random.nextint (width), Random.nextint (height),random.nextint (width), Random.nextint (height));}/** * <extension>jpg</extension> <mime-type>image/jpeg</mime-type> *//notify the browser to send the data when a picture Response.setcontenttype ("Image/jpeg");//Send picture to browser imageio.write (image, "JPG", Response.getoutputstream ());}}loginservlet.javapackage Com.yxl.servlet;Import Java.io.IOException;Import Java.io.PrintWriter;Import Javax.servlet.ServletException;Import Javax.servlet.http.HttpServlet;Import Javax.servlet.http.HttpServletRequest;Import Javax.servlet.http.HttpServletResponse;Import Javax.servlet.http.HttpSession;Public class Loginservlet extends HttpServlet {public void doget (HttpServletRequest request,httpservletresponse response) throws Servletexception,IOException {this.dopost (Request, response);} public void DoPost (HttpServletRequest request,httpservletresponse response) throws Servletexception,IOException {request.setcharacterencoding ("UTF-8");Response.setcontenttype ("Text/html;charset=utf-8");//Get user-submitted data imagenumber String Imagenumber= Request.getparameter ("Imagenumber");//need to determine the information from the session to obtain the saved verification code//* Get session HttpSession session= Request.getsession ();//* Gets the saved value number String #= (String) session.getattribute ("number");PrintWriter out= Response.getwriter ();//Match the data submitted by the user with the data saved by the program if (number! )=null) {//Program save if (Number.equalsignorecase (Imagenumber)) {//Enter correct out.print ("Validate Pass");} else {//Auth code error Out.print ("Captcha Error");}//Regardless of the circumstances, the data stored by the program can only be used once Session.removeattribute ("Number");} else {out.print ("Verification Code Invalid");}}} webroot new login.html page <! DOCTYPE html>1.html</title> <meta name= "keywords" content= "keyword1,keyword2,keyword3"> <meta name= "description" content= "This is my page"> <meta name= "Content-type" content= "text/html; Charset=utf-8 "> <!--<link rel= "stylesheet" type= "Text/css" href= "./styles.css">--> = "/20141123/loginservlet" method= "POST"> <input Type= "text" name= "Imagenumber"/> /> <br/> <input type= "Submit"/> </form> </body>4. URLConnection use (download page)Package Com.yxl.demo;Import Java.io.IOException;Import Java.io.InputStream;Import Java.io.OutputStream;Import Java.net.URL;Import Java.net.URLConnection;Import Java.util.Scanner;Public class Urlconnectiondemo {public static void main (String[]args) throws IOException {//URL class to the Web resource's location URL URL= new URL ("http://localhost:8080/20141123/login.html");//Get connected and be prepared URLConnection Conn= Url.openconnection ();//must determine whether the current request can read and write Conn.setdoinput (true);//Determines if it is readable, the default is TrueConn.setdooutput (True);//Determines if it can be written, default is False//Prepare data to be sent--request fills OutputStream out= Conn.getoutputstream ();Out.write ("user=abcd1234". GetBytes ());//This method writes content to the HTTP request body//Connection//Conn.connect ();//After establishing the link, get the Web resource InputStream is= Conn.getinputstream ();//will automatically link, only call method, the entire request will take effectByte[]BUF = new byte[1024x768];int len =-1;while (len = Is.read (BUF)) >-1) {//String str= new String (Buf,0,len);System.out.println (str); // } Scanner Scanner= new Scanner (IS);While (Scanner.hasnext ()) {System.out.println ("URL--" + scanner.nextline ());} is.close (); }}
Javaweb learning forwarding and redirection, Session technology: Cookie, Session, captcha instance, urlconnection use (download Web page) (4)