The servlet technology is designed primarily to use the HTTP protocol on the Web. A servlet is a program that runs on a Web server. Java Servlets can be used to process customer requests or to generate dynamic Web pages. An instance first. Then explain.
First edit the following file, named Firstservlet.java
import javax.servlet.*;
import javax.servlet.http.*;
Public class Firstservlet extends httpservlet{
protected void doget (HttpServletRequest request,
httpservletresponse response) throws Servletexception,
java.io.ioexception{
Response.setcontenttype ("text/html");
Java.io.PrintWriter out = Response.getwriter ();
out.println ("
out.println ("
out.println ("<title> Servlet test </title>");
out.println ("
out.println ("<body>");
out.println ("Hello,java servlets");
out.println ("</body>");
out.println ("
out.close ();
}
}
in the path tomcat/webapps/examples/web-inf/web.xml
<servlet> (role: Used to name the servlet)
<servlet-name>FirstServlet</servlet-name>
<servlet-class>FirstServlet</servlet-class> (If you have a package name, use the. Separate)
</servlet>
<servlet-mapping> (function: Provide a default URL for the servlet)
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/FirstServlet</url-pattern>
</servlet-mapping>
Then, under Tomcat/bin/startup.bat, double-click Startup.bat to start the Tomcat container. Input path: Http://localhost:8080/examples/FirstServlet can see output: Hello,java servlets.
Add the two tags in Web. xml <servlet></servlet> and <servlet-mapping></servlet-mapping>, naming and customizing the role of a URL. We can name the servlet file and customize the URL path, where the custom URL is name-dependent and must be named before the custom URL. For example:
<servlet>
<servlet-name>servlet1 </servlet-name>
<servlet-class>org.whatisjava.testservlet</servlet-class >
<init-param>
< Param-name>username</param-name>
< Param-value>daniel</param-value>
</init-param>
< Init-param>
<param-name>e-mail</ Param-name>
<param-value>[email Protected]</param-value>
</init-param>
</servlet>
With this configuration, the servlet can call Getservletconfig (). Getinitparameter ("param1") to obtain the value corresponding to the parameter name.
<servlet>
<servlet-name>servlet1</servlet-name>
<servlet-class>org.whatisjava.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servlet1</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
Function: Name is implemented and URL is customized for servlet
Getting Started with Servlets