有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用POST将参数从JSP发送到Servlet

我正在构建一个简单的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,而不是相反。您是否可以/应该使用请求调度器将POST数据从JSP发送到Servlet?如何从Servlet访问这些参数?(POST是否有一个等效的request.getParameter())

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

对于这个基本的问题,我在网上找到了很多教程,但是没有一个能回答这个问题。多谢各位


共 (5) 个答案

  1. # 1 楼答案

    试试看

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

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

    但它实际上并不比使用GET更“安全”。它们仍以明文形式出现在帖子正文中。如果你想让它安全,请确保使用HTTPS

    编辑

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

    Edit2

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

  2. # 2 楼答案

    尝试重写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);
    }
    
  3. # 3 楼答案

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

    我建议你用doPost()方法代替processRequest()

  4. # 4 楼答案

    重写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请求

  5. # 5 楼答案

    在元素中使用method=“POST”属性