我创建了一个简单的 servlet,它打印了一些像这样的消息:
@WebServlet("/servletExample")
public class ServletExample extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello there");
}
一切运作良好。然后我创建了2个这样的jsp页面:
<body>
<form method="post" action="servletExample">
<table border="0">
<tr>
<td>
First name:
</td>
<td>
<input type="text" name="firstname"/>
</td>
</tr>
<tr>
<td>
Last name:
</td>
<td>
<input type="text" name="lastname"/>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
</form>
</body>
和
<body>
<%
String firstName = (String)request.getAttribute("firstname");
String lastName = (String)request.getAttribute("lastname");
out.println(firstName+ " "+lastName);
%>
</body>
servlet 现在看起来像这样:
@WebServlet("/servletExample")
public class ServletExample extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String firstName=request.getParameter("firstname");
String lastName=request.getParameter("lastname");
if(firstName == null || lastName==null){
getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
return;
}
request.setAttribute("firstname", firstName);
request.setAttribute("lastname", lastName);
getServletContext().getRequestDispatcher("/output.jsp").forward(request, response);
}
}
当我运行它时,我看到了该表单,但是当我提交时,我看到了我 2 天前所做的示例中的“Hello there”。无论我做什么,我都看到了。我需要清洁什么?我错过了什么?
编辑:我使用 eclipse 和 tomcat 7