Thursday, 20 October 2011

Struts Login Application with JDBC connection


********Just create as Dynamic web project in eclipse and run using tomcat server*********

1. add lib, tld  folder and web.xml, struts-config.xml inside WEB-INF
2.index.jsp , homepage.jsp, userUnlog.jsp
3. <%@taglib uri="/WEB-INF/tld/struts/struts-html.tld" prefix="html" %>  in welcome.jsp
4. LoginForm, LoginAction, Loginservice, LoginServiceImpl



Folder Structure of StrutsApplication
LoginApplication
*src
----com.action -> LoginAction.java
----com.form   -> LoginForm.java
----com.service -> LoginService.java
                 -> LoginServiceImpl.java
*webcontent
----WEB-INF
-> lib
          -->> antlr.jar, commons-beanutils, coms-digester,
           coms-fileupload, coms-logging, coms-validator,
                   jakarta-oro, jstl, ojdbc14, standard, struts.jar, struts-el.jar
-> tld --->> struts
             ---->>> struts-html.tld
             ---->>> struts-logic.tld
-> struts-config.xml
-> web.xml
----homepage.jsp
----index.jsp
----userUnlog.jsp


**********  web.xml **************

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">

<display-name>StrutsApplication1</display-name>

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

<servlet>
<servlet-name>actionServlet</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>actionServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

<session-config>
<session-timeout>120</session-timeout>
</session-config>

<jsp-config>
<taglib>
<taglib-uri>http://jakarta.apache.org/struts/tags-html</taglib-uri>
<taglib-location>/WEB-INF/tld/struts/struts-html.tld</taglib-location>
</taglib>

<taglib>
<taglib-uri>http://jakarta.apache.org/struts/tags-logic</taglib-uri>
<taglib-location>/WEB-INF/tld/struts/struts-logic.tld</taglib-location>
</taglib>
</jsp-config>
</web-app>

**********  struts-config.xml **************

<?xml version="1.0" encoding="UTF-8"?>
<!-- ?xml version="1.0" encoding="ISO-8859-1" ?-->

<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
          "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">

<struts-config>
<form-beans>
<form-bean name="LoginForm" type="com.form.LoginForm" />
</form-beans>

<action-mappings>
<action input="/index.jsp" name="LoginForm" path="/Login"
scope="session" type="com.action.LoginAction">
<forward name="SUCCESS" path="/homepage.jsp" />
<forward name="FAILURE" path="/userUnlog.jsp" />
</action>
</action-mappings>
</struts-config>

**********  LoginForm.java**************

package com.form;
import org.apache.struts.action.ActionForm;
public class LoginForm extends ActionForm{
private static final long serialVersionUID = 1L;
String userName;
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;
}
}

**********  LoginService.java**************

package com.service;
import java.util.List;
public interface LoginService {
public boolean userValidation(String username, String userpass);
}


**********  LoginServiceImpl.java**************

package com.service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import com.form.LoginForm;
public class LoginServiceImpl implements LoginService {
public boolean userValidation(String username, String userpass){

System.out.println("Username & password : " + username + " " + userpass);
String strQuery= "";
        boolean validUser = false;
try {
Class.forName("oracle.jdbc.OracleDriver");
Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "db_username", "db_password");
Statement statement = connection.createStatement();
strQuery="select * from user_table where username='"+username+"' and  password='"+userpass+"'";
System.out.println(strQuery);  

ResultSet rs = statement.executeQuery(strQuery);
rs = statement.executeQuery(strQuery);
System.out.println("Result : " + rs);
            boolean more = rs.next();

            if (!more) {
            validUser = false;
      }else if (more) {
            validUser = true;
            }
}catch (Exception ex) {
            System.out.println("Log In failed: An Exception has occurred! " + ex);
}
return validUser;
}
}

**********  LoginAction.java**************

 package com.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.form.LoginForm;
import com.service.LoginService;
import com.service.LoginServiceImpl;
public class LoginAction extends Action {
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {

LoginForm loginForm = (LoginForm) form;
String username = loginForm.getUserName();
String password = loginForm.getPassword();

HttpSession session = request.getSession(true);
session.setAttribute("currentSessionUser", username);

LoginService loginService = new LoginServiceImpl();
boolean isValidUser = loginService.userValidation(username, password);

if (isValidUser) {
return mapping.findForward("SUCCESS");
} else {
return mapping.findForward("FAILURE");
}
}
}


**********  index.jsp **************

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@taglib uri="/WEB-INF/tld/struts/struts-html.tld" prefix="html" %>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Struts Example</title>
</head>
<body>
<center>
<html:form action="/Login" method="post">
        User Name :<html:text property="userName" /><br>
        Password  :<html:password property="password" /><br>
        <html:submit value="Login" />
    </html:form>
    </center>
</body>
</html>


**********  homepage.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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1256">
<title> User Logged Successfully </title>
</head>
<body>
<center>
<% String user = (String)session.getAttribute("currentSessionUser"); %>
Welcome <%= user %> !!
</center>
</body>
</html>


**********  userUnlog.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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Invalid user</title>
</head>
<body>
<center>
Sorry, you are not a registered user! Please sign up first..
</center>
</body>
</html>

************************************************************************

Simple Servlet login application with jdbc connection



************** index.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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="LoginServlet">
Please enter your username <input type="text" name="un"/><br>
Please enter your password <input type="password" name="pw"/>
<input type="submit" value="submit">
</form>
</body>
</html>

