这是实现您的任务的示例代码。
第一步:创建一个servlet。
package org.smarttechie;
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;
/**
* Servlet implementation class SampleServlet1
*/
public class SampleServlet1 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public SampleServlet1() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<form action=\"SampleServlet2\" method=\"get\">");
out.println("<input type=\"submit\" value=\"Submit\">");
out.println("</form>");
out.println("</body></html>");
}
}
步骤 2:创建另一个 servlet。这将从表单操作标签中调用。如果您观察到表单操作标记值,即指向不包括“/”的“SampleServlet2”url 模式。如果要给出绝对路径(包含'/'),我们需要指定上下文路径。
package org.smarttechie;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class SampleServlet2
*/
public class SampleServlet2 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public SampleServlet2() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("The request is reached");
}
}
Step3:web.xml配置如下。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<servlet>
<description></description>
<display-name>SampleServlet1</display-name>
<servlet-name>SampleServlet1</servlet-name>
<servlet-class>org.smarttechie.SampleServlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SampleServlet1</servlet-name>
<url-pattern>/SampleServlet1</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>SampleServlet2</display-name>
<servlet-name>SampleServlet2</servlet-name>
<servlet-class>org.smarttechie.SampleServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SampleServlet2</servlet-name>
<url-pattern>/SampleServlet2</url-pattern>
</servlet-mapping>
</web-app>
希望这能解决您的问题。