JSP login page help needed.

Hi guys,
I have just started learning JSP and implemented login model in my application.

Request all of you to kindly go through the code and suggest any recommendation if required.

Though there is no error while executing the code and getting the login page . I just wanted to know whether the code is written in proper manner or not.

Code:
<%@ page import="java.lang.*" language="java"%>
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>

<%
        //Getting Username and Password from text box
        String username   = request.getParameter("username");
        String password  = request.getParameter("password");

        try
        {
         //Triming Username and Password
         String trim_Username  = username.trim();
         trim_Username= trim_Username.toLowerCase();
         String trim_Password =  password.trim();

         Connection conn=null;
         Statement stmt=null;
         ResultSet rs=null;
         String id  =  null;
         String pin =  null;
         String fullname =null;
         String role =null;

         Class.forName ("oracle.jdbc.driver.OracleDriver");
         conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "lightweight", "oracle");
                            // @machineName:port:SID,   userid,  password

        String sql = "select * from LIGHT_CRED where USERNAME='"+trim_Username+"'";

        stmt = conn.createStatement();
        rs = stmt.executeQuery(sql);

        while( rs.next() )
        {
         //Getting Username,Password,roll,Fullname from Database.
         id=rs.getString(1);
         pin=rs.getString(2);
         role=rs.getString(3);
         fullname=rs.getString(4);
         }

        if(trim_Username.equals(id) && trim_Password.equals(pin))
        {
        out.println("login successful");
        session.setAttribute("user",trim_Username);
        session.setAttribute("fullname",fullname);
        session.setAttribute("role",role);
        response.sendRedirect("cgipage.jsp");
        }
        else
        {
        out.println("incorrect username/password combination");
        }
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
%>
<html>
<body>
<form action=login.jsp method=post>
<p align="center">
Light Weight Manager</p>
<table border="1" width="443" height="80" align=center>
<tr>
                <td height="37" width="177">Username: </td>
                <td height="37" width="180"><input type=text size=20 name=username></td>
                <td height="37" width="64"> </td>
        </tr>
        <tr>
                <td height="35" width="177">Password:  </td>
                <td height="35" width="180"><input type=password size=20 name=password></td>
                <td height="35" width="64">
<input type=submit value="Log In"></td>
        </tr>
</table>
 </p>
 </p>
</form>
</body>
</html>
 
Your logic is almost off the boat .. for any standard MVC model, the JSP is only for the presentation layer and a Servlet for the logic/implementation layer .. in most industry standard solutions, simply show the input in the JSP, and set the form action to "post", and then perform the db validation in a Servlet, preferably a controller servlet, in the respective doPost() ..

Also, never create db connections in a JSP .. JSP's are reprocessed every time its requested from the server. So imagine a scenario where 1000 users login through this page, the server will create 1000 individual connections for 1000 requests which is totally unnecessary .. u should maintain some kind of db pool server side, and any connection/validation should be handled in such a way that the server needs to prepare only the "view" for the client.

There is nothing as "only jsp" web application, so keep this in mind when creating any web application. U must use servlets and jsp and beans to the most you can ...

:cool2:

