Struts JDBC Task

  • As we have Done Task in Servlet JSP with jdbc (for database connectivity, operations we will use hibernate)

  • Instead of Servlet Classes we use our own Action Classes for Processing data and operations.

  • we will design this task with Layered Structure(i.e. service, Dao)

  • For Database operation we will use Hibernate instead of JDBC. You should know basic of hibernate before designing this Task.

  • Project Structure (in My Eclipse)
Java By Kiran

Flow of Application:
Java By Kiran

Database Requirements –

1) Software : Mysql Server
2) Create one table in Test Schema as Following for Storing user information –
User_id, Firstname, Lastname, Gender, Mobile_no, Username, Password



CREATE TABLE  `test`.`user1` (
`User_id` int(10) unsigned NOT NULL auto_increment,
` Firstname ` varchar(45) NOT NULL,
` Lastname ` varchar(45) NOT NULL,
` Gender ` varchar(45) default NULL,
` Mobile_no ` varchar(45) default NULL,
`, Username ` varchar(45) default NULL,
`Password` varchar(45) default NULL,

) ENGINE=InnoDB DEFAULT CHARSET=latin1;


Programs

1. User.java(pojo class for table):


package com.pojo;

public class User {
	int userid;

	String fname;

	String lname;

	String gender;

	String mobileno;

	String username;

	String password;

	public String getFname() {
		return fname;
	}

	public void setFname(String fname) {
		this.fname = fname;
	}

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public String getLname() {
		return lname;
	}

	public void setLname(String lname) {
		this.lname = lname;
	}

	public String getMobileno() {
		return mobileno;
	}

	public void setMobileno(String mobileno) {
		this.mobileno = mobileno;
	}

	public String getPassword() {
		return password;
	}

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

	public int getUserid() {
		return userid;
	}

	public void setUserid(int userid) {
		this.userid = userid;
	}

	public String getUsername() {
		return username;
	}

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

}


2.login.jsp:

< % @taglib prefix="s" uri="/struts-tags"% >
< html >
	< h2 >
		Login Application
	< / h2 >
	< s:form action="login.action" >

		< s:textfield label="Username" name="u.username" > < / s:textfield >
		< s:textfield label="Password" name="u.password" > < / s:textfield >
		< s:submit value="login" > < / s:submit >

	< / s:form >
	< s:a href="register.jsp" > Register Here < / s:a >
< / html >


Java By Kiran

3.Register.jsp:


< %@taglib prefix="s" uri="/struts-tags"% >
< s:form action="register" >
	< s:textfield label="Fisrtname" name="u.fname" > < / s:textfield >
	< s:textfield label="Lastname" name="u.lname" > < / s:textfield >
	< s:radio label="Gender" list="{'male','female'}"  name="u.gender" > < / s:radio >
	< s:textfield label="Mobileno" name="u.mobileno" > < / s:textfield >
	< s:textfield label="Username" name="u.username" > < / s:textfield >
	< s:textfield label="Password" name="u.password" > < / s:textfield >
	< s:submit value="Register" > < / s:submit >
< / s:form >


Java By Kiran

4.web.xml:


