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

Source: Internet
Author: User

Recent work on the low efficiency, a variety of changes in demand for a lot of time costs (do not spit groove, you understand, have been powerless), high physical and mental exhaustion. ... ... Each time the rubbish is more, I also served oneself, when I was to gather the word number! No nonsense, start to the point:

Turn over the previous article, found that there is no development environment, here to fill-in the "Step by step" tomcat+mysql for their own app server (1) The server environment has been set up in the JDK, This time directly to find a Java EE version of Eclipse extracted to the directory we want to install, with the Eclipse+adt development of Android students know that Eclipse is free to install, under/eclipse directly open Eclipse.exe can be.

To this we simply install a server running environment, now we start to write their own server program. Whether you are learning Java or Android, you must have learned Core-java course, then you must have learned the Servlet, perhaps you forget, but it doesn't matter, we start again.

        I. Introduction of the Servlet

Excerpt from a short explanation in the book-"aJava Servlet is a program running on a Web server or application server that acts as a middle tier between a request from a Web browser or other HTTP client and a database or application on an HTTP server." Using a Servlet, you can collect user input from a Web page form, render records from a database or other source, and create Web pages dynamically . The Servlet is a technology that Sun offers to develop dynamic Web resources. In fact, "servlet" originally refers to the Java language implementation of an interface (narrow-sense Servlet), but more and more common is: we have any implementation of the Servlet interface class is called "servlet." The role of the Servlet is primarily to parse request data, process it according to business logic, and encapsulate the result as Response return my understanding is "read-Calculate-write", like a math calculator, input operand, operator press "equals" to show the result , and like the neurons of the human brain, "accept stimulation-signal processing-respond." For ease of understanding, let's slowly dismantle:

        Ii. location of the servlet in the server

In the eyes of ordinary users, we use the Internet in the usual way:


Ordinary users only care about themselves as a client, and a thing called the server in the data interaction, where the specific server, what to do, how to implement, the database with what kind of ... None of this matters.

And as the developer of US , the user does not care about the problem we should be regarded as Jia Zhen (this is the guy we eat)-we have to enlarge the server, from the perspective of an entry-level server developer to look at the structure of the server (in this case only Servlet):

