我在root / Reverse目录中有这个reverse.html
<!DOCTYPE html>
<html>
<body>
<h1>Assignment Servlets-2 - Reverse</h1>
<form method='post' action='ReverseServlet'>
Text: <input type='text' name='text' size='50'><br><br>
<input type='submit' value='submit'>
</form>
</body>
</html>
这是/ WEB-INF目录中的web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet> <servlet-name>ReverseServlet</servlet-name>
<servlet-class>ReverseServlet</servlet-class> </servlet>
<servlet-mapping> <servlet-name>ReverseServlet</servlet-name>
<url-pattern>/reverse</url-pattern>
</servlet-mapping>
</web-app>
这是ReverseServlet.java源代码,它被编译成/ classes目录中的类文件
import java.io.* ;
import javax.servlet.http.* ;
public class ReverseServlet extends HttpServlet {
public void doGet( HttpServletRequest request, HttpServletResponse response ) {
String text = request.getParameter("text");
response.setContentType("text/html");
try {
PrintWriter out = response.getWriter();
out.println( new StringBuffer( text ).reverse().toString() );
out.close();
} catch( Exception e ) {
System.out.println( "cannot get writer: " + e );
}
}
}
它们都在正确的目录中,我可以加载reverse.html,但该操作不会绑定到ReverseServlet类。我正在使用Tomcat 7.0,我已经得到了一个简单的servlet,所以我知道它已正确安装。它只是在点击提交时不会转到servlet代码...
答案 0 :(得分:2)
问题是您是使用发布方法发送请求并尝试使用 get 方法捕获它。
1路:
尝试将post
转换为get
或从表单中删除方法属性:
<form method='get' action='/reverse'>
OR
2路: 在ReverseServlet中实现doPost方法,以便从post方法中捕获请求:
public void doPost( HttpServletRequest request, HttpServletResponse response ){...}
答案 1 :(得分:1)
表单的操作应该是servlet的URL,而不是它的名称:
<form method='post' action='/reverse'>