Prepared Statement不使用Java Class的Method参数从MySql获取数据

时间:2012-03-03 23:08:25

标签: java jsp jdbc

我正在尝试将用户名和密码从jsp页面传递到Java类(LogMeIn.java)中的Authenticate Method,但结果是我得到'false'。但是当我硬编码值(abc / abc)时,我会得到'pass'结果。即。它很成功。

请问你为什么不接受通过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>

非常感谢

1 个答案:

答案 0 :(得分:0)

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

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

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