the server receives different requests from different users (which are, of course, those requested by the server as the target of the request), analyzes the different requests, and the control module distributes the respective requests to the corresponding Servlet (such as a login request, The login data is sent to Loginservlet), and the Servlet processes the business logic according to the request content (such as the login request to resolve the user name password, and the database stored in the user name password to compare, to determine whether it is a legitimate user's conclusion), complete the response data package returned to the control module, The control module then returns the response to the corresponding requesting user, which completes the network interaction.

        third, start using servlets from small whiteNext , let's start with a Servlet to create an application server:Create Dynamic Web Project in Java EE version of Eclipse (here we take a whole new workspace example, why use a new workspace?). The following will be involved):                the next steps are default, next until:        
In this case, the project was created successfully, so let's take a brief look at the directory structure:        Here's a note : When we create the project, our Dynamic Web module version option defaults to 3.0, which will appear after the Generate Web. XML Deployment Descri Ptor to create the Web. xml file, the Web. xml file is created by default if the previous version of 3.0 does not have this tick option. This is because of the results of the new annotation mechanism of Servlet3.0.         new Servlet class:                           If you don't know what it is, add it first and see what it is later.
URL mappings, I changed to/home/firstservlet:        
NEXT:        Take a look at what you have rewritten, and finally finish, our first servlet is created.
Open the Firstservlet.java you just created and see--oh!. shit! You will be surprised to find that "motherland Jiangshan a red ", all kinds of undefined, all kinds of bags can not be found! Don't be surprised, this is why we started with a whole new WorkSpace for example . Find problem solving problem, we are fearless fearless program Ape! Remember when I specified the next option for the name when I created the Servlet? That's it:, you can see that the parent class of the servlet is Java.servlet.http.HttpServlet, which is not found here, which means that there is still something missing, not a. jar is the environment. -That's the problem.
the root cause of the problem is easy to solve-remember when we first created Dynamic Web Project and didn't specify the Target runtime? This is the designation of the runtime environment, which is our layman's statement-environmental issues. It's okay, now let's do it again:in the Project Explorer blank area > Right-click > New > Other > Select server:        
NEXT > Choose Tomcat Server (because my tomcat is 8.0.32, I am in "step by step" tomcat+mysql for my app to build a server (1) The server environment is also given this version of the build, so choose V8 .0, you have to choose the appropriate version according to your Tomcat):        
NEXT > Set the Tomcat installation path (the JRE can workspace the default JRE, or you can select a specific JRE, such as JRE1.7), followed by finish:        
(You can also next > add the previously created project to the server, then finish, This step is optional ):        have you found all the mistakes before? Don't worry, just one more step--just created the project "right button" > Properties > Targeted runtimes, Shangang create a good server,ok, see the project, normal? Of course, these creation or selection of Target Runtime can also be done at the time of the creation of the project, but I am here alone to take out a walk, let us all impressive. Well, this problem has been solved. Go back to our main line.
let's look at the question that we left before.--initialization parameters, url mappings, literally means initialization parameters, URL mappings. In conjunction with the context, we are editing this when creating the servlet, so the initialization parameter is definitely the servlet's parameter, and the URL mapping is definitely the path map for this servlet. In order to compare, we create a preferenceservlet, in the creation process can not fill in the options are not filled, compared to the code, you will find that there are only the following:
the firstservlet include:
@WebServlet (Description = "Learning servlet created", Urlpatterns = {"/home/firstservlet"}, InitParams = {@WebInitParam (name = "User Name ", value =" abc ", Description =" user name ")})

in the Preferenceservlet:
@WebServlet ("/home/preferenceservlet")
you can see that the previously added options are some description, initialization parameters that appear as annotations. To understand this, I identified the configuration file contents of the servlet in the previous version of the Web. xml file in Servlet3.0:
<servlet><servlet-name>firstservlet</servlet-name><servlet-class>servlet. firstservlet</servlet-class><init-param><param-name>username</param-name>< param-value>abc</param-value></init-param></servlet><servlet-mapping>< servlet-name>firstservlet</servlet-name><url-pattern>/home/firstservlet</url-pattern>< /servlet-mapping>
The functions of the two styles are the same, but it is easier and more efficient to configure the annotations after Servlet3.0. <servlet> tags and <servlet-mapping> tags correspond to each other, servlet-name must be consistent (can have multiple mapping corresponding to a servlet, that is, multiple addresses to a target), when a request arrives , the server first looks for the matching address in <servlet-mapping> and then matches the request Servlet's Java class with the corresponding servlet-name in the <servlet> tag, then sends the request to the class Initialization parameters can be obtained by Getinitparameter ("ParameterName").Speaking in fact, the Doget method in the Firstservlet we created above is as follows:
protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Response.getwriter (). Append ("\ n Initialize parameter UserName =" + Getinitparameter ("UserName"));}

then right-click on the project >run as:        Server selects the project created before, add that works to the server configuration, finish. Appear                That means the operation was successful! enter in the browser address bar http/localhost:8080/servlettest/home/firstservlet Enter and you will see:        
Well, it's a preliminary success. If you're a newbie, there's definitely a lot of places you don't know why, like why do you ask for an address? How did the Servlet's response return? Why is the displayed Chinese become garbled? No matter, everything is not overnight, we are like the title, step by step, carefully. Confined to space, this thought an article can say, did not think or left a lot of content, we continue the next chapter. due to my limited level, please advise me if you have any questions. If I am more satisfied with the article, please wait for the next article, _ Program Ape Adult _ here thanked.

"Step by Step" tomcat+mysql the use of server (2-1) 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.