如果请求采用Get方式,则重写doGet()方法,如果请求采用Post方式,则重写doPost()方法。
下面是重写doGet()方法的servlet例子。
servlet继承如下类:
整体结构:
在servlet程序的空白处右键-Source-Override/Implements Methods..,选择重写doGet()与doPost()方法,点击ok,则会自动添加程序段。
由于采用doGet()方式请求Servlet,所以重写doGet()方法,内容如下:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>第一个Servlet小例子</title>
</head>
<body>
<!-- 超链接就是一种Get请求方式 -->
<a href="servlet/HelloServlet">Get方式请求HelloServlet</a>
</body>
</html>
index.jsp
package 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; //继承于HttpServlet
public class HelloServlet extends HttpServlet { @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
//super.doGet(request, response);
System.out.println("处理Get()请求");//后台输入话,表名确实进行了对Get()请求的处理
PrintWriter out =response.getWriter();//打印输出内容
response.setContentType("text/html;charset=utf-8");//响应内容类型的字符集设置
out.println("<strong>Hello Servlet</strong><hr>");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
//super.doPost(request, response);
} }
HelloServlet.java
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>MyFirstServlet</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>HelloServlet01</servlet-name>
<servlet-class>servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet01</servlet-name>
<!-- url-pattern要和请求的路径相同 -->
<url-pattern>/servlet/HelloServlet</url-pattern>
</servlet-mapping>
</web-app>
web.xml
如果使用post请求,我们就做一个表单,method设置为post:
程序改动有2处,一是在index.jsp中加入表单,以post方式提交,二是在web.xml中重写doPost()方法。程序截图如下:
运行项目,输入地址,点击提交按钮,就会将请求提交给HelloServlet来处理,该Servlet调用doPost()方法进行业务处理。
点击按钮,控制台输出:
结果显示:
可以看到地址栏从原来的index.jsp变成了HelloServlet,说明请求提交给了servlet处理。