0

我正在构建一个简单的 Web 应用程序并尝试创建一个登录页面。该页面由一个 JSP 和一个加载 Servlet 的表单组成。

我已经使用 GET 方法使表单工作:

JSP 看起来像这样:

<form method="get" action="Login">
Email:<input name="email"/>
Password:<input name="password"/>
<input type="Submit" value="Log in"/>

在 Servlet 中:

@WebServlet(name = "Login", urlPatterns = {"/Login"})
public class Login extends HttpServlet {

/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");

//Assign variables from the request parameters
String loginFormEmail = request.getParameter("email");
String loginFormPassword = request.getParameter("password");

此代码有效,但它在 URL 字符串中包含用户名和密码,因此这显然不是一个好习惯。我曾尝试使用 POST 来执行此操作,但我遇到了错误。(HTTP 状态 405 - 此 URL 不支持 HTTP 方法 POST)

我需要知道如何使用 POST 将参数从 JSP 发送到 Servlet。我认为这可能涉及使用 RequestDispatcher 对象,但我发现的所有教程都解释了使用 RequestDispatcher 将数据从 Servlet 发送到 JSP,而不是相反。您可以/应该使用 Request Dispatcher 将 POST 数据从 JSP 发送到 Servlet 吗?以及如何从 Servlet 访问这些参数?(对于 POST 是否有等效的 request.getParameter() ?)

我知道使用 POST 仍然不安全,但它比在查询字符串中包含密码要好得多,我稍后会考虑安全性。

为基本问题道歉,我在网上找到了很多教程,但似乎没有一个能回答这个具体问题。谢谢你。

4

5 回答 5

4

尝试

<form method="POST" action="Login>

注意:method而不是type用于指定 GET/POST。

但它实际上并不比使用 GET 更“安全”。它们仍然在帖子正文中以明文形式提供。如果您希望它是安全的,请确保使用 HTTPS。

编辑

您现在已经编辑了您的问题,看来您使用的是method,而不是type。因此,如果在将其更改为 后仍然有错误POST,请指定您遇到的错误。

编辑2

您指定您收到HTTP method POST is not supported by this URL错误。这意味着您的 servlet 不接受该POST方法。这很可能意味着您正在继承一些只接受GET. 查看 servlet 的所有代码会很有帮助。

于 2013-05-21T12:58:12.333 回答
0
<form type="get" action="Login" method="POST">
 Email:<input name="email"/>
 Password:<input name="password"/>
<input type="Submit" value="Log in"/>

我建议你而不是processRequest(), 使用doPost()方法。

于 2013-05-21T12:59:47.670 回答
0

覆盖类中的HttpServlet#doPost()方法Login

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    String loginFormEmail = request.getParameter("email");
    String loginFormPassword = request.getParameter("password");
    // do something to produce a response
}

这可能需要您更改service()可能被覆盖的方法以调用您的processRequest()方法,而不管 HTTP 方法如何。这取决于Login您未显示的其他类实现。

然后更改您<form>POST请求。

于 2013-05-21T16:21:36.893 回答
0

在你的元素中使用 method="POST" 属性

于 2013-05-21T13:00:21.487 回答
0

尝试覆盖 HttpServlet 方法 doPost() 和 doGet():

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException,IOException {
    processRequest(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException,IOException {
    processRequest(request,response);
}
于 2016-03-29T13:23:21.513 回答