"Java Project Combat" servlet specific explanation and servlet writing landing page (ii)

Source: Internet
Author: User
Tags java web

The servlet is a technology that Sun offers to develop dynamic Web pages.

Sun provides a servlet interface in the API, and we pretend to use Java programs to develop a dynamic Web page that simply implements the Servelet interface and deploys the class to webserver.


What exactly is a servlet?


In a popular point, only Java programs that implement the Servlet interface are called Servlets.

Servlets are named by Sun, servlet = server + applets (applets represent small applications), and Servlets are small programs executed on the server side.


Write a realistic landing servlet, and deploy the interview


1, we first write a simple HTML, can be new in Webroot, can also copy a written HTML, we use the Post submission method. Of course, you can submit it with GET, you can try it yourself.

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

2, complete the servlet, in the Web project SRC right-click a new class Loginservlet. Enter the following code to do so.

Introduce the required package import Java.io.*;import Javax.servlet.*;import javax.servlet.http.*;p ublic class Loginservlet extends HttpServlet {//override doget method public void doget (HttpServletRequest request, httpservletresponse response) throws   Servletexception, IOException {String username = request.getparameter ("username");      String Password = request.getparameter ("password"); Server-side information printing//system.out.println ("username=" + username);//system.out.println ("password=" + password);// Set the encoding format response.setcontenttype ("text/html;charset=gb18030");//Return HTML page response.getwriter (). println ("

!! "); Response.getwriter (). println (" </body> "); Response.getwriter (). println ("


3, in Webroot under the Web-inf of Web. XML, deploy our servlet, start the server.


<?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 "> <servlet> <servlet-name>MyServlet</servlet-name> <servlet-class >LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name >MyServlet</servlet-name> <url-pattern>/LoginServlet</url-pattern> </ Servlet-mapping></web-app>


4. Be sure to start the server, and then enter your URL in the browser. At this point we are able to invoke the servlet. Let's take a look at the results.


demo:http://download.csdn.net/detail/jiuqiyuliang/7593641 of an instance

=============================================================================================================== ===============

Suppose you don't know how to configure a Java Web project. To be able to move to my previous blog (a step at a myeclipse to build a Java Web project development Environment (i)), here's a concrete introduction to the basics of servlets.

=============================================================================================================== ===============

Servlet Basics


1. Interpret API documentation. Write a servlet program purely manually and deploy the access (as seen above).

Interpreting APIs is a pain in the way of denying learning about APIs, but it is the best tool for learning and improving, and learning and cherishing.




You can go and have a look at the point. From that, you can see that the Servlet interface defines three implementation classes, each of which is Facesservlet, Genericservlet. HttpServlet. Here's a brief introduction.


2. Servlet interface Implementation Class

(1) Facesservlet is a servlet used to manage the Web application request processing lifecycle that uses JSF (JavaServer Faces) to build a user interface. (Facesservletis a servlet this manages the request processing lifecycle for Web applications that's utilizing J Avaserver Faces to construct the user interface.). Everyone assumes deep learning. can point here.

(2)Genericservlet is the parent of HttpServlet, including the regular usage of servlets. Genericservlet makes it easier for program apes to write Servlets. It provides methods for initializing and destroying the life cycle, as well as implementing methods for writing log files.

(3)HttpServlet refers to a servlet that can handle HTTP requests. This is what developers usually should inherit from this class when writing a servlet.

For these three implementation classes, just for everyone to do a simple introduction, false assumptions in-depth research. Just look at the API.



3. Servlet deployment

The client visits the resources in the Webserver through the URL address, so if you want to access the servlet, you need to map the servlet program to a URL address. Use the <servlet> elements and <servlet-mapping> elements in the Web. xml file, as in the above example.

*<servlet> is used to register a servlet, including <servlet-name> and <servlet-class> two child elements, respectively, to set the name of the servlet and the class name of the servlet.

The *<servlet-mapping> is used to map the external access paths in <servlet> above, including <servlet-name> and <url-pattern> two elements. Lets you set the name of the servlet and the external access path for the servlet, respectively.

There are two formats in which the servlet maps to URLs:

1. "*. Extension"

2. Start with a forward slash (/) and End with "/*".

The servlet's matching rules for URLs and path issues. You can check online. There is a lot of relevant information. For example: http://blog.csdn.net/xh16319/article/details/8014107

4. webserver calls the servlet process (servlet life cycle)

The servlet program is called by Webserver and webserver implements the management of the servlet life cycle. The life cycle of a servlet is divided into four steps:

1) instantiation and loading the servlet,new process.

2) Initialize init (servletconfig).

3) to process the request, invoke the servlet's Service,doget,dopost method to call request and response. Passed as a parameter.

4) exit the service and call the Destory method to release the resource.



Attention:

1. The servlet is instantiated only once. Feel a bit of a single-case pattern, and you can look at the implementation of Tomcat.

2, the Init method is also only run once. The servlet instance is created only once. So init initialization is called only once.


5. servlet Thread Safety issues


When multiple clients visit the same servlet concurrently, Webserver creates a thread for each client's access request. and call the service method on this thread. Therefore, the service method assumes that the same resource is being interviewed. It is possible to raise a thread safety issue. It is important to understand the following two sentences:
(1) A servlet is a single-instance multithreading, and a thread-safety problem can occur if there are member variables that can be altered.
(2) The servlet is best used to ensure that the servlet is stateless, that is, there are no member variables that can be changed.




This blog post simply introduces the basics of servlet. We have any questions can give me a message, I will be in time for everyone to solve.



=============================================================================================================== ==============

Next blog post. We do a JDBC connection to the Oracle database instance, to know how to funeral, please see next!

=============================================================================================================== ==============




"Java Project Combat" servlet specific explanation and servlet writing landing page (ii)

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.