I recently read more than N tutorials on the Internet when I was studying how to develop servlets using eclipse, which made me confused. Many articles are copied one by one and copied exactly the same, I did not write it myself, so an article that has been outdated for N years is still widely circulated on the Internet! I can't see it, so I wrote down this development experience, hoping to help my friends who just learned servlet.
Taking Hello world as an example, the basic steps are as follows:
1. Select File> New> project.
2. Select Tomcat project in the dialog box, and then click
3. Enter the project name. Here you can write helloworld and continue next.
4. Check the can update server. xml file option, finish, and a poject has been created.
5. Open the New Class Wizard, enter helloworld in name, And javax. servlet. http. httpservlet in superclass. Press finish. A servlet is created.
6. Reload the doget method in helloworld. java. The Code is as follows:
Import javax. servlet. http. httpservlet;
Import javax. servlet. http. httpservlet;
Import javax. servlet. http. httpservletrequest;
Import javax. servlet. http. httpservletresponse;
Import java. Io. ioexception;
Import java. Io. printwriter;
Import javax. servlet. servletexception;
Public class helloworld extends httpservlet {
Public void doget (httpservletrequest request, httpservletresponse response)
Throws ioexception, servletexception {
Response. setcontenttype ("text/html ");
Printwriter writer = response. getwriter ();
Writer. println ("Hello world! ");
}
}
7. Create a web. xml file in the WEB-INF directory as follows (note that this XML file should be built in the WEB-INF under the project ):
<? XML version = "1.0" encoding = "UTF-8"?>
<! Doctype web-app public "-// Sun Microsystems, Inc. // DTD web application 2.2 //" http://java.sun.com/j2ee/dtds/web-app_2_2.dtd ">
<Web-app>
<Servlet>
<Servlet-Name> testservlet </servlet-Name>
<Servlet-class> helloworld </servlet-class>
</Servlet>
<Servlet-mapping>
<Servlet-Name> testservlet </servlet-Name>
<URL-pattern> Servlet/helloworld </url-pattern>
</Servlet-mapping>
</Web-app>
8. CTRL + S save, right-click helloworld project, select Tomcat project-> Update context to server. xml
Note: This step is very important. eclipse will automatically modify the server. xml file and add the helloworld project.
9. Start tomcat in eclipse
10. Access http: // localhost: 8080/helloworld/servlet/helloworld in a browser