作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用页面 Controller 模式。如何通过检测请求操作然后根据结果进行调度来为两个不同的页面使用同一个 Controller ?
这是我的代码:
account.jsp
<form name="input" action="<%=request.getContextPath() %>/edit" method="get">
<input type="submit" value="Modifier" />
</form>
帐户 Servlet
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("received HTTP GET");
String action = request.getParameter("action");
if (action == null)
{
// the account page
dispatch(request, response, "/account");
}
else if (action == "/edit") {
// the popup edit page
dispatch(request, response, "/edit");
}
protected void dispatch(HttpServletRequest request,
HttpServletResponse response, String page)
throws javax.servlet.ServletException, java.io.IOException {
RequestDispatcher dispatcher = getServletContext()
.getRequestDispatcher(page);
dispatcher.forward(request, response);
}
}
最佳答案
我发现使用 HttpServletRequest#getServletPath()
得到我需要的东西,所以我不需要解析任何东西!
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("received HTTP GET");
String action = request.getServletPath();
if (action.equals("/account"))
{
// the account page
dispatch(request, response, "/content/account.jsp");
}
else if (action.equals("/edit"))
{
// the popup edit page
dispatch(request, response, "/content/edit.jsp");
}
}
protected void dispatch(HttpServletRequest request,
HttpServletResponse response, String page)
throws javax.servlet.ServletException, java.io.IOException {
RequestDispatcher dispatcher = getServletContext()
.getRequestDispatcher(page);
dispatcher.forward(request, response);
}
}
关于jsp - 如何从 HttpServlet 请求中获取操作以分派(dispatch)到多个页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11255397/
我是一名优秀的程序员,十分优秀!