【发布时间】:2016-10-13 03:14:04
【问题描述】:
我有一个 Java Servlet Web 应用程序,一切正常。 然而,有一件小事困扰着我。
当一个人登录时,表单被转发到验证信息的 LoginServlet。验证信息后,用户将被重定向到dashboard.jsp。困扰我的是浏览器中的 URL 显示“http://localhost:8080/LoginServlet.do”而不是“http://localhost:8080/dashboard.jsp”。我正在转发请求和响应对象,所以我需要使用 RequestDispatcher,对吗?
如何确保 URL 读取的是“dashboard.jsp”而不是“LoginServlet.do”?
登录小服务程序:
public class LoginServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*
* Information that has arrived here, has been checked by the login filter.
* This servlet takes the parameters from the form, calls the UserService and tries to login.
* If it succeeds: put the User object in the session scope, and redirect to welcome.jsp with a message 'login successful'
* If it fails: redirect back to index.jsp with a message 'Login failed'
*/
RequestDispatcher rd;
String email = req.getParameter("loginEmail");
String password = req.getParameter("loginPassword");
UserService us = ServiceProvider.getUserService();
User u = us.loginUser(email, password);
if(u != null) {
// User information was correct, login successful.
req.getSession().removeAttribute("loggedUser");
req.getSession().setAttribute("loggedUser", u);
req.setAttribute("message", "Login successful");
u.getAllPomodoros();
rd = req.getRequestDispatcher("dashboard.jsp");
rd.forward(req, resp);
} else {
// Login failed. Redirect to index.jsp
req.setAttribute("message", "Login failed");
rd = req.getRequestDispatcher("index.jsp");
rd.forward(req, resp);
}
}
}
我的 Web.xml(不确定是否相关):
--SNIP--
<servlet>
<servlet-name>Login Servlet</servlet-name>
<servlet-class>controller.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login Servlet</servlet-name>
<url-pattern>/LoginServlet.do</url-pattern>
</servlet-mapping>
--SNIP--
【问题讨论】: