Java Servlet Review

Source: Internet
Author: User

First, forwarding request RequestDispatcher

Use the request domain object to bring the data to the forwarding resource, which is different from redirection: The client only makes one request, the server invokes multiple resources, the client browser address bar does not change; forwarding is a request, using the same response and request;

?

Servletcontext.getrequestdispatcher (String); Servletcontext.getnameddispatcher (String); Servletrequest.getrequestdispatcher (String);

There are two ways of doing this:

Resp.setcontenttype ("Text/html;charset=utf-8"); Resp.addheader ("Refresh", "3;url= '/w/index.html '"); Resp.getwriter (). Write ("Congratulations login successful, if there is no relay, please click the hyperlink <a href= '/w/index.html ' >AAAA</a>");

The above code after receiving the request will show a successful login jump prompt, 3s will automatically jump to the index.html page;

String message = "<meta http-equiv= ' refresh ' content= ' 3;url=/w/index.html ' ><a href= '/w/index.html ' >aaaa </a> "; this. Getservletcontext (). SetAttribute ("message", message);
this. Getservletcontext (). Getrequestdispatcher ("/message.jsp"). Forward (req, resp); // The message is brought to the message.jsp page for display;

Write the URL tip: Write '/', give the server no need to write the Web application name, and add the Web application name to the browser

'/' on behalf of the current Web application, write the resource path when the first write '/' represents the current Web application;

InputStream in = This.getservletcontext (). getResourceAsStream ("/web-inf/classes/db.properties"); String path = This.getservletcontext (). Getrealpath ("/web-inf/classes/db.properties");//Get the absolute path of resources;

Second, the program code
Program response the response object to what the Code table output, it is important to control the browser to open the Code table, you can use the meta-technology in HTML to simulate the HTTP response header, to control the browser's behavior;

Out.write ("<meta http-equiv= ' content-type ' content= ' Text/html;charset=utf-8 ' >". getBytes ());

You can also set the encoding directly by response the response object;

Response.setcharacterencoding ("UTF-8"); // set the Code table used by response, control response to write data to the browser by the Code table,response.setheader ("Content-type", "Text/html;charset=utf-8" ); // Specify what code table the browser will use to open the data;

A more concise notation.

Response.setcontenttype ("Text/html;charset=utf-8");

Gets the request request parameter and, with the knowledge of the encoding of the request parameter, can encode the requested parameter:

only valid for post mode // Get method handles garbled characters String value = Request.getparameter ("username"new String (value.getbytes ("iso8859-1"), "UTF-8"  ); System.out.println (out);

There are several ways to solve the Chinese garbled:
1. Decode () method

Java.net.URLDecoder.decode (s)  

2. How to set character sets

Request.setcharacterencoding ("Utf-8");  

3. Define the charset character set on the page

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "  pageencoding=" Utf-8 "%>  

4. Define the encoding in the Web. xml file, and define the code as Utf-8 in the Corefilter class.

<Filter>     <Filter-name>Encodingfilter</Filter-name>        <Filter-class>Com.demo.filter.CoreFilter</Filter-class>      <Init-param>         <Param-name>Encoding</Param-name>         <Param-value>Utf-8</Param-value>      </Init-param>     </Filter>           <filter-mapping>        <Filter-name>Encodingfilter</Filter-name>            <Url-pattern>/*</Url-pattern>     </filter-mapping>  

5. Define the code in the Form form

accept-charset= "Utf-8" onsubmit= "document.charset= ' utf-8 ';"  

6. Change the value of ContentTypes
Change the value of contenttypes in Eclipse to Utf-8
7. Changing the tomcat character set
To receive Chinese by changing the character set in the Server.xml file

<port= "8080"  protocol= "http/1.1"  connectiontimeout = "20000" Redirectport = "8443"    uriencoding= "UTF-8"/>  

Third, set session

Response.setdateheader ("Expires", System.currenttimemillis () + 1000*3600); // set the session effective time 10 minutes; response.getwriter (). write (data); Response.setheader ("Refresh", "3");  

Zip file, tell the browser to return a compressed file

        New Bytearrayoutputstream ();        Gzipoutputstream Gout;         Try {            new  gzipoutputstream (bout);            Gout.write ("DD". GetBytes ());            Gout.close ();         Catch (IOException e) {        }        byte[] gzip = Bout.tobytearray ();        Response.setheader ("content-encoding", "gzip");        Response.setheader ("Length", Gzip.length + "");        Response.getoutputstream (). write (gzip);

V. REDIRECT

Response.setstatus (302); //  redirect Response.setheader ("Location", "/first/myjsp.jsp"); // response.sendredirect ("/first/myjsp.jsp"); * The browser will send two requests to the server, the browser address bar will change, when the user log in/display the shopping cart is usually used to redirect
ServletConfig

ServletConfig The configuration information for a specific servlet;
In actual development, there are some things that are not suitable to be written in the servlet program, such data can be configured to the servlet, for example: Which code table the servlet, which database, which configuration file to load;

this. Getservletconfig (). Getinitparameter ("name"); <servlet> <init-param> <param-name>name</param-name> <param-value>xxxxx</ Param-value> </init-param></servlet>
ServletContext

ServletContext: This is a container, the scope of the container for the entire application;
All servlets in a web app share the same ServletContext object

this. Getservletcontext (). Getinitparameter ("DataContext"); <context-param> <param-name>datacontext</param-name> <param-value>xxdata</param-value ></context-param>

If the object reading the resource file is not a servlet, the file can only be read through the class loader, but the resource file should not be too large and the class loader will only load once;

class userinfo {  static= userinfo. class. getClassLoader (). getResourceAsStream ("db.properties"= userinfo.     Class. getClassLoader (). GetResource ("Db.properties"). GetPath ();   The location of the file is obtained by means of the class load, and then the resource file is read in the traditional way. }
}

Servlet configuration

 <?xml version= "1.0" encoding= "UTF-8"? ><web-app version= "2.4" xmlns= "HTTP://JAVA.SUN.COM/XML/NS/J2EE"  Xmlns:xsi  =" Http://www.w3.org/2001/XMLSchema-instance " xsi:schemalocation  = "http://java.sun.com/xml/ns/j2ee http:// java.sun.com/xml/ns/j2ee/web-app_2_4.xsd,  <welcome-file-list> <welcome-file>index.html& lt;/welcome-file> </welcome-file-list> <servlet> <servlet-name>file</servlet-name>        ; <servlet-class  >com.test.fileservlet</servlet- class  > </servlet> <servlet-mapping> <servlet-name>f Ile</servlet-name> <url-pattern>/file</url-pattern> </servlet-mapping></web-app>
   
Cookies & Session
Request.getcookies ();//access to all cookies;Response.addcookie (cookie);//Add a cookie//The session is passed to the browser via a cookie;HttpSession HS =request.getsession ();//The browser has disabled the cookie processing methodString URL1 = Response.encodeurl ("/coosee/servlet/seesiondemo1"); String Url2= Response.encodeurl ("/coosee/servlet/seesiondemo2"); Out.print ("<a href=" + url1 + "> Purchase </a></br>"); Out.print ("<a href=" + url2 + "> Checkout </a></br>"); Request.getsession (false);// false, only fetch, but not create session;

Md5

MessageDigest MD = messagedigest.getinstance ("MD5"); byte [] MD5 =new  base64encoder (); return Encoder.encode (MD5);

Java Servlet Review

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.