Here is how i wud have done it (using u're code as reference) :

1st the folder structure :

folderstructure_eclipse.png


the HTML body code :

Code:
<form onSubmit="return validateInput(username.value,password.value)" action="ControlServlet" method="post">

	<p align="center">
Light Weight Manager</p>

		

	<table border="0" width="443" height="80" align="center">

		<tr>

			<td height="35" width="177">Username :</td>

			<td height="35" width="180"><input type="text" size="20" name="username"></td>

			<td height="35" width="64"> </td>

		</tr>

		<tr>

			<td height="35" width="177">Password :</td>

			<td height="35" width="180"><input type="password" size="20" name="password"></td>

		</tr>

		<tr>

			<td height="35" width="54">  

			<input type="submit" value="Log In"></td>

	        </tr>

	</table>

</form>

the input validation script (assuming username must be an email) :

Code:
<script language="javascript">

	function validateInput(username,password) {

		var userexp  = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/g;

			

		if(username=="" || password =="" ) {

		   	alert('Invalid Input');

			return false;

		}

			

		if(!userexp.test(username)){

  			alert('Invalid Username');

  			return false;

		}

  			

		return true;

           }

</script>

the servlet doPost() :

Code:
protected void doPost(final HttpServletRequest request, final HttpServletResponse response)

		 throws ServletException, IOException {

  

          // Perform login validation here using a database connection pool

	  response.getWriter().println(request.getParameter("username")+"
"+request.getParameter("password"));

}

And finally the web.xml mapping :

Code:
<welcome-file-list>

    <welcome-file>index.jsp</welcome-file>

</welcome-file-list>

  

<servlet>

    <description></description>

    <display-name>ControlServlet</display-name>

    <servlet-name>ControlServlet</servlet-name>

    <servlet-class>controller.ControlServlet</servlet-class>

</servlet>

  

<servlet-mapping>

    <servlet-name>ControlServlet</servlet-name>

    <url-pattern>/ControlServlet</url-pattern>

</servlet-mapping>

This is how you should prefer to write any web application, particularly if the web application needs to create database connections. In such case u can use application specific db connection pool or use server specific db connection pool (JNDI is really awesome).

If you look carefully i have reused your code, only segmented it into different files.
 
deathvirus_me said:
For this code i wud like to see u do it plz :) .. the above code wont run anyway .. but still i would like to see sql injection without passing sql parameters in the url ...

@pinga123 : This is a very good read on SQL Injection : SQL Injection (Definition, Examples, Videos, and Prevention)

I m using above code and its running fine. I know its not properly built.

Being a novice to java I would like to begin JSP from scratch .I would like to know which technology should i prefer.

1) Developing web application using netbean.

2) Developing web applications using eclips.

3) Using any other technology.

Please suggest as i m so confused about my next step in building JSP.
 
Running u're code gives me two should-not-be-present "null" in the webpage .. Anyway .. before learning IDE's u must learn about design patterns, they are the utmost basics of web applications ,,

Start with any basic MVC pattern, u can even make u're own custom pattern by simply following the rules. Later on u shud try stuff like Struts and Spring .

From my personal experience, Netbeans is awesome for starters at it makes building and deploying applications for starters easier. But if u know the basics then using Netbeans or Eclipse won't make much of a difference. The built in profiler and debugger of Netbeans is awesome, Eclipse is highly customizable so you can get those things on Eclipse too, but u need to do it manually.

Here are some things u must learn

(i) IDE : Eclipse, coz its more of an industry preference, Netbeans/IntelliJ IDEA for specific stuff (particularly debugggin)

(ii) MVC patterns

(iii) presentation techs like HTML,CSS,Javascript and JQuery for starters

(iv) JEE coding

(v) Connection pooling, Multithreading are some cool features to learn about

(vi) Application servers, Tomcat, Glassfish etc.

(vii) Profiling using simple tools, for starters u shud try JVisualVM.

The list might sound wierd, but google around and look into everything individually, then try some sample apps and you should have no problem. Anything java is easy to learn.

Also remember the most important thing about JSP which most people dont realize : its meant for presenting the data to the user in a usable way, no processing should be in the jsp.

Every web application is a collection of different technology at different layers. SO you must not stick to one. U need atleast the basics of every technology, and then master one layer after another.
 
Well, since you're a beginner, you're doing a pretty good job. But the thing you need to learn next was depicted by the members here.

For basic JSP learning this stuff is OK. And if you want to move ahead of that, just learn Servlet and next go to MVC. If you use MVC design pattern with JSP/Servlets then you can easily get a hang of other frameworks out there.(Like Struts,Spring and Tapestry)

Things you need to learn.

1. MVC

2. SQL Injection (Looks like basic but will kill the application as a whole)

3. Ways to secure the Application

Always use PreparedStatement to execute a query as its much more cleaner that Statement thing.
 
Back
Top