"Step by Step" tomcat+mysql the use of server (2-2) servlet for your app

Source: Internet
Author: User

In the previous "Step by step" tomcat+mysql for their own app to build server (2-1) servlet usage We simply have a general understanding of what the servlet is doing, the position in the server, and finished in a brand new WorkSpace When you create the first Dynamic Web Project and create the first Servlet that resolves the common problems that you may encounter during the solution, there is still a lot of content that is not finished, and today we are going to continue to solve these problems:

How can I access the meanings of the parts in a servlet & URL

Let's look back at the address http://localhost:8080/ServletTest/Home/FirstServlet that was used when accessing Firstservlet in the browser at the end of the previous article, and we specifically labeled different parts of the URL with different colors. , let's look at what each of these parts is:

/http localhost:8080 /servlettest/home/firstservlet

/ http is a network communication protocol, HTTP is the application Layer communication protocol between client browser or other program and Web server, such as FTP, HTTPS ... And so on, you can understand that is the network communication rules, you want to use HTTP to follow its specified under the various rules (this specific I also do not understand, do not add explanation, lest fraught).

Span style= "White-space:pre" >         localhost:8080 * Note * only the public IP can be accessed over the Internet, otherwise it can only be used over the LAN, on this issue, we will also be involved in the back, then explain in detail.

/strong> /servlettest/home/firstservlet is the path that the program you are accessing is deployed on the server. In fact, this path is two parts, /servlettest /home/firstservlet /servlettest is the project name (consistent with your project name, you and I are not necessarily the same),/home/firstservlet is specified when creating a servlet Url-mapping. The project name and url-mapping group compose your Servlet path.

When we request such an address (the previous example is to access the address in the browser via GET, and then we add a POST request example), according to the rules of the Http protocol will go to the corresponding IP host, the boot Tomcat will listen to the settings of the port (if there is no change, The default port number is 8080), listen to the local host this port after the access according to the path-project project name + url-mapping map to match the requested address corresponding Servlet. In this way, our request is sent to where we want to go, and then we see how the Servlet responds to the request.

        Second, the servlet responds to the request

Our most commonly used servlet is inherited from HttpServlet, a servlet that responds to GET, post two requests. Remember when we created Firstservlet in the last article to remind you to look at the picture, and then paste it:

When creating a Servlet, Eclipse defaults to overriding the parent class method Doget, DoPost. The Doget method is specifically used to respond to a GET request (starting with the Servlet we started with, always using GET requests, post requests we will appear later, and give a complete example of my Android and server post interaction); The DoPost method is specifically used to ring should be POST-requested. GET, Post is the two most commonly used network request mode, but the use of different methods, each has advantages and disadvantages, no basic knowledge of the students directly to Baidu, more easily understood.

As we have not yet talked about POST, let's take the GET request as an example of how the Servlet responds to our request:

In the above question we already know how to request to a specific servlet, let's complete the servlet response. Then the engineering servlettest in the previous article continues, and the original Doget method of our newly created Firstservlet is as follows:

/** * @see Httpservlet#doget (httpservletrequest request, HttpServletResponse *      response) */protected void Doget ( HttpServletRequest request, HttpServletResponse response) throws Servletexception, IOException {}

