Pages

Saturday, September 22, 2012

Simple login tutorial for web application using MySQL

Hey my dear friends. In this post we are going to create simple login application.Before we start check following resources do you have.
  1. Netbeans IDE or you can use any other Java IDE.
  2. JDBC mysql connector - you can download it from here.
  3. MySQL Server - you can download it from here.(Im not here describe how to install MySQL Server and Database creating part)
01. Open Netbeans IDE. File>New Project.

02. Select Java Web under Categories and Web Application under the Projects  and Click Next.

03. Give your Project Name in the Project Name box. In mine SimpleLogin and click Next>Finish.
     Do you have any problem up to now creating new webproject please refer the first four step in
     this post.

04. Create following form in index.jsp.  

<html>
    <head>
    </head>
    <body>
        <form name="loginform" method="post" action="loginbean.jsp">
            <br><br>
            <table align="center"><tr><td><h2>Welcome to School of Java</h2></td></tr></table>
            <table width="300px" align="center" style="border:1px solid #000000;background-color:#FE9A2E;">
                <tr><td colspan=2></td></tr>
                <tr><td colspan=2> </td></tr>
                <tr>
                    <td><b>Login Name</b></td>
                    <td><input type="text" name="userName" value=""></td>
                </tr>
                <tr>
                    <td><b>Password</b></td>
                    <td><input type="password" name="password" value=""></td>
                </tr>
                <tr>
                    <td></td>
                    <td><input type="submit" name="Submit" value="Submit"></td>
                </tr>
                <tr><td colspan=2> </td></tr>
            </table>
        </form>
    </body>
</html>



05. Now right click web pages in your Project(SimpleLogin) and choose New>JSP. Give a filename
      as loginbean and click Finish. In loginbean.jsp edit as follows.

<%@ page language="Java" import="java.sql.*" %>
<html>
    <head><title>School of JAVA</title></head>
    <body>
        <jsp:useBean id="db" scope="request" class="logbean.LoginBean" >
            <jsp:setProperty name="db" property="userName" value="<%=request.getParameter("userName")%>"/>
            <jsp:setProperty name="db" property="password" value="<%=request.getParameter("password")%>"/>
        </jsp:useBean>
        <jsp:forward page="hello">
            <jsp:param name="username" value="<%=db.getUserName()%>" />
            <jsp:param name="password" value="<%=db.getPassword()%>" />
        </jsp:forward>
    </body>
</html>

06. Next right click web pages in your Project an choose New>JSP. Give a  filename as welcome
     and click Finish.  In welcome.jsp edit as follows.

<html>
<head>
<title>Welcome to School of JAVA</title>
</head> 
<body>
<br><br>
        <%
            if (session.getAttribute("username") != null && session.getAttribute("username") != "") {
            String user = session.getAttribute("username").toString();
        %>
        <center><h1>Welcome <b><%= user%></center>
        <%}%>
</body>
<html>

07. Next right click Source Packages in your Project an choose New>Java Package. Give a 
      Package Name as com.schoolofjava.bean and click Finish.



08. Right click on  com.schoolofjava.bean>New>Java Class.Give class name as LoginBean
     and click Finish.Add following codes to LoginBean class.

package com.schoolofjava.bean;

public class LoginBean{

    private String username;
    private String password;

    public String getUserName() {
        return username;
    }

    public void setUserName(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

09. Next right click Source Packages in your Project an choose New>Java Package. Give a 
     Package Name as com.schoolofjava.sql and clickFinish.



10. Right click on  com.schoolofjava.bean>New>Servlet.Give servlert name as Login and click
     Next.Select Add information to deployment descripter(web.xml) and click Finish.Add
     following codes to Login Servlet.


 Add following codes to Login Servlet.

 package com.schoolofjava.sql;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.sql.*;
import java.sql.*;

public class Login extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        System.out.println("MySQL Connect Example.");
        Connection conn = null;
        String url = "jdbc:mysql://localhost:3306/";
        String dbName = "user";
        String driver = "com.mysql.jdbc.Driver";
        String sqlUser = "root";
        String sqlPassword = "sql";

        String username = "";
        String password = "";
        String strQuery = "";
        Statement st = null;
        ResultSet rs = null;
        HttpSession session = request.getSession(true);

        try {
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url + dbName, sqlUser, sqlPassword);
            if (request.getParameter("username") != null && request.getParameter("username") != "" && request.getParameter("password") != null && request.getParameter("password") != "") {
                username = request.getParameter("username").toString();
                password = request.getParameter("password").toString();
                strQuery = "select * from user_info where username='" + username + "' and  password='" + password + "'";
                System.out.println(strQuery);
                st = conn.createStatement();
                rs = st.executeQuery(strQuery);
                int count = 0;
                while (rs.next()) {

                    session.setAttribute("username", rs.getString(2));
                    count++;
                }

                if (count > 0) {
                    response.sendRedirect("welcome.jsp");
                } else {
                    response.sendRedirect("index.jsp");
                }

            } else {
                response.sendRedirect("index.jsp");
            }
            System.out.println("Connected to the DB");
            conn.close();
            System.out.println("Disconnected from DB");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Note: Change the url, dbName, sqlUser, sqlPassword with your Database URL, Database Name, MySQL username and MySQL passwordsetting.
  
10.Right click on Libaries>ADD JAR/Folder give your path to JDBC MySQL connector JAR file.


  
12. Now right click your project and choose Run.Now your Simple Login Application run in your web
     browser.It look like as follows.



 



 I hope this post will be helpful.See you in next post......

1 comment: