PreparedStatment не извлекает данные из MySql с использованием параметров метода класса Java - PullRequest
0 голосов
/ 04 марта 2012

Я пытаюсь передать имя пользователя и пароль со страницы jsp методу аутентификации в Java-классе (LogMeIn.java), но в результате получаю «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 голосов
/ 04 марта 2012

использовать метод setAttribute (). Этот метод устанавливает значение атрибута для запроса, который позже извлекается в сервлете путем передачи объекта запроса через метод диспетчера. Заданное значение атрибута извлекается методом getAttribute () объекта запроса.

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

 http://www.roseindia.net/tutorial/servlet/passParameters.html
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...