2

I have a Java login application that works and uses a microsoft access database to validate login details. I'm currently in the process of building a java web application and I'm just trying to implement code from my working example.

My problem is that I have 2 input fields here for username and password, (called "name" and "password") But my SQL code which works in the previous example cannot detect the fields on this page called name and password, where the user would input their details respectively.

Any help would be much appreciated!

<%@page import="javax.swing.JOptionPane"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.DriverManager"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Angels & Demons</title>
        <a href="index.jsp">Home Page</a>
        <link rel="stylesheet" type="text/css" href="style.css">
    </head>
    <body>
        <h1><center>Login</center></h1>

<center><form action="login.jsp"> 
<h2>Please make sure to fill all fields! </h2> 
<table> 
<tr><td>User:<input name="name" type="text" size="10"></td></tr> 
<tr><td>Password:<input name="password" size="10"></td></tr> 

<td><input type="submit" value="Submit"></input></td>
</table>   
        </center>




     <%
             if ((request.getParameter("name") != null )
                  && (request.getParameter("password") != null ) 
                )

             {

                Connection conn = null;
                Statement st = null;
                ResultSet rs;


            try{



        String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
        Class.forName(driver);

        String db = "jdbc:odbc:AngelsAndDemons";
        conn = DriverManager.getConnection(db);
        st = conn.createStatement();
        String sql = "select user,pass from AngelsAndDemons where user = '"+name+"'and pass = '"+password+"'";
        rs = st.executeQuery(sql);

               int count = 0;
               while(rs.next())
               {
                   count = count + 1;
               }

           if(count == 1)
           {
               JOptionPane.showMessageDialog(null,"User found, Access Granted!");

           }
           else if(count > 1){
                JOptionPane.showMessageDialog(null,"Duplicte User, Access Denied");
           }
           else{
                JOptionPane.showMessageDialog(null,"User not found");
           }

        }
        catch(Exception ex)
        {
    }  
                    }

            %>


               There was Problem in Login. 
               <%

                 %> 

              }
           </form>     
    </body>
</html>
  • when you submit your form as you have mentioned your action as `login.jsp` hence it will go to that JSP in login . In JSP you should put your `<% %>`. Provide method attribute too. – Vinayak Pingale Jan 24 '14 at 17:30
  • The code above IS login.jsp –  Jan 24 '14 at 17:33
  • You need to go through this [how-to-avoid-java-code-in-jsp-files](http://stackoverflow.com/questions/3177733/how-to-avoid-java-code-in-jsp-files) – Vinoth Krishnan Jan 24 '14 at 17:46
  • Import `javax.swing.JOptionPane` have not sense – Jacek Cz Oct 12 '15 at 08:18
  • Stop pretending to live in a Monkey world. It is significantly better practice to use a servlet (or handler if you use spring) for java code and to use a JSP strictly for display and input. Split this into a servlet to do the login and a jsp to send input and another (possibly the same jsp) to display results. – DwB Jan 10 '16 at 16:29

3 Answers3

0

There are two problems in your code..

1) You want your java code to be executed on button click..so you should check for button click and then write code within it as:

<input type="submit" value="Submit" name="bt"></input></td> //Define a name for button

<%
      if(request.getParameter("bt")!=null)
      {
           if ((request.getParameter("name") != null )
              && (request.getParameter("password") != null ))
           {
                //your code
            }
      }
 %>

2) You have not stored your username and password in any variable and still accessing them in your query by using the name of your text field which is wrong..Save them in a variable and use that variable in the query as :

String name= request.getParameter("name");
String pass= request.getParameter("password");

String sql = "select user,pass from AngelsAndDemons where user = '"+name+"'and pass = '"+pass+"'";
Java Enthusiast
  • 654
  • 7
  • 19
  • I've never checked if a button was actually clicked exept with multiple buttons ... what is important is : is the method (POST, GET, PUT) expected and are the parameters corrects. And I wonder where JOptionPane display will go ... not on browser I assume ! – Serge Ballesta Jun 23 '14 at 13:55
  • @SergeBallesta It's always better to check button click in cases where the form action is on the same page..also from where does `JOptionPane` comes from in this.. – Java Enthusiast Jun 23 '14 at 15:42
  • I prefere testing the method. I find it simpler if I want to call the app as a RESTful web service. And SpringMVC `@RequestMapping` annotated controllers automatically test method for me ... But this is opinion and we should avoid opinions on SO :-) – Serge Ballesta Jun 23 '14 at 15:48
  • @SergeBallesta the things you are talking about is of no concern to this question.. – Java Enthusiast Jun 23 '14 at 15:51
0

Do not concatenate Strings. Used PreparedStatements to avoid SQL injection.

Also avoid storing passwords on String variables. Use char[] when possible, and wipe it after using it, to avoid leaving a cleartext password on memory.

BlueMoon93
  • 2,910
  • 22
  • 39
0

Congrats on trying web server development.

First a corrected version.

<%@page contentType="text/html" pageEncoding="UTF-8"
    import="java.sql.*"
    import="javax.sql.*"%>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Angels & Demons</title>
        <a href="index.jsp">Home Page</a>
        <link rel="stylesheet" type="text/css" href="style.css">
    </head>
    <body>
        <h1><center>Login</center></h1>

     <%
         String name = request.getParameter("name");
         String password = request.getParameter("password");
         if (name == null || password == null) {
    %>

        <center>
        <form action="login.jsp" method="POST"> 
        <h2>Please make sure to fill all fields! </h2> 
        <table> 
        <tr><td>User:<input name="name" type="text" size="10"></td></tr> 
        <tr><td>Password:<input name="password" size="10"></td></tr> 
        <td><input type="submit" value="Submit"></input></td>
        </table>   
        </center>
        </form>     

     <%
         } else {

            String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
            Class.forName(driver);

            String db = "jdbc:odbc:AngelsAndDemons";
            try (Connection conn = DriverManager.getConnection(db)) {
                String sql = "select count(*) from AngelsAndDemons where user = ? and pass = ?";
                try (PreparedStatement st = conn.prepareStatement(sql)) {
                    st.setString(1, user);
                    st.setString(2, password);
                    try (ResultSet rs = st.executeQuery()) {
                        int count = 0;
                        if (rs.next()) {
                            count = rs.getInt(1);
                        }

                        if(count == 1) {
                            %><h2>User found, Access Granted!</2><&
                        } else if(count > 1) {
                            %><h2>Duplicate User, Access Denied</2><&
                        } else {
                            %><h2>Duplicate User, Access Denied</2><&
                        }
                    }
                }
            } catch (Exception ex) {
                            %><h2>There was Problem in Login.</2>
                              <p><%= ex.getMessage() %></p>
                            <&
            }
        }
    %>
    </body>
</html>

With the imports I was a bit lazy and used * - which is bad style.

The page is delivered on a browser request (HTTP GET) back to the browser, the client. No parameters were in the request, so the form is output.

After the form is submitted by the browser, here as HTTP POST request, there are parameters.

Now a database query can be done.

Try-with-resources ensure that all is closed (connection, prepared statement and result set). Even on return/break/exception.

A PreparedStatement takes care of escaping (say a Name with an apostrophe in it). And most important prevents hacking, SQL injection (=creating evil SQL). Like a name admin and password xxx' OR 1=1.

Access was in my time not a multiuser database. You might use a Derby or H2 database.

JOptionPane does not work in an HTML page delivered, or even on creating the page on the server. The alternatives is writing on the result page.

You picked a hard topic with many features. Good luck.

As JSPs get soon ugly, unreadable, try servlets, maybe in combinations, pure servlet for coding and delivering results in a JSP page.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138