Wednesday 3 August 2022

Create A Struts2 CRUD Application with Tiles configuration











-----------------------------------------  Auth.java -------------------------------------

package com.ramsis.actions;
import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Entity;

@Entity
@Table(name = "auth")
public class Auth implements Serializable {
@Id
@GeneratedValue
@Column(name="uid")
private int uid;
@Column(name="username")
private String username;
@Column(name="pass")
private String pass;

public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
}


-------------------------------- CustomerAction.java ----------------------------------
package com.ramsis.actions;

import com.opensymphony.xwork2.ActionSupport;

public class CustomerAction extends ActionSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private Integer age;
private String email;
private String telephone;

public String addCustomer() {
return SUCCESS;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}

}

-------------------------- LoginAction.java -------------------------

package com.ramsis.actions;

import com.opensymphony.xwork2.ActionSupport;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
import org.hibernate.*;
import org.hibernate.cfg.AnnotationConfiguration;

public class LoginAction extends ActionSupport implements SessionAware {
/**
*
*/
private static final long serialVersionUID = 1L;
private String username;
private String pass;
private String u;
private String p;
Map m;
public String getUsername() {
return username;
}

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

public String getPass() {
return pass;
}

public void setPass(String pass) {
this.pass = pass;
}



public String getU() {
return u;
}

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

public String getP() {
return p;
}

public void setP(String p) {
this.p = p;
}



public String logOut(){
m.remove("loginId");
addActionMessage("You Have Been Successfully Logged Out");
return SUCCESS;
}

public String execute() {
try{
SessionFactory cfg = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = cfg.openSession();
Transaction t = session.beginTransaction();
//Auth auth = new Auth();
//auth.setUsername("pavan");
//auth.setPass("pavan");
//session.save(auth);
//t.commit();

Query u= session.createQuery("from Auth where username= '"+username+"' and pass= '"+pass+"'");
List<Auth> li = u.list();
if(li.size()>0){
Iterator<Auth> itr = li.iterator();
while(itr.hasNext()){
Auth a = itr.next();
m.put("loginId", a.getUsername());
}

System.out.println("session name is :"+m.get("loginId"));
t.commit();
session.close();


return "success";
}else{

addActionError(getText("Your User name and Password is not valid. "));
return "error";
}
}catch(Exception e){
e.printStackTrace();
addActionError(getText("Some technical error has been occured, Please login after some time.  "));
return "error";

}
}


@Override
public void setSession(Map<String, Object> arg0) {
this.m=arg0;

}

}

-------------------------------- LoginAction-Validation.xml ------------------------

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
  "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
  "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
<field name="username">
<field-validator type="requiredstring">
<param name="trim">true</param>
<message>User Name is required.</message>
</field-validator>
</field>
<field name="pass">
<field-validator type="requiredstring">
<param name="trim">true</param>
<message key="password.required" />
</field-validator>
</field>
</validators>

----------------------------- ClearCacheInterceptor.java ---------------------------

package com.ramsis.clearcache.interceptor;

import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.StrutsStatics;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class ClearCacheInterceptor  extends AbstractInterceptor{
private static final long serialVersionUID = 1L;

@Override
public String intercept(ActionInvocation invocation) throws Exception {
ActionContext context=(ActionContext)invocation.getInvocationContext();
HttpServletResponse response=(HttpServletResponse)context.get(StrutsStatics.HTTP_RESPONSE);
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
String result=invocation.invoke();
return result;
}
}

--------------------------- ClientForSave.java -------------------------------

package com.ramsis.hibernate.contact.util;

import org.hibernate.*;
import org.hibernate.cfg.*;

