Java如何创建HelloWorld Servlet?
Servlet是用于创建动态Web应用程序的Java解决方案,可以与旧的CGI技术进行比较。使用Servlet,我们可以创建一个Web应用程序,该应用程序可以显示来自数据库的信息,可以从Web表单接收要存储在应用程序数据库中的信息。
这个例子展示了servlet的基本知识,它为浏览器返回一个helloworldhtml文档。Servlet至少会具有doPost()anddoGet()方法,用于处理HTTPPOST和GET请求。
package org.nhooo.example.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class HelloWorld extends HttpServlet {
public HelloWorld() {
super();
}
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doPost(req, res);
}
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter writer = res.getWriter();
writer.println("<html>");
writer.println("<head><title>Hello World Servlet</title></head>");
writer.println("<body>Hello World! How are you doing?</body>");
writer.println("</html>");
writer.close();
}
}为了使servlet在诸如ApacheTomcat之类的servlet容器上工作,我们需要在应用程序的web.xml文件中添加或注册servlet。此配置告诉容器有关我们的servlet类的信息以及将请求映射到servlet的URL。
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" 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">
<display-name>nhooo-example</display-name>
<servlet>
<description></description>
<display-name>HelloWorld</display-name>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>
org.nhooo.example.servlet.HelloWorld
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
</web-app>将Servlet部署到容器后,我们可以从URL中以http://localhost:8080/app-name/HelloWorld的形式访问它。