< ? xml version="1.0" encoding="UTF-8"?>
< web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
	xmlns:xsi=" http: //www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http:// java.sun.com/xml/ns/j2ee 
	http:// java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	< welcome-file-list >
		< welcome-file>login.jsp
	< / welcome-file-lis t>
	< filter >
		< filter-name>f1
		< filter-class >
			org.apache.struts2.dispatcher.FilterDispatcher
		< / filter-class >
	< / filter >
	< filter-mapping >
		< filter-name > f1 < / filter-name >
		< url-pattern > /* < / url-pattern >
	< / filter-mapping >

< / web-app >


5. struts.xml:


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

	< package name="mypackage" extends="struts-default" >
		< action name="register" class="com.coral.action.UserAction"
			method="addUser" >
			< result name="success" > login.jsp < / result >
			< result name="error" > error.jsp < / result >
		< / action >
		< action name="login" class="com.coral.action.LoginAction"
			method="logincheck" >
			< result name="success" > success.jsp < / result >
			< result name="error" > logout.jsp < / result >
		< / action >
		< action name="addPage" >
			< result > add.jsp < / result >
		< / action >
		< action name="add" class="com.coral.action.UserAction"
			method="addUser" >
			< result name="success" > success.jsp < / result >
			< result name="error" > error.jsp < / result >
		< / action >
		< action name="edit" class="com.coral.action.UserAction"
			method="editUser" >
			< result name="success" > edit.jsp < / result >
			< result name="error" > error.jsp < / result >
		< / action >
		< action name="update" class="com.coral.action.UserAction"
			method="updateUser" >

			< result name="success" > success.jsp < / result >
			< result name="error" > error.jsp < / result >

		< / action >

		< action name="delete" class="com.coral.action.UserAction"
			method="deleteUser" >

			< result name="success" > success.jsp < / result >
			< result name="error" > error.jsp < / result >

		< / action >

		< action name="logout" class="com.coral.action.LoginAction"
			method="logOut" >
			< result name="success" > login.jsp < / result >
		< / action >
	< / package >



6.LoginAction.java:


package com.coral.action;

import java.util.ArrayList;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import com.coral.dao.LoginDao;
import com.coral.service.LoginService;
import com.coral.service.UserService;
import com.opensymphony.xwork2.ActionSupport;
import com.pojo.User;

public class LoginAction extends ActionSupport {
	private String status;

	private String msg;

	private User u;

	ArrayList ulist = new ArrayList();

	public String logincheck() throws Exception {

		LoginService logser = new LoginService();
		System.out.println("we are in login check");
		String str = logser.logincheck(u);

		if (str == "success") {
			ulist = logser.getUserservice();
			HttpSession hs = ServletActionContext.getRequest().getSession();
			if (!hs.isNew()) {
				hs.invalidate();
				hs = ServletActionContext.getRequest().getSession();
				System.out.println(hs.isNew());
			}
			hs.setAttribute("login", "true");
			return "success";
		} else {
			return "error";
		}

	}

	public String logOut() {
		HttpSession hs = ServletActionContext.getRequest().getSession(false);
		if (hs != null)
			hs.invalidate();
		return "success";
	}

	public User getU() {
		return u;
	}

	public void setU(User u) {
		this.u = u;
	}

	public ArrayList getUlist() {
		return ulist;
	}

	public void setUlist(ArrayList ulist) {
		this.ulist = ulist;
	}

}


7. LoginDao.java:


package com.coral.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

import com.coral.db.DbutilDao;
import com.pojo.User;

public class LoginDao {

	String username;

	String password;

	public String getUserdata(User u) throws Exception {
		Connection con = DbutilDao.getConnection();
		Statement stmt = DbutilDao.createStatement(con);

		String username = u.getUsername();

		String password = u.getPassword();

		String sql = "select * from user1 where username='" + username
				+ "' and password='" + password + "'";

		ResultSet rs = DbutilDao.executeQuery(stmt, sql);
		System.out.println(rs);

		while (rs.next()) {

			return "success";

		}
		return "error";
	}
	public ArrayList getServiceDao() {

		ArrayList ulist = new ArrayList();

		Connection con;
		try {
			con = DbutilDao.getConnection();

		Statement stmt = DbutilDao.createStatement(con);
			String sql = "select * from user1 ";
			ResultSet rs = DbutilDao.executeQuery(stmt, sql);

			while (rs.next()) {

				User u = new User();
				u.setUserid(rs.getInt("User_id"));
				u.setFname(rs.getString("Firstname"));
				u.setLname(rs.getString("Lastname"));
				u.setGender(rs.getString("Gender"));
				u.setMobileno(rs.getString("Mobile_no"));
				u.setUsername(rs.getString("Username"));
				u.setPassword(rs.getString("Password"));
				ulist.add(u);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return ulist;
	}

	public String loginCheckDao(User u) throws Exception {
		Connection con = DbutilDao.getConnection();
		Statement stmt = DbutilDao.createStatement(con);
		ArrayList ulist = new ArrayList();
		String username = u.getUsername();
		System.out.println(username);
		String password = u.getPassword();
		System.out.println(password);

		String sql = "select * from user1 where username='" + username
				+ "' and password='" + password + "'";

		ResultSet rs = stmt.executeQuery(sql);
		System.out.println(rs);

		if (rs.next()) {

			return "success";

		} else {
			return "error";
		}
	}
}


8.Dbutildao.java


package com.coral.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DbutilDao {

	public static Connection getConnection() throws Exception {
		Connection con = null;
		try {

			Class.forName("com.mysql.jdbc.Driver");
             con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");			
			
		} catch (ClassNotFoundException e) {

			e.printStackTrace();

		} catch (SQLException e) {

			e.printStackTrace();
		}
		return con;
	}

	/*
	 * To create the statement.
	 */

	public static Statement createStatement(Connection con) {
		Statement stmt = null;
		try {
			stmt = con.createStatement();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return stmt;
	}
	public static ResultSet executeQuery(Statement stmt, String sql) {
		ResultSet result = null;
		try {
			result = stmt.executeQuery(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}

	/*
	 * To close the connection.
	 */
	public static void closeConnection(Connection con) {
		try {
			con.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		
		try {
			DbutilDao.getConnection().createStatement();
		} catch (Exception e) {
			
			e.printStackTrace();
		}	
	}
}


9.success.jsp:


< %@ page language="java" contentType="text/ html; charset = ISO-8859-1"
pageEncoding="ISO-8859-1"%>
< % @ taglib prefix="s" uri="/struts-tags"%>
< ! DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" >
< html >
< script type="text/javascript" >
function func(id){
alert(id.value);
}
< / script >
< body >
< h3 align="right" >
< s:a href="logout.action" > Logout < / s:a >
< / h3 >
< hr >
< br >
< center >


< table border="1" cellspacing="0" cellpadding="5" >
< thead >
< tr >
< th >
Select
< / th >
< th >
Fname
< / th >
< th >
Lname
< / th >
< th >
Gender
< / th >
< th >
Mobile
< / th >
< th >
Username
< / th >
< th >
Password
< / th >
< / tr >
< / thead >
< tbody >

< tr >
< td >
< input type="radio" name="u.userid"
value=" < s:property value="userid" / > " id="rd"
onclick="func(this)">
< / td >
< td >
< s:property value="fname" / >
< / td >
< td >
< s:property value="lname" / >
< / td >
< td >
< s:property value="gender" / >
< / td >
< td >
< s:property value="mobileno" / >
< / td >
< td >

< / td >
< td >
< s:property value="password" / >
< / td >
< / tr >
< /s:iterator >
      < / tbody >
< / table >
< br >
< s:submit value="ADD" action="addPage" / >
< s:submit value="DELETE" action="delete" / >
< s:submit value="EDIT" action="edit" / >
< / s:form >
< br >
< s:property value="msg" / >
< / center>
< / body >
< / html >


Java By Kiran

10. add.jsp:


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

			< s:form action="add" >
	< s:textfield label="First Name" name="u.fname" required="true" />
	< s:textfield label="Last Name" name="u.lname" required="true" />
	< s:radio list="{'male','female'}" label="Gender" name="u.gender" />
	< s:textfield label="Mobile" name="u. mobileno" />
	< s:textfield label="User Name" name="u.username" required="true" />
	< s:textfield label="Password" name="u.password" required="true" />
				< s:submit value="Register" />
			< /s:form >
		< / center >
	< / body >
< / html >


Java By Kiran

11.UserAction.java:


package com.coral.action;

import java.util.ArrayList;

import com.coral.service.LoginService;
import com.coral.service.UserService;
import com.pojo.User;

public class UserAction {

	User u;

	String str;

	String status;

	ArrayList ulist;

	public UserAction() {
		System.out.println("we are in the useraction");
	}

	public String registerUser() throws Exception {

		UserService us = new UserService();
		String str = us.registerService(u);

		if (str == "success") {
			return str;

		} else {
			return "error";
		}
	}

	public String addUser() throws Exception {

		UserService us = new UserService();

		String status = us.registerService(u);
		if (status == "error") {

			return status;
		} else {

			ulist = new UserService().getService();
			System.out.println(ulist);
			return "success";
		}
	}

	public String editUser() throws Exception {

		u = new UserService().editService(u);
		if (u != null)
			return "success";
		else
			return "error";
	}

	public String updateUser() throws Exception {

		status = new UserService().updateService(u);
		if (status.equals("success")) {
			System.out.println("Successfully updated...");
			ulist = new UserService().getUsersService();
		}
		return status;

	}

	public String deleteUser() throws Exception {
		status = new UserService().delService(u);
		if (status.equals("success")) {
			System.out.println("Successfully deleted...");
			ulist = new UserService().getService();
		}
		return status;
	}

	public User getU() {
		return u;
	}

	public void setU(User u) {
		this.u = u;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public ArrayList getUlist() {
		return ulist;
	}

	public void setUlist(ArrayList ulist) {
		this.ulist = ulist;
	}
}



12.UserService


package com.coral.service;

import java.util.ArrayList;
import java.util.List;

import com.coral.dao.LoginDao;
import com.coral.dao.UserDao;
import com.coral.db.DbutilDao;

import com.pojo.User;

public class UserService {

	User u;

	UserDao ud = new UserDao();

	DbutilDao db = new DbutilDao();

	String status;

	public String registerService(User u1) throws Exception {

		UserDao us = new UserDao();

		 status=us.insertdata(u1);

		return "success";
	}

	public String addService(User u) throws Exception {

		UserDao ud = new UserDao();
		ud.addDao(u);

		return "success";
	}
public String addService1(User u) throws Exception{
		
		
		return(new UserDao().addDao1(u));
	}
	

	public ArrayList getService() {

		ArrayList ulist = new ArrayList();
		LoginDao ld = new LoginDao();
		ulist = ld.getServiceDao();

		return ulist;
	}

	public User editService(User u) throws Exception {
		return (new UserDao().editUserDao(u));
	}

	public String updateService(User u) throws Exception {

		return (new UserDao().updateUserDao(u));
	}

	public ArrayList getUsersService() {

		return (new UserDao().getUsersDao());
	}

	public String delService(User user) throws Exception {

		return (new UserDao().delUserDao(user));
	}

}


13. UserDao.java:


package com.coral.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.coral.db.DbutilDao;
import com.pojo.User;

public class UserDao {

	User u;

	public String insertdata(User u1) throws Exception {
		Connection con = DbutilDao.getConnection();
		Statement stmt = DbutilDao.createStatement(con);
		String fname = u1.getFname();

		String lname = u1.getLname();

		String gender = u1.getGender();

		String mobileno = u1.getMobileno();

		String username = u1.getUsername();

		String password = u1.getPassword();

		String sql = "insert into user1(Firstname,Lastname,Gender,Mobile_no,Username,Password) values('"
				+ fname
				+ "','"
				+ lname
				+ "','"
				+ gender
				+ "','"
				+ mobileno
				+ "','" + username + "','" + password + "')";
		stmt.executeUpdate(sql);
		return "success";
	}

	public String addDao1(User u) throws Exception {

		Connection con = DbutilDao.getConnection();
		Statement stmt = DbutilDao.createStatement(con);
		String fname = u.getFname();

		String lname = u.getLname();

		String gender = u.getGender();

		String mobileno = u.getMobileno();

		String username = u.getUsername();

		String password = u.getPassword();

		String sql = "insert into user1(Firstname,Lastname,Gender,Mobile_no,Username,Password) values('"
				+ fname
				+ "','"
				+ lname
				+ "','"
				+ gender
				+ "','"
				+ mobileno
				+ "','" + username + "','" + password + "')";
		stmt.executeUpdate(sql);
		return "success";
	}

	public String updateUserDao(User u) throws Exception {
		Connection con = DbutilDao.getConnection();
		Statement stmt = DbutilDao.createStatement(con);

		int id = u.getUserid();

		String fname = u.getFname();
		String lname = u.getLname();
		String gender = u.getGender();
		String mobileno = u.getMobileno();
		String username = u.getUsername();
		String password = u.getPassword();

		String sql = "update user1 set Firstname='" + fname + "',Lastname='"
				+ lname + "',Gender='" + gender + "',Mobile_no='" + mobileno
				+ "',Username='" + username + "', Password='" + password
				+ "'  where User_id='" + id + "'";
		stmt.executeUpdate(sql);
		return "success";

	}

	public int addDao(User user) throws Exception {
		Connection con = DbutilDao.getConnection();
		Statement stmt = DbutilDao.createStatement(con);
		User u = new User();

		String fname = u.getFname();
		System.out.println(fname);
		String lname = u.getLname();
		System.out.println(lname);
		String gender = u.getGender();
		System.out.println(gender);
		String mobileno = u.getMobileno();
		System.out.println(mobileno);
		String username = u.getUsername();
		System.out.println(username);
		String password = u.getPassword();
		System.out.println(password);

		String sql = "insert into user1(Firstname,Lastname,Gender,Mobile_no,Username,Password) values('"
				+ fname
				+ "','"
				+ lname
				+ "','"
				+ gender
				+ "','"
				+ mobileno
				+ "','" + username + "','" + password + "')";
		int i = stmt.executeUpdate(sql);
		return i;
	}

	public User editUserDao(User user) throws Exception {
		Connection con = DbutilDao.getConnection();
		Statement stmt = DbutilDao.createStatement(con);

		User newuser = new User();
		int id = user.getUserid();

		String sql = "select * from user1 where User_id= " + id + "";

		ResultSet rs = stmt.executeQuery(sql);

		if (rs.next()) {
			newuser.setUserid(rs.getInt(1));
			newuser.setFname(rs.getString(2));
			newuser.setLname(rs.getString(3));
			newuser.setGender(rs.getString(4));
			newuser.setMobileno(rs.getString(5));
			newuser.setUsername(rs.getString(6));
			newuser.setPassword(rs.getString(7));
		}
		return newuser;
	}

	public ArrayList getUsersDao() {
		ArrayList ulist = new ArrayList();
		try {
			Connection con = DbutilDao.getConnection();
			Statement stmt = DbutilDao.createStatement(con);
			String sql = " select * from user1";
			ResultSet rs = DbutilDao.executeQuery(stmt, sql);

			while (rs.next()) {

				User user = new User();

				user.setUserid(rs.getInt("User_id"));
				user.setFname(rs.getString("Firstname"));
				user.setLname(rs.getString("Lastname"));
				user.setGender(rs.getString("Gender"));
				user.setMobileno(rs.getString("Mobile_no"));
				user.setUsername(rs.getString("Username"));
				user.setPassword(rs.getString("Password"));

				ulist.add(user);
			}

		} catch (Exception e) {
			System.out.println(e);
		}
		System.out.println(ulist);
		return ulist;
	}
	public String delUserDao(User user) throws Exception {
		Connection con = DbutilDao.getConnection();
		Statement stmt = DbutilDao.createStatement(con);
		int id = user.getUserid();
		String sql = "delete from user1 where User_id='" + id + "'";
		stmt.executeUpdate(sql);
		return "success";
	}
}


14.edit.jsp:


< % @ page language="java" contentType="text / html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
< % @ taglib prefix="s" uri="/struts-tags"%>
< ! DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http:// www.w3.org/ TR/html4/loose.dtd">
< html >
	< body >
		< center >
			< s:form action="update">
			< s:hidden value="%{u.userid}" name="u.userid" / >
				< s:textfield label="First Name" name="u.fname" required="true"
					value="%{u.fname}" / >
				< s:textfield label="Last Name" name="u.lname" required="true"
					value="%{u.lname}" / >
				< s:radio list="{'male','female'}" label="Gender" name="u.gender"
					value="%{u.gender}" / >
				< s:textfield label="Mobile" name="u.mobileno" value="%{u.mobileno}" / >
				< s:textfield label="User Name" name="u.username" required="true"
					value="%{u.username}" />
				< s:textfield label="Password" name="u.password" required="true"
					value="%{u.password}" / >
				< s:submit value="Update" / >
			< / s:form >
		< / center >
	< / body >
< / html >


Java By Kiran