Writing a Basic Servlet Program

1. Download and Configure Tomcat

1. Download

Download from the official website

2. Configure

For Windows users, the .exe installer is the easiest option, but it also requires a Java environment to be installed first.

Just go through the installer with the default settings. At one step it will ask you to select your JDK path.

After installation, the directory should look roughly like this:

3. Use It

The bin directory is used to start Tomcat, and webapps is where we place our Servlet application.

Open bin\Tomcat7.exe, then visit http://localhost:8080 in your browser.

If the Tomcat landing page appears, the installation was successful.

2. Write the Servlet Program

1. Write the Java Code

1
import javax.servlet.http.HttpServlet; 

Place the cursor on the error, press Alt+Enter, and choose Add Java EE 6 ..., then wait for it to download.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package cn.lzumi;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(name = "HttpServletTest", urlPatterns = {"/time"})
public class HttpServletTest extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws ServletException, IOException {
        httpServletResponse.setContentType("text/html");
        PrintWriter writer = httpServletResponse.getWriter();
        // Display the current time
        writer.print("<html><head></head><body>" +
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) +
                "</body></html>");
    }
}

Then compile it:

2. Put the .class File into the Tomcat Directory

Find the generated .class file under the out directory and copy it to webapps\ROOT\WEB-INF\classes.

Note: if your class is inside a package, you need to copy the full directory structure as shown below.

Edit the file webapps\ROOT\WEB-INF\web.xml and change the metadata-complete attribute to false:

1
metadata-complete="false"

Open bin\Tomcat7.exe again, then visit http://localhost:8080/time in your browser.

You should now see the current time returned by the servlet.

转载请保留本文转载地址,著作权归作者所有