***************** LoginServlet.java ******************

package login;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
     
    public LoginServlet() {
        super();
    }

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out = response.getWriter();

 String username = request.getParameter("un");
 String userpass = request.getParameter("pw");
 String strQuery= "";

 try {
 Class.forName("oracle.jdbc.OracleDriver");

 Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "photonmail", "photonmail");
 Statement statement = connection.createStatement();

 strQuery="select * from user_table where username='"+username+"' and  password='"+userpass+"'";
 
 ResultSet rs = statement.executeQuery(strQuery);
 rs = statement.executeQuery(strQuery);
 System.out.println("Result : " + rs);

          boolean more = rs.next();
           // check user is valid
           if (!more) {
               System.out.println("Sorry, you are not a registered user! Please sign up first");
               out.println(" Sorry, register first!");
           }
           else if (more) {
            out.println("Welcome " + username);
           }

 } catch (ClassNotFoundException e) {
e.printStackTrace();
 } catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}

}

************** web.xml ****************

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>StrutsApplication1</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>LoginServlet</display-name>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>login.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
  </servlet-mapping>
</web-app>
*************************

Monday, 12 September 2011

Reverse the String


public class ReverseString {
    public static void main(String[] args) {
        System.out.println("ReverseString\n");
        String revString = new String();
        revString = "Mathematics";
        char[] chrArray = revString.toCharArray();
       
        for(int i = chrArray.length-1 ; i >=0 ; i--){
            System.out.print(chrArray[i]);
        }
    }
}

Count the Pattern in a String

Ex:
string : My first example to count pattern in my Java using my eclipse.
pattern : my
count : 3

public class PatternMatching {
     public static void main(String args[]) {
          String myString = "My first example to count pattern in                          my Java using my eclipse.";
          char[] chararr = myString.toLowerCase().toCharArray();
          // without predefined function
          findMatch(chararr);
          split();
     }

  private static void findMatch(char[] chararr) {

     String pattern = "my";
     char[] patternArr = pattern.toLowerCase().toCharArray();
     int patternArrlen = patternArr.length;
     int f = 0;
     for (int k = 0; k < chararr.length; k++) {
          int j = 0;
          for (int z = 0; z < patternArrlen; z++) {
               if (patternArr[z] == chararr[k]) {
                    j = j + 1;
                    k = k + 1;
                    if (j == patternArrlen) {
                         f = f + 1;
                    }
               }
          }
     }
     System.out.println(f);
  }

  static void split() {
     String myString = "This is my first prgm to my pattern count in my java.";
     String pattern = "my";
     String[] seperateWords = myString.split(" ");
     int i = 0;
     for (int j = 0; j < seperateWords.length; j++) {
          if (seperateWords[j].equalsIgnoreCase(pattern)) {
               i++;
          }
     }
     System.out.println(i);
   }
}


Tuesday, 6 September 2011

Number of Occurances of a variable in an array


public class OccurancesInArray {

    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("How many elements you want to enter in the array: ");
        int num = 0;
        try {
            num = Integer.parseInt(in.readLine());
        } catch (NumberFormatException ne) {
            System.out.println(ne.getMessage() + " is not a number!");
            System.exit(0);
        }
        String[] elements = new String[num];
        int a;
        int k;
        for (int i = 0; i < num; i++) {
            elements[i] = in.readLine();
        }
        for (int i = 0; i < elements.length; i++) {
            a = 0;
            k = 1;
            for (int j = 0; j < elements.length; j++) {
                if (j >= i) {
                    if (elements[i].equals(elements[j]) && j != i) {
                        k++;
                    }
                } else if (elements[i].equals(elements[j])) {
                    a = 1;
                }
            }
            if (a != 1) {
                System.out.println("Occurance of \'" + elements[i] + "\' : " + k);
            }
        }
    }
}

Friday, 22 July 2011

Program for the below pattern without using 'for' loop

0
10
010
1010
01010

public class Design1 {

    private static int printNumber(int data) {
        System.out.print(data % 2);
        return data > 0 ? printNumber(data - 1) : 0;
    }
    private static int iterate(int noOfRows) {
        int currentnoOfRows = noOfRows > 0 ? iterate(noOfRows - 1) : 0;
        System.out.println();
        return printNumber(noOfRows);
    }
    public static void main(String[] args) {
        iterate(10);
        System.out.println();
    }
}

Divide two numbers without slash

public class Division {

    public static void main(String[] args) {
        int number1 = 10;
        int number2 = 3;
        int count = 0;
        while(number1 > number2) {
          number1 = number1 - number2;
          count++;
        }
        System.out.println(count);
    }
}

Tuesday, 19 July 2011

Subtract Two numbers without minus

public class Subtraction {

    public static void main(String[] args) {
       int number1 = 10;
       int number2 = 1;

       int result = ~(~number1+number2);
        System.out.println(result);
    }
}

Second Biggest Number

public class SecondMaximum {

    public static void main(String arg[]) throws Exception {
        int[] numbers = {87, 900, 500, 400, 700, 600, 300, 200,};
       
        int max = getMaxValue(numbers);
        System.out.println("Second Max number : "+ max);
    }

    public static int getMaxValue(int[] numbers) {
        int firstMax = numbers[0];
        int secondMax = 0;
        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] > firstMax) {
                firstMax = numbers[i];
            }
            else if(numbers[i] > secondMax && numbers[i] != firstMax){
                secondMax = numbers[i];
            }
        }
        return secondMax;
    }
}