import com.opensymphony.xwork2.ActionSupport;
public class ClientForSave extends ActionSupport {

private Long id;
private String name;
private int age;
private String email;
private String telephone;

public Long getId() {
return id;
}

public String getName() {
return name;
}

public int getAge() {
return age;
}

public String getEmail() {
return email;
}

public String getTelephone() {
return telephone;
}

public void setId(Long id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setEmail(String email) {
this.email = email;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
   

    public String addCustomer()
    {
   
        Configuration cfg = new AnnotationConfiguration().configure();
 
        SessionFactory factory = cfg.buildSessionFactory();
        Session session = factory.openSession();
        Contact p=new Contact();
       
        p.setName(getName());
        p.setAge(getAge());
        p.setEmail(getEmail());
        p.setTelephone(getTelephone());
 
        Transaction tx = session.beginTransaction();
        session.save(p);
        System.out.println("Object saved successfully.....!!");
        tx.commit();
        session.close();
        factory.close();
       
        return "success";
    }
 
}

---------------------------------- Contact.java ---------------------------

package com.ramsis.hibernate.contact.util;

public class Contact{

private Long id;
private String name;
private Integer age;
private String email;
private String telephone;
private String username;


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;
}
private String password;

public Long getId() {
return id;
}

public String getName() {
return name;
}

public Integer getAge() {
return age;
}

public String getEmail() {
return email;
}

public String getTelephone() {
return telephone;
}

public void setId(Long id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setAge(Integer age) {
this.age = age;
}
public void setEmail(String email) {
this.email = email;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
   

}

------------------------------ DeleteData.java ---------------------------------

package com.ramsis.hibernate.contact.util;

import com.opensymphony.xwork2.ActionSupport;
import java.util.ArrayList;
import java.util.List;


import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;

public class DeleteData extends ActionSupport{

    private String telephone;
private String msg="Records found.";
private String q;
public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}

public String getTelephone() {
return telephone;
}

public void setTelephone(String telephone) {
this.telephone = telephone;
}

public String execute(){
try{
SessionFactory cfg = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = cfg.openSession();
Transaction t = session.beginTransaction();
Transaction t1 = session.beginTransaction();
Query qr1 = session.createQuery("from Contact where telephone='"+telephone+"'");
List<Contact> li = qr1.list();
//System.out.println("telephone : "+telephone);
if(telephone==(null)||telephone==("")||li.size()==0){
    System.out.println("No record Deleted!!");
    msg="No record Deleted!!";
    return "success";
}
else{
   q ="delete from Contact where telephone='"+telephone+"'";

Query qr = session.createQuery(q);
qr.executeUpdate();
t.commit();
session.close();
System.out.println("Record has been Deleted.");
    msg="Record has been Deleted!!";
      return "success";
}
}
catch(Exception e){
e.printStackTrace();
return "error+'"+e+"'";
}

}
  }

------------------------------------- Product.java ----------------------------------------

package com.ramsis.hibernate.contact.util;
public class Product{

private int productId;
private String proName;
private double price;

public void setProductId(int productId)
{
   this.productId = productId;
}
public int getProductId()
{
   return productId;
}

public void setProName(String proName)
{
   this.proName = proName;
}
public String getProName()
{
   return proName;
}

public void setPrice(double price)
{
   this.price = price;
}
public double getPrice()
{
   return price;
}
}

----------------------------------- ShowData.java -------------------------------------

package com.ramsis.hibernate.contact.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.hibernate.*;
import org.hibernate.cfg.AnnotationConfiguration;

import com.opensymphony.xwork2.ActionSupport;

public class ShowData extends ActionSupport {
private List<Contact> comboMeals = new ArrayList<Contact>();

public List<Contact> getComboMeals() {
return comboMeals;
}
 
public void setComboMeals(List<Contact> comboMeals) {
this.comboMeals = comboMeals;
}
public String execute(){
try{
SessionFactory cfg = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = cfg.openSession();
Transaction t = session.beginTransaction();

Query s = session.createQuery("from Contact");

List<Contact> li = s.list();
Iterator<Contact> itr = li.iterator();

while(itr.hasNext()){
Contact c = itr.next();
//System.out.println(c.getName());
// c.getName();
// c.getEmail();
// c.getPassword();
// c.getTelephone();
// c.getUsername();
comboMeals.add(c);
//System.out.println(t.wasCommitted());
}

t.commit();
session.close();

}
catch(Exception e){
e.printStackTrace();
}
if(comboMeals.size()>0){
return "success";
}
else{
return "error";
}

 }

}

----------------------------------------- ShowTest.java -----------------------

package com.ramsis.hibernate.contact.util;

import java.util.ArrayList;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;

public class ShowTest extends ActionSupport {
private List<String> comboMeals;

public List<String> getComboMeals() {
return comboMeals;
}
 
public void setComboMeals(List<String> comboMeals) {
this.comboMeals = comboMeals;
}
 
public String execute() {
 
comboMeals = new ArrayList<String>();
comboMeals.add("Snack Plate");
comboMeals.add("Dinner Plate");
comboMeals.add("Colonel Chicken Rice Combo");
comboMeals.add("Colonel Burger");
comboMeals.add("O.R. Fillet Burger");
comboMeals.add("Zinger Burger");
 
return SUCCESS;
}

}


------------------------------------ Update.java ------------------------

package com.ramsis.hibernate.contact.util;

import org.hibernate.*;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

import com.opensymphony.xwork2.ActionSupport;

public class Update extends ActionSupport {

private int id;
private String name;
private String age;
private String telephone;
private String email;
private String msg="";


public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email=email;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}

public String execute(){

 try{
SessionFactory cfg = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = cfg.openSession();
Transaction t =  session.beginTransaction();
Query u = session.createQuery("update Contact set name='"+name+"', age='"+age+"', email='"+email+"' , telephone='"+telephone+"' where id ='"+id+"'");
       u.executeUpdate();
   t.commit();
   session.close();
   //System.out.println(t.wasCommitted());
   boolean ck = t.wasCommitted();
   
   if(ck==(false)){
    System.out.println("Record has not updated.");
    msg="Record has not updated.";
    return "error";
   }
   
   else
    System.out.println("Record has been updated.");
       msg="Record has been updated.";
       return "success";
   }  
catch(Exception e){
e.printStackTrace();
return "error";
}

}

}

---------------------------------- UpdateData.java --------------------------------

package com.ramsis.hibernate.contact.util;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
import org.hibernate.*;
import org.hibernate.annotations.*;
import org.hibernate.cfg.AnnotationConfiguration;

import com.opensymphony.xwork2.ActionSupport;

public class UpdateData extends ActionSupport{

private String name;
private String telephone;
private String msg="";
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}

private List<Contact> list = new ArrayList<Contact>();

public List<Contact> getList() {
return list;
}
public void setList(List<Contact> list) {
this.list = list;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}

public String execute(){
       try{
SessionFactory cfg = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = cfg.openSession();
Transaction t = session.beginTransaction();

Query q = session.createQuery("from Contact where telephone='"+telephone+"' and name='"+name+"'");

List <Contact> li = q.list();

Iterator <Contact> itr = li.iterator();
System.out.println(name);
System.out.println(telephone);
if(li.size()==0){
msg="No record found!!";
System.out.println(msg);
return "error";
}
System.out.println("size : "+li.size());
msg="Records found.";
while(itr.hasNext()){

Contact c = itr.next();

System.out.println(msg);
list.add(c);
}

t.commit();

       }
       catch(Exception e){
      e.printStackTrace();
       }
    return "success";
}

public String click(){
return "success";
}
}

---------------------------------------- ClientForSave-validation.xml ----------------------

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
  "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
  "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
<field name="name">
<field-validator type="requiredstring">
<param name="trim">true</param>
<message key="name.required" />
</field-validator>
</field>
<field name="age">
<field-validator type="required">
<message key="error.required" />
</field-validator>
<field-validator type="int">
<param name="min">1</param>
<param name="max">100</param>
<message key="age.range"/>
</field-validator>
</field>
<field name="email">
<field-validator type="requiredstring">
<message key="email.required" />
</field-validator>
<field-validator type="email">
<message key="email.invalid" />
</field-validator>
</field>
<field name="telephone">
<field-validator type="requiredstring">
<message key="errors.required" />
</field-validator>
</field>
</validators>

