我有一个 JSP 页面,其中包含一个表单,我必须从中调用 servlet。但即使在
web.xml
中添加了 servlet 映射并尝试了 webservlet 注释,JSP 页面本身也不会加载。我很困惑不知道该怎么办。
JSP页面:
<html>
<h1>Active Users </h1>
<body>
<form id="userForm" action="${pageContext.request.contextPath}/users" method="post">
<ul id="list" style="list-style: none;">
<input type="submit" name="delete" value="Delete"/>
<input type="reset" name="cancel" value="Cancel"/>
</ul>
</form>
</body>
</html>
调用servlet:
//@WebServlet(name = "users", urlPatterns = ("/users"))
public class UserManagementControllerServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public UserManagementControllerServlet() {
super();
}
public void init() throws ServletException{
Logger.getLogger(UserManagementControllerServlet.class).info("UserManagementControllerServlet initiated");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
try{
//to do
response.sendRedirect("users.jsp");
}catch(Exception e){
}
System.out.println("Reached here!!");
}
}
这是我的
web.xml
配置:
<servlet>
<servlet-name>UserManagementControllerServlet</servlet-name>
<servlet-class>com.ehc.plugins.UserManagementPlugin.UserManagementControllerServlet</servlet-class>
<jsp-file>/jsp/users.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>UserManagementControllerServlet</servlet-name>
<url-pattern>/users</url-pattern>
</servlet-mapping>
您的 JSP 页面位于
/jsp/users.jsp
,您应该能够通过 GET 方法访问它。
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws Exception {
try{
//process the request
...
req.getRequestDispatcher("/jsp/users.jsp").forward(req, resp);
}catch(Exception e){
e.printStackTrace();
throw e;
}
}
当 POST 方法时,您从表单获取数据,处理它并重定向到 servlet。如果是同一个 servlet
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws Exception
{
try{
Strind data = request.getParameter("delete");
//todo
...
response.sendRedirect(request.getContextPath()+"/users");
}catch(Exception e){
e.printStackTrace();
throw e;
}
System.out.println("Reached here!!");
}
要在 servlet 中使用注释,您应该使用支持版本 >= 3.0 的 servlet 容器,或者使用
web.xml
显式定义版本
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
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_3_0.xsd">
<description>Users Web Application</description>
<display-name>Users</display-name>
<servlet>
<servlet-name>UserManagementControllerServlet</servlet-name>
<servlet-class>com.ehc.plugins.UserManagementPlugin.UserManagementControllerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserManagementControllerServlet</servlet-name>
<url-pattern>/users</url-pattern>
</servlet-mapping>
</web-app>