As you can see, theDoget method has two arguments (the Dopost method is the same): a HttpServletRequest instance object, a HttpServletResponse instance object . Where HttpServletRequest is the GET request that we send to the Servlet (in the same way that the DoPost method's entry HttpServletRequest object is the POST request sent), from which we can get the parameters set when we initiated the request The HttpServletResponse is the response that will be returned to the client or browser ( as to how this response is returned from here to the request source, and we are done with this problem), what we want to do in the Servlet is from the request Gets the request parameter, calculates the processing according to the business logic, draws the conclusion after the result assigns the value to the response to return to the client. At this point, a complete network interaction is completed, the following simple example:

In the following code, we simulate the simplest process of login validation:

/** * Servlet Implementation class Firstservlet */@WebServlet ("/home/firstservlet") public class Firstservlet extends HttpServlet {private static final long Serialversionuid = 1l;/** * Default constructor. */public Firstservlet () {}/** * @s EE httpservlet#doget (httpservletrequest request, HttpServletResponse * response) */protected void Doget (httpservletre Quest request, HttpServletResponse response) throws Servletexception, IOException {String account = Request.getparameter ("account"); Get the value of the parameter named account from request string password = request.getparameter ("password"); Get the value of the parameter named password from request System.out.println ("account:" + account + "\npassword:" + password); Print out a look at string result = "", if ("abc". Equals (account) && "123". Equals (password)) {//Demo login, password verify result = "Login S Uccess! ";} else {result = "sorry! Account or password error. ";} /* Here we just simulated one of the simplest business logic, of course, your actual business can be quite complex */printwriter PW = Response.getwriter (); Gets the output stream pw.println (result) of the response; Outputs the result of the business logic by the output stream pW.flush ();} /** * @see Httpservlet#dopost (httpservletrequest request, HttpServletResponse * response) */protected void DoPost (HTT Pservletrequest request, HttpServletResponse response) throws Servletexception, IOException {doget (request, response); The default code, meaning to do dopost and doget the same//* * * But it is not feasible in essence? We'll talk about it next or next.}}

running as > run on Server runs in Tomcat.

Next, we'll splice an ideal GET request in the browser:

Http://localhost:8080/ServletTest/Home/FirstServlet?account=abc&password=123

Operation Result:

Request parameters for Terminal Console logging:

Let's take another counter-example:

Terminal record:

What, did you succeed? Ax, we have to earnestly practice the title of the step by step, POST method put on this topic after the detailed said.

        Third, the servlet workflow

If you are a full service side of the small white, do here is not a little excited about it? Finally got through the two veins of the governor! But as a program ape that needs constant learning and thinking, how can a Servlet receive a GET request and receive a POST request? How can you return the response to the request source? Let's look at the workflow of the Servlet.

There is an extremely important method in HttpServlet--service (httpservletrequest request, httpservletresponse response), in Ser The Vice method obtains request requests in the way that the GET, POST different requests are distributed to the corresponding Doget, DoPost methods , the general process of the Servlet such as:

Note that: two parameters HttpServletRequest request and HttpServletResponse response are objects that are owned by the Server, Doget, DoPost method is to change its contents (so both methods have a return type of void), and after completion the Server returns the response of the operation to the request source. This is the general process of the Servlet!

Different as:

The Servlet has a creation process that fires its init () (This is the method that httpservlet the parent class Genericservlet) to initialize. There are two conditions that can be fired, which we can set ourselves, by default (2) The first time the servlet is requested and the servlet does not have an instance of Init (), or it can be configured under the <servlet> tab in Web. XML < Load-on-startup> label, the configured value is integer, the smaller the value, the higher the Servlet's boot priority.

For more client requests, the Server creates a new request and response object, and still activates the Servlet's service () method, passing the two objects as parameters to it. This repeats the above loop, but does not need to call the Init () method again. The generic servlet is initialized only once (only one object), and when the server no longer needs the servlet (typically when the server shuts down), the server calls the servlet's Destroy () method.

        Four, garbled problem

In the last example, we left a problem, is the Chinese garbled (if you are a Virgo, do not toss you, thoughtful to give you a link, do not bother to find) the problem, remember? Have you found that this article has been avoided in Chinese before? Now let's get to the problem:

We add the Doget account password in Chinese, in response also add a bit of Chinese;

/** * @see Httpservlet#doget (httpservletrequest request, HttpServletResponse * response) */protected void Doget (Httpservletreque St request, httpservletresponse Response) throws Servletexception, IOException {String account = Request.getparameter (" Account "); Get the value of the parameter named account from request string password = request.getparameter ("password"); Get the value of the parameter named password from request System.out.println ("account:" + account + "\npassword:" + password);  Print out a look at string result = "", if ("King X". Equals (account) && "Jay X". Equals (password)) {//Add Chinese result = "Login success!" + "It worked!" "; The response is also dotted with Chinese}else {result = "sorry! Account or password error. "+" a bit of a problem! "; The response is also dotted with Chinese}/* here we are just simulating a simplest business logic, of course, your actual business can be quite complex */printwriter PW = Response.getwriter (); Gets the output stream pw.println (result) of the response; Outputs the result of the business logic by the output stream Pw.flush ();} 
after you make sure that the server program is updated (typically after the first run succeeds, after the code changes are automatically executed after saving), the browser requests

Http://localhost:8080/ServletTest/Home/FirstServlet?account= Wang x&password= Jie x

As we can see, the English part of the result is correct-the result of the judgment is true, which indicates that the request-to-logic processing is ideal, and as a secondary certificate, we look at the request parameter records received by the server:

Here, we find out the source of the garbled problem-the response process problems, and the Chinese garbled problem is generally caused by encoding format. So here we are adding a line:

// ...... The previous code piece does not have to post the Response.setcontenttype ("Text/html;charset=utf-8"); Set the encoding format of the response message PrintWriter PW = Response.getwriter (); Gets the output stream pw.println (result) of the response; outputting the result of the business logic through the output stream Pw.flush ();
Once the change has been successfully applied, request again:


* Note * Generally we in normal use, will directly set the request, Response encoding format, in case of the problem caused by coding problems, as follows:

protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {/* First set the request, Response message encoding format  */request.setcharacterencoding ("Utf-8"); Response.setcontenttype ("Text/html;charset=utf-8") ;// ..... and proceed with our logic processing}
Is not a classmate will think, if each Servlet to write this, doget, doPost to write manually, is not very troublesome also very annoying? Yes! It's kind of annoying. Is there any good way to solve this problem? The answer must be, that is, the Servlet filter filters (under Package javax.servlet.Filter), which we'll talk about behind. This article is here first!

The level is limited, if has the insufficiency and the mistake, please treatise, _ Program Ape Adult _ here thanked!

"Step by Step" tomcat+mysql the use of server (2-2) servlet for your app

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.