------------------------------------ LoginInterceptor.java -------------------------

package com.ramsis.loginapi.interceptor;

import java.util.Map;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class LoginInterceptor implements Interceptor {
private static final long serialVersionUID = 1L;
@Override
public void destroy() {
// TODO Auto-generated method stub

}

@Override
public void init() {
// TODO Auto-generated method stub

}

@Override
public String intercept(ActionInvocation invocation) throws Exception {
Map<String, Object> sessionAttributes = invocation.getInvocationContext().getSession();

if (sessionAttributes == null || sessionAttributes.get("loginId") == null) {
return "login";
} else {
if (!((String) sessionAttributes.get("loginId")).equals(null)) {
return invocation.invoke();
} else {
return "login";
}
}

}

}

------------------------------------ Contact.hbm.xml --------------------------------

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="com.ramsis.hibernate.contact.util.Contact" table="Contact">

<id name="id" column="Id"  >
<generator class="increment"/>
</id>
<property name="name" column="Name" length="30"/>
<property name="age" column="Age" length="10"/>
<property name="email" column="Email" length="20"/>
<property name="telephone" column="Telephone" length="30"/>

</class>
</hibernate-mapping>

------------------------------------ hibernate.cfg.xml --------------------------------

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

<!-- Database connection settings -->
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/exampledb
</property>
<property name="connection.username">cdb</property>
<property name="connection.password">1234</property>

<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>

<!-- SQL dialect -->
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>

<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>

<!-- Disable the second-level cache  -->
<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider
</property>

<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>

<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>

<!--  <mapping class="com.ramsis.hibernate.contact.model.Contact" /> -->
          <mapping class="com.ramsis.actions.Auth" />
          <mapping resource="Contact.hbm.xml" />
       
</session-factory>

</hibernate-configuration>

----------------------------------- struts.xml -----------------------------------

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
 
<struts>
    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="false" />
    <constant name="struts.custom.i18n.resources" value="ApplicationResources" />
   
    <package name="default" extends="struts-default" namespace="/" >
         <result-types>
            <result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult" />
        </result-types>
       
      <interceptors>
<interceptor name="loginInterceptor" class="com.ramsis.loginapi.interceptor.LoginInterceptor1" ></interceptor>
<interceptor name="clear-cache" class="com.ramsis.clearcache.interceptor.ClearCacheInterceptor" ></interceptor>
<interceptor-stack name="loginStack">
<interceptor-ref name="loginInterceptor" />
<interceptor-ref name="defaultStack" />
</interceptor-stack>
 </interceptors>
     
         <global-results>
<result name="login">/Login.jsp</result>
</global-results>

        <action name="login"
            class="com.ramsis.actions.LoginAction" method="execute">
           
            <result name="success" type="tiles">/welcome.tiles</result>
              <result name="error">/Login.jsp</result>
            <result name="input">/Login.jsp</result>
        </action>
      <!--  <action name="customer"
            class="com.ramsis.actions.CustomerAction">
    <interceptor-ref name="loginStack" />
            <result name="success" type="tiles">/customer.success.tiles</result>
            <result name="input" type="tiles">/customer.tiles</result>
        </action> -->
        <action name="customer-form">
            <interceptor-ref name="loginStack" />  
            <result name="success" type="tiles">/customer.tiles</result>
        </action>
        <!--   logout action  -->
<action name="logOut" class="com.ramsis.actions.LoginAction" method="logOut">
       <interceptor-ref name="clear-cache" />
       <interceptor-ref name="loginStack" />
<result name="success">/Login.jsp</result>
</action>

      <action name="customer" class="com.ramsis.hibernate.contact.util.ClientForSave" method="addCustomer">
    <interceptor-ref name="loginStack" />
<result name="success" type="tiles">/customer.success.tiles</result>
<result name="input" type="tiles">/customer.tiles</result>
</action>

<action name="ShowTest" class="com.ramsis.hibernate.contact.util.ShowData">
    <interceptor-ref name="loginStack" />
    <result name="error">/error.jsp</result>
<result type="tiles" name="success" >/ShowTest.success.tiles</result>
</action>

<action name="DeleteData" class="com.ramsis.hibernate.contact.util.DeleteData">
    <interceptor-ref name="loginStack" />
   <result name="error">/error.jsp</result>
<result type="tiles" name="success" >/DeleteData.success.tiles</result>
</action>

<action name="DeleteDataClick" class="">
    <interceptor-ref name="loginStack" />
   <result name="error">/error.jsp</result>
<result type="tiles" name="success" >/DeleteDataClick.success.tiles</result>
</action>

<action name="BeforeUpdate" class="com.ramsis.hibernate.contact.util.UpdateData" method="click">
    <interceptor-ref name="loginStack" />
    <result name="error">/error.jsp</result>
<result type="tiles" name="success" >/BeforeUpdate.success.tiles</result>
</action>

<!-- <action name="BeforeUpdate" class="com.ramsis.hibernate.contact.util.UpdateData" method="execute">
    <interceptor-ref name="loginStack" />
    <result name="error">/error.jsp</result>
<result type="tiles" name="success" >/BeforeUpdate.success.tiles</result>
</action> -->

<action name="UpdateData" class="com.ramsis.hibernate.contact.util.UpdateData" method="execute">
    <interceptor-ref name="loginStack" />
    <result type="tiles" name="error">/BeforeUpdate.error.tiles</result>
<result type="tiles" name="success" >/Update.success.tiles</result>
</action>

         <action name="Updated" class="com.ramsis.hibernate.contact.util.Update" method="execute">
    <interceptor-ref name="loginStack" />
    <result name="error">/error.jsp</result>
<result type="tiles" name="success" >/Updated.success.tiles</result>
</action>

    </package>
</struts>

--------------------------------------- tiles.xml -----------------------------------------

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE tiles-definitions PUBLIC
       "-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
       "http://tiles.apache.org/dtds/tiles-config_2_0.dtd">

