JSP details-Servlet (2)
Servlet development 1. Servlet Creation
Servlet creation is simple. There are two main methods: one is to create a common Java class to inherit from the HttpServlet class, and register the Servlet object in the manual configuration web. xml file. The other method is to directly use the IDE inherited development tools for creation.
2. Servlet Configuration
(1) Declare the Servlet object
In web. xml Label declares a Servlet object. The tag contains two child elements: And . Where The element is used to specify the Servlet name, which can be a custom name; Specifies the complete position of the Servlet object. Includes the package name and Class Name of the Servlet object. Its lifecycle syntax format:
SimpleServlet
Com. zgy. servlet
(2) map Servlet
After the Servlet object is declared in the web. xml file, the URL for accessing the Servlet needs to be mapped. This operation uses Label. The tag contains two child elements: And . Where, Element and Label You cannot change the name of an element. Element is used to map access URLs. The configuration method is as follows:
SimpleServlet
/SimpleServlet
Example:
Package com. zgy. servlet;
Import java. io. IOException;
Import java. io. PrintWriter;
Import javax. servlet. ServletException;
Import javax. servlet. http. HttpServlet;
Import javax. servlet. http. HttpServletRequest;
Import javax. servlet. http. HttpServletResponse;
Public class MyServlet extends HttpServlet {
/**
* The doGet method of the servlet.
*
* This method is called when a form has its tag value method equals to get.
*
* @ Param request the request send by the client to the server
* @ Param response the response send by the server to the client
* @ Throws ServletException if an error occurred
* @ Throws IOException if an error occurred
*/
Public void doGet (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {
Response. setContentType ("text/html ");
Response. setCharacterEncoding ("GBK ");
PrintWriter out = response. getWriter ();
Out. println ("");
Out. println ("");
Out. println ("Servlet instance");
Out. println ("");
Out. print ("Servlet instance ");
Out. print (this. getClass ());
Out. println (", using the GET method ");
Out. println ("");
Out. println ("");
Out. flush ();
Out. close ();
}
}
Web. xml configuration
Xmlns = "http://java.sun.com/xml/ns/javaee"
Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
Xsi: schemaLocation = "http://java.sun.com/xml/ns/javaee
Http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd>
This is the description of my J2EE component
This is the display name of my J2EE component
MyServlet
Com. zgy. servlet. MyServlet
MyServlet
/Servlet/MyServlet
Index. jsp