我正在学习JSP / Servet,并尝试制作一个简单的Servlet控制器。
这是我的项目结构:
test是主页,用户可以输入自己的爱好。确认页面,将向用户确认详细信息。它可以选择返回并编辑信息或将信息提交到process.jsp页面。
Test.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html lang="eu">
<head>
<meta charset="UTF-8">
<title>Simple web page</title>
</head>
<body>
<p>
This is a simple HTML page that has a form in it.
<form action="ch2/servletController/Controller">
<p>
Hobby:<input type="text" name="hobby" value="${param.hobby}">
<input type="submit" name ="confirmButton" value="confirm">
</form>
</body>
</html>
Confirm.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Confirm Page</title>
</head>
<body>
<p>
The value of the hobby that was sent to this page is <strong>${param.hobby} </strong>.
<p>
<form action="ch2/servletController/Controller">
<p>
If there is any error, please click the edit button and
to process press the Submit button <br>
<input type="hidden" name="hobby" value="${param.hobby}">
<input type="submit" name="editButton" value="Edit">
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
Process.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Process Page</title>
</head>
<body>
Thank you for your information, Your hobby of <strong>${param.hobby} </strong> will
be added to our records, eventually.
</body>
</html>
Controller.java
package ch2.servletController;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/Controller")
public class Controller extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
String address;
if(request.getParameter("submit") != null)
{
address = "Process.jsp";
}
else if ( request.getParameter("editButton") != null)
{
address = "test.jsp";
}
else
{
address = "/Confirm.jsp";
}
RequestDispatcher dispatcher =
request.getRequestDispatcher(address);
dispatcher.forward ( request, response);
}
}
但是我无法返回到test.jsp页面和Process.jsp页面:
我注意到我的路径不正确,甚至servlet位置也在重复。是否可以解释为什么servlet位置重复,以及如何通过控制器成功导航到test.jsp?
非常感谢您的提前反馈。
在Confirm.jsp
中的表格上,您使用的是相对URL:ch2/servletController/Controller
。 URL与服务请求的资源的位置(浏览器的地址栏中的位置)http://localhost:9191/SampleProject/ch/servletController/Controller
相关。
您应该在您的Confirm.jsp
上使用绝对URL,使用:
<form action="${request.contextPath}/ch2/servletController/Controller">