<tiles-definitions>

<definition name="baseLayout" template="/BaseLayout.jsp">
<put-attribute name="title" value="" />
<put-attribute name="header" value="/Header.jsp" />
<put-attribute name="menu" value="/Menu.jsp" />
<put-attribute name="body" value="" />
<put-attribute name="footer" value="/Footer.jsp" />
</definition>

<definition name="/welcome.tiles" extends="baseLayout">
<put-attribute name="title" value="Welcome" />
<put-attribute name="body" value="/Welcome.jsp" />
</definition>

<definition name="/customer.tiles" extends="baseLayout">
<put-attribute name="title" value="Customer Form" />
<put-attribute name="body" value="/Customer.jsp" />
</definition>
<definition name="/customer.success.tiles" extends="baseLayout">
<put-attribute name="title" value="Customer Added" />
<put-attribute name="body" value="/SuccessCustomer.jsp" />
</definition>
<definition name="/ShowTest.success.tiles" extends="baseLayout">
<put-attribute name="title" value="ShowTest" />
<put-attribute name="body" value="/ShowTest.jsp" />
</definition>
    <definition name="/DeleteData.success.tiles" extends="baseLayout">
<put-attribute name="title" value="DeleteData" />
<put-attribute name="body" value="/DeleteData.jsp" />
</definition>
<definition name="/DeleteDataClick.success.tiles" extends="baseLayout">
<put-attribute name="title" value="DeleteDataClick" />
<put-attribute name="body" value="/DeleteData.jsp" />
</definition>
<definition name="/BeforeUpdate.success.tiles" extends="baseLayout">
<put-attribute name="title" value="BeforeUpdate" />
<put-attribute name="body" value="/BeforeUpdate.jsp" />
</definition>
<definition name="/BeforeUpdate.error.tiles" extends="baseLayout">
<put-attribute name="title" value="UpdateError" />
<put-attribute name="body" value="/BeforeUpdate.jsp" />
</definition>
<definition name="/Update.success.tiles" extends="baseLayout">
<put-attribute name="title" value="Update" />
<put-attribute name="body" value="/Update.jsp" />
</definition>
<definition name="/Updated.success.tiles" extends="baseLayout">
<put-attribute name="title" value="Updated" />
<put-attribute name="body" value="/BeforeUpdate.jsp" />
</definition>

</tiles-definitions>

----------------------------------------- web.xml -----------------------------

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" 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">

<display-name>Struts2 Application</display-name>
<listener>
<listener-class>
org.apache.struts2.tiles.StrutsTilesListener
</listener-class>
</listener>
<context-param>
<param-name>tilesDefinitions</param-name>
<param-value>/WEB-INF/tiles.xml</param-value>
</context-param>

<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>Login.jsp</welcome-file>
</welcome-file-list>

</web-app>

---------------------------------------- BaseLayout.jsp ----------------------------------

<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<!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=UTF-8">
<title><tiles:insertAttribute name="title" ignore="true" /></title>
</head>
<body>
<table border="1" cellpadding="2" cellspacing="2" align="center">
<tr>
<td height="30" colspan="3"><tiles:insertAttribute name="header" />
</td>
</tr>
<tr>
<td height="300" width="100"><tiles:insertAttribute name="menu" /></td>
<td width="350"><tiles:insertAttribute name="body" /></td>
<td height="300"><tiles:insertAttribute name="menu" /></td>
</tr>
<tr>
<td height="30" colspan="3"><tiles:insertAttribute name="footer" />
</td>
</tr>
</table>
</body>
</html>

--------------------------------- BeforeUpdate.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">
<%@ taglib prefix="s" uri="/struts-tags" %>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Check Data which you have to update.</title>
</head>
<body>
<h2>Update your data.</h2>
<p><s:property value="msg" /></p>

<s:form action="UpdateData.action" method="Post" >
    <s:textfield  name="name"  size="20" label="Name" />
    <s:textfield  name="telephone" size="20" label="Telephone" />
    <s:submit method="execute" key="Submit" />
</s:form>
</body>
</html>

------------------------------- body.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>
<p> sample body content.</p>
</body>
</html>

----------------------------- Customer.jsp ----------------------------------------

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Customer Form - Struts2 Demo </title>
</head>

<body>
<h2>Customer Form</h2>

<s:form action="customer.action" method="post" validate="true">
<s:textfield name="name" key="name" size="20" label="Name" />
<s:textfield name="age" key="age" size="20" label="Age" />
<s:textfield name="email" key="email" size="20" label=" Email" />
<s:textfield name="telephone" key="telephone" size="20" label="Telephome" />
<s:submit method="addCustomer" key="submit" align="center" />
</s:form>
</body>
</html>

--------------------------- DeleteData.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">
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2>Delete Data</h2>
<s:property value="msg" />
<s:form action="DeleteData.action" method="post" >
 
  <s:textfield  name="telephone" size="20" label="Enter Telephone Number " />
  <s:submit method="execute" key="Submit" />
 
</s:form>

</body>
</html>

------------------------------- error.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>
<h2>Error has been occur. Try again. </h2>
</body>
</html>

------------------------------------ Footer.jsp -------------------------

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
Copyright &copy; ramsis-code.blogspot.in

------------------------------------ Header.jsp -------------------------

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<center><h2>Ramsis-Code</h2></center>
<table width="100%" border="0">
<tr>
<td>
Hello <s:property value="%{#session['loginId']}"/>&nbsp;|&nbsp;<a href="<s:url action="logOut"/>">LogOut</a>
&nbsp;|&nbsp;<a href="<s:url action="logOut"/>">Log In</a>
</td>
</tr>
</table>

--------------------------------- Login.jsp ----------------------------


