我创建了一个简单的登录页面。如果用户输入正确的用户名和密码,页面将被重定向到成功页面,否则它将被重定向到索引页面。在登录页面中,我向 servlet 提供了表单提交操作。一旦 servlet 验证输入,它将分派到相应的 jsp 页面。我的问题是操作名称在调度后仍然在 url 中。这样对吗?
package com.123.www;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
public Login() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
//PrintWriter out = response.getWriter();
String userName = request.getParameter("username");
String passWord = request.getParameter("password");
RequestDispatcher view = null ;
if((userName=="")&&(passWord==""))
{
view = request.getRequestDispatcher("index.jsp");
}
else
{
HttpSession session = request.getSession(true);
session.setAttribute("name",userName);
view = request.getRequestDispatcher("success.jsp");
}
view.forward(request, response);
}
}
调度发生在服务器端,而不是客户端。转发基本上告诉 servlet 容器使用哪个视图来呈现结果。它的位置确实没有出现在客户端的浏览器地址栏中。仅当您使用重定向而不是response.sendRedirect()
。重定向基本上告诉网络浏览器在给定位置触发新的 GET 请求。此时浏览器地址栏将更改为新的 URL。
只需隐藏视图(JSP 文件)即可/WEB-INF
文件夹,以便最终用户不再直接访问它,并重用相同的 servlet 通过以下方式显示登录表单doGet()
并继续处理通过以下方式提交的登录表单doPost()
。如果你不实施doGet()
然后它会显示HTTP 状态 405 - 此 URL 不支持 HTTP 方法 GET https://stackoverflow.com/questions/5370633/405-http-method-get-is-not-supported-by-this-url.
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Just show form.
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Process form submit.
// ...
if (success) {
response.sendRedirect("home");
} else {
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
}
}
}
这样你就可以通过以下方式获取登录页面http://example.com/context/login http://example.com/context/login并提交到相同的 URL。
您可以借助单个 servlet 对所有其他 URL 执行相同的操作前控制器模式 https://stackoverflow.com/questions/3541077/design-patterns-web-based-applications/。这只是一点工作,这也是 MVC 框架存在的原因:)
也可以看看:
- 我们的 Servlet wiki 页面 https://stackoverflow.com/tags/servlets/info
- RequestDispatcher.forward() 与 HttpServletResponse.sendRedirect() https://stackoverflow.com/questions/2047122/requestdispatcher-interface-vs-sendredirect/2048640#2048640
- Servlet 中的 doGet 和 doPost https://stackoverflow.com/questions/2349633/doget-and-dopost-in-servlets/
- 基于网络的应用程序设计模式 https://stackoverflow.com/questions/3541077/design-patterns-web-based-applications
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)