A simple sample:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException{
PrintWriter out = resp.getWriter();
out.println("Hello World!");
}
}
If a class is to be a servlet, it must inherit from httpservlet and select doget or dopost or all based on the data transmission method. The doget and dopost methods both have two parameters: httpservletrequest and httpservletresponse. Httpservletrequest provides an access information method, which represents a client request. When the client accesses the server through the HTTP protocol, all information in the HTTP request header is encapsulated in this object. Httpservletresponse provides the printwriter for specifying the HTTP response status and response header, and sending data to the client. You can use the println statement to generate pages sent to the client.
Both the doget and dopost Methods throw the servletexception and ioexception exceptions.
Differences between doget and dopost:
Doget transfer data from URL, while dopost put data into a package before transfering, so doget has better performance than dopost, dopost support more security then doget. doget has upper limit up to 4kb on the data size it can transfer, while dopost has no limitation. doget submit the request by appending the URL while dopost request is submitted via form.
If we don't care about whether the request type is get or post, we can just write the implementation in dopost and let doget call dopost, or verse vice. but if the specific request type is required, then we need to write implementation in the related method.
So in practice, we use get to get something from the server, and post to post (insert/update/delete) data or files to the server. get is idempotent, the same operation applied multitime will return the same result.
Httpservletrequest object Method(From http://blog.csdn.net/redarmy_chen/article/details/8157053)
-
Common methods for obtaining client information
The getrequesturl method returns the complete URL when the client sends a request.
The getrequesturi method returns the resource name in the request line.
The getquerystring method returns the parameters in the request line.
The getremoteaddr method returns the IP address of the client sending the request.
The getremotehost method returns the complete host name of the client sending the request.
The getremoteport method returns the network port number used by the client.
The getlocaladdr method returns the IP address of the web server.
The getlocalname method returns the Host Name of the Web server.
Getmethod
-
Obtain client request header information
Gethead (name); getheader (string name); getheadernames ()
-
Obtain client request parameters
Getparameter (name): Get the parameter value of the specified name. This is one of the most common methods.
Getparametervalues (string name): obtains an array of all values of the specified name parameter. It is applicable when a parameter name corresponds to multiple values. Such as the check box in the page form, select multiple values submitted by the list.
Getparameternames (): returns an enumeration object containing all parameter names in the request message. You can retrieve all the parameter names in the request message by traversing this enumeration object.
Getparametermap (): returns a map object that saves all parameter names and values in the request message. The key of the map object is the parameter name of the string type, and value is the array of values of the object type corresponding to this parameter.
Httpservletresponse object(From http://blog.csdn.net/redarmy_chen/article/details/8157038)
Response status line:
The response status line of the HTTP Response Message includes the HTTP Version, status code, and related prompt information:
HTTP/1.1 200 OK
Httpservletresponse defines several constants corresponding to the status code value. The name of each constant starts with SC (short for Status Code, then, it is a combination of the English words of the status information in the HTTP 1.1 Standard. Each word is connected by an underscore and all letters are capitalized.
The constant corresponding to Status Code 404 is httpservletresponse. SC _not_found.
The setstatus method is used to set the HTTP Response Message status code and generate a response status line.
The senderror method is used to send the status code indicating the error message (generally 404, the client requested resources cannot be found) to the client and clear the content in the buffer.
Construct a Response Message Header:
Addheader and setheader Methods
Addintheader and setintheader Methods
Adddateheader and setdateheader Methods
Setcontentlength Method
Setcontenttype: This method is used to set the MIME type of the servlet output content. For HTTP, it is used to set the value of the Content-Type response header field. For example, "text/html; charset = UTF-8"
Setcharacterencoding: used to set the character set encoding in the mime Declaration of the output content. For HTTP, it is to set the character encoding in the Content-Type header field.
Use the <meta> label to simulate the Response Message Header:
The HTTP-equiv attribute of the <meta> tag is defined in the HTML language to simulate the HTTP Response Message Header in the HTML document, when the browser reads the <meta> tag with the http-equiv attribute in the HTML document, it will process it in the same way as processing the response message header sent by the Web server.
The getoutputstream and getwriter methods are used to obtain the servletouputstream and printwriter objects that output binary data and text data respectively.
The getoutputstream and getwriter methods are mutually exclusive. After you call any of the methods, you cannot call another method.
The data written by the servlet program to the servletoutputstream or printwriter object will be obtained by the servlet engine from the response. The Servlet Engine regards the data as the body of the Response Message, then, it is combined with the response status line and Response Headers and then output to the client.
After the Serlvet service method is complete, the servlet engine checks whether the close method has been called for the output stream object returned by getwriter or getoutputstream. If no, the servlet engine will call the close method to close the output stream object.
Forward & redirect:
Requestdispatcher (). Forward (request, response)
Httpservletresponse's sendredirect (string location)
The forward method will forward the request and response and pass to the path that was specified in getrequestdispatcher (string path ). the response will Noe be sent back to the client. this method is useful for communicating between server resources (servlet to servlet)
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ RequestDispatcher rd = req.getRequestDispatcher("pathToResource"); rd.forward(request,response);}
Sendredirect method will tell the client that it will send a request to the specified path, the client will build a new request and submit it to the server.
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ resp.sendRedirect("pathToResource");}
So, sendredirect method shocould be used if need to transfer control to different domain or to achieve separate task. For other scenarios, forward is efficient to use since it is faster.
This part illustrates some basic knowledge in Servlet and is also a question that may be asked during the interview. Now I hope I can better understand it.
Thank you for your attention. You must continue to improve yourself.