【问题标题】:PreparedStatment not fetching data from MySql using Java Class's Method parametersPreparedStatment 未使用 Java 类的方法参数从 MySql 获取数据
【发布时间】:2012-03-03 23:08:24
【问题描述】:

我试图将用户名和密码从 jsp 页面传递给 Java 类 (LogMeIn.java) 中的 Authenticate Method,但结果是“假”。但是,当我硬编码值(abc/abc)时,我确实得到了“通过”结果。 IE。成功了。

请您告知为什么它不接受通过jsp传递的参数?

--LogMeIn.java--

package org.cms.model;

      import java.sql.Connection;
      import java.sql.ResultSet;
      import java.sql.SQLException;
      import java.sql.Statement;
      import java.sql.PreparedStatement;

      import javax.naming.Context;
      import javax.naming.InitialContext;
      import javax.sql.DataSource;


      public class LogMeIn {


        public boolean Authenticate( String username, String password ) {

          Connection connection = null;
           // Statement statement = null;
            ResultSet resultSet = null;
            PreparedStatement pst = null;
            String query;
            boolean result = false;

            try {
              Context initCtx = new InitialContext();
              Context envCtx = (Context) initCtx.lookup("java:comp/env");
              DataSource ds = (DataSource) envCtx.lookup("jdbc/TestDB");
              connection = ds.getConnection();
                //statement = connection.createStatement();

                query = "select name from account where name= ? and password = ?";

                pst = connection.prepareStatement(query);

                pst.setString(1, username);
                pst.setString(2, password);

                resultSet = pst.executeQuery();

                int count=0;

                if(resultSet.next())
                {
               count++;
                }
                if(count>0)
                {
                  result = true;
                }
                else
                {
                  result = false;
                }
            }

            catch (SQLException e){
              e.printStackTrace();
            }
            catch (Exception e){
              e.printStackTrace();
            }
            finally {
                if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}
                if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
            }

          return result;
        }

      }

---LoginServlet---

    package org.cms.controller;

    import java.io.IOException;

    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import org.cms.model.LogMeIn;

    /**
     * Servlet implementation class LoginServlet
     */
    @WebServlet("/LoginServlet")
    public class LoginServlet extends HttpServlet {
      private static final long serialVersionUID = 1L;

      /**
       * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
       */
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username;
        String password;

        username = request.getParameter("user");
        password = request.getParameter("pass");

        LogMeIn a = new LogMeIn();

        boolean result = a.Authenticate(username, password);
            System.out.println(result);
        if (result) {
          request.setAttribute("loginresult","Pass");
          RequestDispatcher dispatcher = request.getRequestDispatcher("Login.jsp");
          dispatcher.forward(request, response);
          }
        else {
          request.setAttribute("loginresult","Failed");
          RequestDispatcher dispatcher = request.getRequestDispatcher("Login.jsp");
          dispatcher.forward(request, response);
          }

      }

    }

---Login.jsp---

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
        <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"  %>  
        <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <title>Login</title>

    <link rel="stylesheet" href="css/style.css" type="text/css"></link>

    <script language="JavaScript" type="text/JavaScript" src="validate.js"> </script>

    </head>
    <body>

    <form enctype="multipart/form-data" onSubmit="return validate(this)" method="post" action="LoginServlet" class="form">
      <table border = "0">
      <tr align="left" valign="top">
      <td>User Name:</td>
      <td><input type="text" name ="user" class="inputbox"/></td>
      </tr>
      <tr align="left" valign="top">
      <td>Password:</td>
        <td><input type="password" name ="pass" class="inputbox" /></td>
      </tr>
      <tr align="left" valign="top">
      <td></td>
      <td><input type="submit" name="submit" 
      value="submit" class="fb8"/></td>
      </tr>
      </table>
      <c:out  value="${loginresult}" > </c:out>

    </form>
    </body>
    </html>

非常感谢

【问题讨论】:

  • JSP 向 LogMeIn 传递哪些参数?您是否将它们打印到控制台?
  • validate() 是做什么的?
  • 旁注:LogMeIn 中的 catch 块之前的最后 12 行可以减少到 result = resultSet.next();
  • 您可能需要将它们用引号或类似的东西括起来。
  • 特别感谢各位 DNA! Validate() 正在查看一个不存在的 javascript 文件。问题是由于 Validate() 方法而将空参数传递给 servlet。 JB Nizet - 感谢您的建议,我已经在我的代码中进行了更改。你能把这个作为答案吗?

标签: java jsp jdbc


【解决方案1】:

使用 setAttribute() 方法。此方法设置请求的属性值,稍后在 servlet 中通过将请求对象传递给调度程序方法来检索该属性值。属性的设置值由请求对象的getAttribute()方法获取。

   http://www.roseindia.net/servlets/request-parameter.shtml

 http://www.roseindia.net/tutorial/servlet/passParameters.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-19
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 2016-10-05
    相关资源
    最近更新 更多