<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Struts 2 - Login Application | ViralPatel.net</title>
</head>
<body>
<h2>Struts 2 - Login Application</h2>
<s:actionmessage />
<s:actionerror />
<s:form action="login.action" method="post" namespace="LoginUser">
<s:textfield name="username" key="label.username" size="20" label="User Name" />
<s:password name="pass" key="label.password" size="20" label="Password" />
<s:submit method="execute" value="Submit" key="label.login" align="center"  />
</s:form>
</body>
</html>


--------------------------------- Logout.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="Refresh" CONTENT="0;URL=Test.action">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
 <p> Logout Successfully...</p>
</body>
</html>

------------------------------- Menu.jsp --------------------------

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<s:a href="customer-form">Submit Form</s:a><br/>
<s:a href="ShowTest">Show Data</s:a><br/>
<s:a href="DeleteDataClick">Delete Data</s:a><br/>
<s:a href="BeforeUpdate">Update Data</s:a>

----------------------------- ShowTest.jsp ------------------------

<%@ taglib prefix="s" uri="/struts-tags" %>
 
<html>
<head>
</head>
 
<body>
<!--  <h1>Struts 2 Iterator tag example</h1>-->
 
<h3>Show Records</h3>
<table border="1" style="border-collapse:collapse;">
<th>Name</th>
<th>Age</th>
<th>Email</th>
<th>Telephone</th>
<s:iterator value="comboMeals" status="comboMealsStatus" >
<tr>
  <!--  <s:if test="comboMealsStatus.odd == true" />  -->
  <td style="background: #CCCCCC"> <s:property value="name" /></td>
  <td> <s:property value="age" /></td>
  <td> <s:property value="email" /></td>
  <td> <s:property value="telephone" /></td>
</tr>  
</s:iterator>
</table>

</body>
</html>

-------------------------- SuccessCustomer.jsp -----------------------

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Customer Page - Struts2 Demo | ViralPatel.net</title>
</head>

<body>
<h2>Customer Added Successfully.</h2>
</body>
</html>

--------------------------- Update.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">
<%@ taglib prefix="s" uri="/struts-tags" %>

<html>
<head>
<title>Check Data which you have to update.</title>
</head>
<body>
<h2>Update your data.</h2>
<p><s:property value="msg" /></p>
<p><s:set var="strmsg" value="msg"/></p>
<s:form action="Updated.action" method="Post" >
    <s:iterator value="list" var="list">
    <s:hidden name="id" value="%{#list.id}" />
    <s:textfield  name="name" value="%{#list.name}" size="20" label="Name" />
    <s:textfield  name="age" value="%{#list.age}" size="20" label="Age " />
    <s:textfield  name="email" value="%{#list.email}"  size="20" label="Email" />
    <s:textfield  name="telephone" value="%{#list.telephone}"  size="20" label="Telephone" />
    </s:iterator>
    <s:submit method="execute" key="Submit" />
     
</s:form>
</body>
</html>

--------------------------- Welcome.jsp ----------------------------------

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Welcome</title>
</head>

<body>
<h2>Howdy, <s:property value="username" />...!</h2>

</body>
</html>

Download Code

Create A Pagination Application using jsp Servlet





----------------------------------- ConnectionFactory.java -------------------------------------------

package com.ramsiscode.db;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
 
public class ConnectionFactory {
    //static reference to itself
    private static ConnectionFactory instance =
                new ConnectionFactory();
    String url = "jdbc:mysql://localhost:3306/exampledb";
    String user = "asdfg";
    String password = "cctns@7777";
    String driverClass = "com.mysql.jdbc.Driver";
 
