下面是一个简单的 Servlet(Process.java)、JSP 页面(index.jsp) 和 Model(Model.java) 的代码。
索引.jsp:
<%@ page import="com.example.*" %>
<html>
<head>
<title> Myapp </title>
</head>
<body>
<form action="process.do" method="POST">
UserName: <input type="text" name="username">
<br>
UserID: <input type="text" name="userid">
<br>
<input type="submit">
<br>
<%
Model m = (Model) request.getAttribute("model");
if( m != null) {
out.println("Username: " + m.getUserName() );
out.println("UserID: " + m.getUserID() );
}
%>
</form>
</body>
</html>
进程.java:
package com.example;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Process extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
Model m = new Model();
m.setUserName( request.getParameter("username") );
m.setUserID( Integer.parseInt( request.getParameter("userid") ) );
request.setAttribute("model", m);
response.sendRedirect( request.getRequestURI() );
}
}
模型.java:
package com.example;
public class Model {
private String userName = "";
private int userID = -1;
public void setUserName(String userName) {
this.userName = userName;
}
public void setUserID(int userID) {
this.userID = userID;
}
public String getUserName() {
return userName;
}
public int getUserID() {
return userID;
}
}
网页.xml:
<servlet>
<servlet-name>Process</servlet-name>
<servlet-class>com.example.Process</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Process</servlet-name>
<url-pattern>/process.do</url-pattern>
</servlet-mapping>
我正在使用 Tomcat7,并且我已经在上下文 /myapp 中部署了这个应用程序。我能够正确查看 index.jsp 页面,但是当我提交表单时,出现以下错误:
HTTP Status 405 - HTTP method GET is not supported by this URL