    //private constructor
    private ConnectionFactory() {
        try {
            Class.forName(driverClass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
 
    public static ConnectionFactory getInstance()   {
        return instance;
    }
 
    public Connection getConnection() throws SQLException,
    ClassNotFoundException {
        Connection connection =
            DriverManager.getConnection(url, user, password);
        return connection;
    }
}


----------------------------------- EmployeeServlet.java -------------------------------------------


package com.ramsiscode.servlets;
 
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ramsiscode.dao.EmployeeDAO;
import com.ramsiscode.to.Employee;
 
/**
 * Servlet implementation class EmployeeServlet
 */
public class EmployeeServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
 
    public EmployeeServlet() {
            super();
    }
 
    public void doGet(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {
        int page = 1;
        int recordsPerPage = 8;
        if(request.getParameter("page") != null)
            page = Integer.parseInt(request.getParameter("page"));
        EmployeeDAO dao = new EmployeeDAO();
        List<Employee> list = dao.viewAllEmployees((page-1)*recordsPerPage,
                                 recordsPerPage);
        int noOfRecords = dao.getNoOfRecords();
        int noOfPages = (int) Math.ceil(noOfRecords * 1.0 / recordsPerPage);
        request.setAttribute("employeeList", list);
        request.setAttribute("noOfPages", noOfPages);
        request.setAttribute("currentPage", page);
        RequestDispatcher view = request.getRequestDispatcher("displayEmployee.jsp");
        view.forward(request, response);
    }
}



----------------------------------- EmployeeDAO.java -------------------------------------------

package com.ramsiscode.dao;
 
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.ramsiscode.db.ConnectionFactory;
import com.ramsiscode.to.Employee;
 
public class EmployeeDAO {
    Connection connection;
    Statement stmt;
    private int noOfRecords;
 
    public EmployeeDAO() { }
 
    private static Connection getConnection()
            throws SQLException,
                ClassNotFoundException
    {
        Connection con = ConnectionFactory.
                getInstance().getConnection();
        return con;
    }
 
    public List<Employee> viewAllEmployees(
                int offset,
                int noOfRecords)
    {
        String query = "select SQL_CALC_FOUND_ROWS * from employee limit "
                 + offset + ", " + noOfRecords;
        List<Employee> list = new ArrayList<Employee>();
        Employee employee = null;
        try {
            connection = getConnection();
            stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery(query);
            while (rs.next()) {
                employee = new Employee();
                employee.setEmployeeId(rs.getInt("emp_id"));
                employee.setEmployeeName(rs.getString("emp_name"));
                employee.setSalary(rs.getDouble("salary"));
                employee.setDeptName(rs.getString("dept_name"));
                list.add(employee);
            }
            rs.close();
 
            rs = stmt.executeQuery("SELECT FOUND_ROWS()");
            if(rs.next())
                this.noOfRecords = rs.getInt(1);
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }finally
        {
            try {
                if(stmt != null)
                    stmt.close();
                if(connection != null)
                    connection.close();
                } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return list;
    }
 
    public int getNoOfRecords() {
        return noOfRecords;
    }
}

--------------------------------------- Employee.java ---------------------------------------


package com.ramsiscode.to;
 
public class Employee {
    private int employeeId;
    private String employeeName;
    private double salary;
    private String deptName;
 
    public int getEmployeeId() {
        return employeeId;
    }
    public void setEmployeeId(int employeeId) {
        this.employeeId = employeeId;
    }
    public String getEmployeeName() {
        return employeeName;
    }
    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }
    public double getSalary() {
        return salary;
    }
    public void setSalary(double salary) {
        this.salary = salary;
    }
    public String getDeptName() {
        return deptName;
    }
    public void setDeptName(String deptName) {
        this.deptName = deptName;
    }
}


---------------------------------- displayEmployee.jsp -----------------------------------------



<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>Employees</title>
</head>
<body>
    <table border="1" cellpadding="3" cellspacing="3">
        <tr>
            <th>Emp ID</th>
            <th>Emp Name</th>
            <th>Salary</th>
            <th>Dept Name</th>
        </tr>
 
        <c:forEach var="employee" items="${employeeList}">
            <tr>
                <td>${employee.employeeId}</td>
                <td>${employee.employeeName}</td>
                <td>${employee.salary}</td>
                <td>${employee.deptName}</td>
            </tr>
        </c:forEach>
    </table>
 
    <%--For displaying Previous link except for the 1st page --%>
    <c:if test="${currentPage != 1}">
        <td><a href="employee.do?page=${currentPage - 1}">Previous</a></td>
    </c:if>
 
    <%--For displaying Page numbers.
    The when condition does not display a link for the current page--%>
    <table border="1" cellpadding="5" cellspacing="5">
        <tr>
            <c:forEach begin="1" end="${noOfPages}" var="i">
                <c:choose>
                    <c:when test="${currentPage eq i}">
                        <td>${i}</td>
                    </c:when>
                    <c:otherwise>
                        <td><a href="employee.do?page=${i}">${i}</a></td>
                    </c:otherwise>
                </c:choose>
            </c:forEach>
        </tr>
    </table>
 
    <%--For displaying Next link --%>
    <c:if test="${currentPage lt noOfPages}">
        <td><a href="employee.do?page=${currentPage + 1}">Next</a></td>
    </c:if>
 
</body>
</html>

------------------------------------ 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_3_0.xsd" id="WebApp_ID" version="3.0">

  <display-name>JSPPagination</display-name>
   <welcome-file-list>
    <welcome-file>employee.do</welcome-file>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>EmployeeServlet</servlet-name>
    <servlet-class>com.ramsiscode.servlets.EmployeeServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>EmployeeServlet</servlet-name>
    <url-pattern>/employee.do</url-pattern>
  </servlet-mapping>
</web-app>

Download Code

Friday 15 July 2022

CRUD Web Application using JSTL Library in jsp











--------------------------------------------------Insert.jsp------------------------------------------

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Choose Option</h1>
        <a href="insert.jsp">Insert Record</a><p></p>
        <a href="display.jsp">Display Record</a>
    </body>
</html>

--------------------------------------------------index.jsp------------------------------------------

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <form action="insertdb.jsp" method="post">
            <table border="0" cellspacing="2" cellpadding="5">
                <thead>
                    <tr>
                        <th colspan="2">Purchase Product</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td><label>Product Name</label></td>
                        <td><input type="text" name="pname"/></td>
                    </tr>
                    <tr>
                        <td><label>Quantity</label></td>
                        <td><input type="text" name="qty"/></td>
                    </tr>
                    <tr>
                        <td><input type="submit" value="Save" /></td>
                        <td><input type="reset" value="reset"/></td>
                    </tr>
                </tbody>
            </table>
        </form>
        <font color="red"><c:if test="${not empty param.errMsg}">
            <c:out value="${param.errMsg}" />
            <a href="index.jsp">Go Back</a>
        </c:if></font>
        <font color="green"><c:if test="${not empty param.susMsg}">
            <c:out value="${param.susMsg}" />
            <a href="index.jsp">Go Back</a>
        </c:if></font>
 
    </body>
</html>

-----------------------------------------------------updatedb.jsp----------------------------------------------
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
       <sql:setDataSource var="dbsource" driver="com.mysql.jdbc.Driver"
                           url="jdbc:mysql://localhost:3306/exampledb"
                           user="xyx"  password="abcd"/>
        <sql:update dataSource="${dbsource}" var="count">
            UPDATE product SET pname = ?, quantity=?
            WHERE id='${param.id}'
            <sql:param value="${param.pname}" />
            <sql:param value="${param.qty}" />
        </sql:update>
        <c:if test="${count>=1}">
            <font size="5" color='green'> Congratulations ! Data updated
            successfully.</font>
              <a href="index.jsp">Go Home</a>        
        </c:if>
    </body>
</html>

-------------------------------------------------update.jsp----------------------------------------------------

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
 
       <sql:setDataSource var="dbsource" driver="com.mysql.jdbc.Driver"
                           url="jdbc:mysql://localhost:3306/exampledb"
                           user="xyx"  password="abcd"/>
 
        <sql:query dataSource="${dbsource}" var="result">
            SELECT * from product where id=?;
            <sql:param value="${param.id}" />
        </sql:query>
        <form action="updatedb.jsp" method="post">
            <table border="0" width="40%">
                <caption>Update Product</caption>
                <tr>
                    <th>Product Name</th>
                    <th>Quantity</th>
                </tr>
                <c:forEach var="row" items="${result.rows}">
                    <tr>
                        <td><input type="hidden" value="${param.id}" name="id"/>
                            <input type="text" value="${row.pname}" name="pname"/></td>
                        <td><input type="text" value="${row.quantity}" name="qty"/></td>
                        <td><input type="submit" value="Update"/></td>
                    </tr>
                </c:forEach>
            </table>
            <a href="index.jsp">Go Home</a>
        </form>
    </body>
</html>
-------------------------------------------------------deletedb.jsp---------------------------------------------

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
  <sql:setDataSource var="dbsource" driver="com.mysql.jdbc.Driver"
                           url="jdbc:mysql://localhost:3306/exampledb"
                           user="xyx"  password="abcd"/>
 
        <sql:update dataSource="${dbsource}" var="count">
            DELETE FROM product
            WHERE id='${param.id}'
        </sql:update>
        <c:if test="${count>=1}">
            <font size="5" color='green'> Congratulations ! Data deleted
            successfully.</font>
              <a href="index.jsp">Go Home</a>        
        </c:if>
    </body>
</html>
---------------------------------------------------------display.jsp---------------------------------------------

<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
 
<html>
    <head>
        <title>SELECT Operation</title>
        <script>
            function confirmGo(m,u) {
                if ( confirm(m) ) {
                    window.location = u;
                }
            }
        </script>
    </head>
    <body>
 
        <sql:setDataSource var="dbsource" driver="com.mysql.jdbc.Driver"
                           url="jdbc:mysql://localhost:3306/exampledb"
                           user="xyx"  password="abcd"/>
 
        <sql:query dataSource="${dbsource}" var="result">
            SELECT * from product;
        </sql:query>
    <center>
        <form>
            <table border="1" width="40%">
                <caption>Product List</caption>
                <tr>
                    <th>Product ID</th>
                    <th>Product Name</th>
                    <th>Quantity</th>
                    <th colspan="2">Action</th>
                </tr>
                <c:forEach var="row" items="${result.rows}">
                    <tr>
                        <td><c:out value="${row.id}"/></td>
                        <td><c:out value="${row.pname}"/></td>
                        <td><c:out value="${row.quantity}"/></td>
                        <td><a href="update.jsp?id=<c:out value="${row.id}"/>">Update</a></td>
                        <td><a href="javascript:confirmGo('Sure to delete this record?','deletedb.jsp?id=<c:out value="${row.id}"/>')">Delete</a></td>
                         
                    </tr>
                </c:forEach>
            </table>
        </form>
        <a href="index.jsp">Go Home</a>
    </center>
</body>
</html>

-----------------------------------------------------------------------------------------------------------------------



Download Code

Saturday 19 December 2020

CRUD Application using Jsp Servlet and JSTL

Project Code Structure





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>JspServletJstlCrud</display-name>
 
  <servlet>
        <servlet-name>UserController</servlet-name>
        <servlet-class>com.ramsiscode.controller.UserController</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>UserController</servlet-name>
        <url-pattern>/UserController</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
 
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

-------------------------------------------------------------------------------------

UserController.java

package com.ramsiscode.controller;
 
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
 
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ramsiscode.dao.UserDao;
import com.ramsiscode.model.User;
 
public class UserController extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static String INSERT_OR_EDIT = "/user.jsp";
    private static String LIST_USER = "/listuser.jsp";
    private UserDao dao;
 
    public UserController() {
        super();
        dao = new UserDao();
    }
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String forward="";
        String action = request.getParameter("action");
 
        if (action.equalsIgnoreCase("delete")){
            String userId = request.getParameter("userId");
            dao.deleteUser(userId);
            forward = LIST_USER;
            request.setAttribute("users", dao.getAllUsers());  
        } else if (action.equalsIgnoreCase("edit")){
            forward = INSERT_OR_EDIT;
            String userId = request.getParameter("userId");
            User user = dao.getUserById(userId);
            request.setAttribute("user", user);
        } else if (action.equalsIgnoreCase("listUser")){
            forward = LIST_USER;
            request.setAttribute("users", dao.getAllUsers());
        } else {
            forward = INSERT_OR_EDIT;
        }
 
        RequestDispatcher view = request.getRequestDispatcher(forward);
        view.forward(request, response);
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = new User();
        user.setUname(request.getParameter("uname"));
        user.setPassword(request.getParameter("pass"));
        try {
            Date reg = new SimpleDateFormat("yyyy/MM/dd").parse(request.getParameter("dob"));
            System.out.println("Date >>> "+ reg);
            user.setRegisteredon(reg);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setEmail(request.getParameter("email"));
        String userid = request.getParameter("uname");
//        if(userid == null || userid.isEmpty())
//        {
//            dao.addUser(user);
//        }
//        else
//        {
            user.setUname(userid);
            dao.checkUser(user);
//        }
        RequestDispatcher view = request.getRequestDispatcher(LIST_USER);
        request.setAttribute("users", dao.getAllUsers());
        view.forward(request, response);
    }
}

--------------------------------------------------------------------------------------

UserDao.java

package com.ramsiscode.dao;
 
import java.sql.*;
import java.util.*;

import com.ramsiscode.model.User;
import com.ramsiscode.util.Database;
 
public class UserDao {
 
    private Connection connection;
 
    public UserDao() {
        connection = Database.getConnection();
    }
 
    public void checkUser(User user) {
        try {
            PreparedStatement ps = connection.prepareStatement("select uname from users where uname = ?");
            ps.setString(1, user.getUname());
            ResultSet rs = ps.executeQuery();
            if (rs.next()) // found
            {
                updateUser(user);
            } else {
                addUser(user);
            }
        } catch (Exception ex) {
            System.out.println("Error in check() -->" + ex.getMessage());
        }
    }
    public void addUser(User user) {
        try {
            PreparedStatement preparedStatement = connection.prepareStatement("insert into users(uname, password, email, registeredon) values (?, ?, ?, ? )");
            // Parameters start with 1
            preparedStatement.setString(1, user.getUname());
            preparedStatement.setString(2, user.getPassword());
            preparedStatement.setString(3, user.getEmail());          
            preparedStatement.setDate(4, new java.sql.Date(user.getRegisteredon().getTime()));
            preparedStatement.executeUpdate();
 
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
 
    public void deleteUser(String userId) {
        try {
            PreparedStatement preparedStatement = connection.prepareStatement("delete from users where uname=?");
            // Parameters start with 1
            preparedStatement.setString(1, userId);
            preparedStatement.executeUpdate();
 
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
 
    public void updateUser(User user) {
        try {
            PreparedStatement preparedStatement = connection.prepareStatement("update users set password=?, email=?, registeredon=?"
                    + "where uname=?");
            // Parameters start with 1
            System.out.println(new java.sql.Date(user.getRegisteredon().getTime()));
            preparedStatement.setString(1, user.getPassword());
            preparedStatement.setString(2, user.getEmail());
            preparedStatement.setDate(3, new java.sql.Date(user.getRegisteredon().getTime()));
            preparedStatement.setString(4, user.getUname());
            preparedStatement.executeUpdate();
 
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
 
    public List<User> getAllUsers() {
        List<User> users = new ArrayList<User>();
        try {
            Statement statement = connection.createStatement();
            ResultSet rs = statement.executeQuery("select * from users");
            while (rs.next()) {
                User user = new User();
                user.setUname(rs.getString("uname"));
                user.setPassword(rs.getString("password"));
                user.setEmail(rs.getString("email"));
                user.setRegisteredon(rs.getDate("registeredon"));
                users.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
 
        return users;
    }
 
    public User getUserById(String userId) {
        User user = new User();
        try {
            PreparedStatement preparedStatement = connection.prepareStatement("select * from users where uname=?");
            preparedStatement.setString(1, userId);
            ResultSet rs = preparedStatement.executeQuery();
 
            if (rs.next()) {
                user.setUname(rs.getString("uname"));
                user.setPassword(rs.getString("password"));
                user.setEmail(rs.getString("email"));
                user.setRegisteredon(rs.getDate("registeredon"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
 
        return user;
    }
}

--------------------------------------------------------------------------------------

User.java

package com.ramsiscode.model;
import java.util.Date;

public class User {

  String uname, password, email;
  Date registeredon;
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getRegisteredon() {
return registeredon;
}
public void setRegisteredon(Date registeredon) {
this.registeredon = registeredon;
}
}

--------------------------------------------------------------------------------------

Database.java

package com.ramsiscode.util;
import java.sql.Connection;
import java.sql.DriverManager;
public class Database {
      public static Connection getConnection() {
          try  {
              Class.forName("com.mysql.cj.jdbc.Driver");
              Connection con = DriverManager.getConnection
                      ("jdbc:mysql://localhost:3306/test?characterEncoding=utf8",
                      "root","admin123");
              return con;
          }
          catch(Exception ex) {
              System.out.println("Database.getConnection() Error -->" + ex.getMessage());
              return null;
          }
      }
 
       public static void close(Connection con) {
          try  {
              con.close();
          }
          catch(Exception ex) {
          }
      }
}

-------------------------------------------------------------------------------------
listuser.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Show All Users</title>
</head>
<body>
    <table border=1>
        <thead>
            <tr>
                <th>User Name</th>
                <th>Email</th>
                <th>Registration Date</th>
                <th colspan=2>Action</th>
            </tr>
        </thead>
        <tbody>
            <c:forEach items="${users}" var="user">
                <tr>
                    <td><c:out value="${user.uname}" /></td>
                    <td><c:out value="${user.email}" /></td>
                    <td><fmt:formatDate pattern="dd MMM,yyyy" value="${user.registeredon}" /></td>
                    <td><a href="UserController?action=edit&userId=<c:out value="${user.uname}"/>">Update</a></td>
                    <td><a href="UserController?action=delete&userId=<c:out value="${user.uname}"/>">Delete</a></td>
                </tr>
            </c:forEach>
        </tbody>
    </table>
    <p><a href="UserController?action=insert">Add User</a></p>
</body>
</html>

-------------------------------------------------------------------------------------

user.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Add new user</title>
    </head>
    <body>
        <form method="POST" action='UserController' name="frmAddUser">
        <Table border="0px;">
            <% String action = request.getParameter("action");
                System.out.println(action);
            %>
            <tr>
            <% if (action.equalsIgnoreCase("edit")) {%>
            <td>
            User Name : </td><td><input type="text" name="uname"
                               value="<c:out value="${user.uname}" />" readonly="readonly"/> (You Can't Change this)</td>
            <%} else {%>
           <td> User Name :</td><td> <input type="text" name="uname"
                               value="<c:out value="${user.uname}" />" /> </td>
            <%}%>
            </tr>
            <tr>
           <td> Password :</td><td> <input
                type="password" name="pass"
                value="<c:out value="${user.password}" />" /> </td>
            </tr>  
            <tr>  
            <td>
            Email : </td><td><input
                type="text" name="email"
                value="<c:out value="${user.email}" />" /> </td>
            </tr>  
            <% if (action.equalsIgnoreCase("edit")) {%>
           <tr>
           <td> Registration : </td><td><input
                type="text" name="dob"
                value="<fmt:formatDate pattern="yyyy/MM/dd" value="${user.registeredon}" />" readonly="readonly"/>(You Can't Change this)  
            </td>
            <%} else {%>
           <td> Registration : </td><td><input
                type="text" name="dob"
                value="<fmt:formatDate pattern="yyyy/MM/dd" value="${user.registeredon}" />" />(yyyy/MM/dd) </td>
            <%}%>
            </tr>
            <br/>
            <tr>
           <td> <input  type="submit" value="Submit" /></td><td><input  type="Reset" value="Reset" /></td>
            </tr>
           </Table>
        </form>
    </body>
</html>

-------------------------------------------------------------------------------------