Thursday 19 December 2013

how to create a simple Gujarati or any language web application in struts2 and hibernate with mysql


 whenever we create a simple jsp page or html file the default char set is 'ISO' like <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
Because it treats English is the standard language for developing a web application.
So in order to make language specific application first we need to change the charset from ex: charset=ISO-8859-1 to charset="UTF-8".

Now I am going to create a simple application having text box is an input field to enter text in any language store it in the database and displays on the same web page.
  
CREATE TABLE `student_master` (
  `student_id` int(20) NOT NULL auto_increment,
  `student_fname` varchar(20) character set utf8 default NULL,
  `student_mname` varchar(30) character set utf8 default NULL,
  `student_lname` varchar(30) character set utf8 default NULL,
  `student_p_add` varchar(70) character set utf8 default NULL,
  `status` tinyint(1) default NULL,
  `temp6` varchar(40) character set utf8 default NULL,
  PRIMARY KEY  (`student_id`)
) ENGINE=MEMORY  DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;

Studentform.jsp
<%@ page pageEncoding="UTF-8"%>

<%@taglib uri="/struts-tags" prefix="s"%>
<%@ taglib prefix="sj" uri="/struts-jquery-tags"%>

<!doctype html>
<html lang="en">

<head>
    <meta http-equiv="Content-Language" content="hi">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
 <header> <h3>વિદ્યાર્થી રજીસ્ટ્રેશન ફોર્મ</h3> </header>
<div id="tablesorter" style="font-style:inherit;font-size:15px;font-variant:inherit;font-style: inherit;font-weight: normal;color:#2C333D;background-color: #E5E5E5 ">
<center>   
<s:form action="addStudent!addStudentdata.action"name="student" enctype="multipart/form-data"  >
<table>
 <tr>
 <td align="left">
            <s:textfield name="FirstName" label="નામ"  size="25" id="my"/>   
</td>
<td align="right" colspan="1">     
            <s:textfield name="MiddleName" label="પિતા / પતિ નામ"  id="target" id="my"></s:textfield>
</td>
</tr>
<tr>
      <td>
            <s:textfield name="LastName" label="અટક" id="my"></s:textfield>
     
      </td>
     
</tr>
      <tr>
      <td> 


      <s:textfield name="permanentAddress"label="કાયમી સરનામું" id="my"/>
      </td>
      </tr>
     
      <tr align="left">
            <td height="" colspan="2" align="left">
     
      <s:textfield name="Phonenumber"     label="ફોન નંબર" id="my"></s:textfield>
      </td>
      </tr>
     
      <tr align="center">
            <td height="47" colspan="2" align="center">
            <s:submit value="સાચવો" name="userSave" theme="simple" id="colorsubmit"></s:submit>
            <s:submit id="colorsubmit" value="રદ કરો" theme="simple"/>

              </td>
            </tr>
     
</table>

</s:form>
</center>
</div>

</body>
</html>

Now I have defined the charset is "UTF-8" which is essential for any language.Now the form tag contains one text box to enter text.We need to define a accept-charset attribute of form tag to "UTF-8" to send the request to server in hindi language.
Now if the method attribute of form tag is "Get" then we need to specify request.setCharacterEncoding("UTF-8") in our Action class. and If we are using "POST" method means request is in the body then we need to add the attribute URIEncoding="UTF-8" in the server.xml file of tomcat which is in the conf directory.
for Ex:

 <Connector port="8080" maxHttpHeaderSize="8192"
               maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
               enableLookups="false" redirectPort="8443" acceptCount="100"
               connectionTimeout="20000" disableUploadTimeout="true" URIEncoding="UTF-8" />

struts.xml
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
<struts>
 <package name="default" extends="struts-default">
            <action name="addStudent" class="Action.StudentAction">
                  <result name="Home">studentregistration.jsp</result>
                  <result name="success">studentview.jsp</result>
            </action>
      </package>
</struts>
StudentAction.java

package Action;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionMessages;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.SessionAware;

import service.studentservice;
import master.StudentMaster;

import DAO.studentdao;
import bean.StudentBean;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class StudentAction  extends ActionSupport implements ModelDriven<StudentBean>,ServletRequestAware,SessionAware {

            boolean insert = false;
            StudentBean sbean=new StudentBean();
            studentdao sdao=new studentdao();
            StudentMaster studentmaster=new StudentMaster();
            List<StudentMaster> liststudent;
            private Map<String, Object> ses;
            HttpServletRequest request;
            boolean isinsert=false;
            Logger logger = Logger.getLogger(StudentAction.class);

            public String addStudentdata()throws Exception{
                 
           
                  System.out.println("Inside addStudent()....");
           
                  try{
                         isinsert = studentservice.addstudent(sbean);
                        if(isinsert){
                  addActionMessage("Student details add successfully");                         getStudentList();
                        }
                        else{
                              addActionError("error:001");
                        }
                  }catch (Exception e) {
                        e.printStackTrace();
                  }
            return "success";
      }
           
            public String getStudentList()throws Exception{
                 
                  try {      
                        liststudent = sdao.getstudent();
                        ses.put("liststudent",liststudent);            
                  } catch (Exception e) {
                        e.printStackTrace();
                  }
                  return "view";
            }
            public StudentBean getModel() {
                  // TODO Auto-generated method stub
                  return sbean;
            }
            public void setServletRequest(HttpServletRequest req) {
                  // TODO Auto-generated method stub
                  this.request=req;
            }
            public void setSession(Map<String, Object> ses) {
                  // TODO Auto-generated method stub
                  this.ses=ses;
            }

            public HttpServletRequest getHttpServletRequest() {
                  return request;
            }


            public Map<String, Object> getSes() {
                  return ses;
            }
      }
StudentBean.java

package bean;

import java.util.Date;

public class StudentBean  implements java.io.Serializable{
      /**
       *
       */
      private static final long serialVersionUID = 1L;
      private String studid;
      private int studentid;
      private String FirstName;
      private String MiddleName;   
      private String LastName;
      private String Phonenumber;
      private String permanentAddress;
     
     
      public String getMotherName() {
            return MotherName;
      }
      public void setMotherName(String motherName) {
            MotherName = motherName;
      }
      public String getPhonenumber() {
            return Phonenumber;
      }
      public void setPhonenumber(String phonenumber) {
            Phonenumber = phonenumber;
      }
     
      public String getFirstName() {
            return FirstName;
      }
      public void setFirstName(String firstName) {
            FirstName = firstName;
      }
      public String getMiddleName() {
            return MiddleName;
      }
      public void setMiddleName(String middleName) {
            MiddleName = middleName;
      }
      public String getLastName() {
            return LastName;
      }
      public void setLastName(String lastName) {
            LastName = lastName;
      }
      public String getPermanentAddress() {
            return permanentAddress;
      }
      public void setPermanentAddress(String permanentAddress) {
            this.permanentAddress = permanentAddress;
      }
      public String getFatherName() {
            return FatherName;
      }
      public void setFatherName(String fatherName) {
            FatherName = fatherName;
      }
      }
}

studentservice.java

package service;

import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import DAO.studentdao;
import bean.StudentBean;

import master.StudentMaster;

public class studentservice implements SessionAware {
     
       Map<String,Object> ses;
     
      public static boolean addstudent(StudentBean b) {
            // TODO Auto-generated method stub
            StudentMaster sm=new StudentMaster();
            studentdao dao=new studentdao();
            boolean add=false;
            try{
                  sm.setStudentFname(b.getFirstName());
                  sm.setStudentMname(b.getMiddleName());
                  sm.setStudentLname(b.getLastName());
                  sm.setStudentBdate(b.getBirthDate());
                  sm.setStatus(true);
                  sm.setStudentPAdd(b.getPermanentAddress());
                  add=dao.addstudent(sm);
            } catch (Exception e) {
                  e.printStackTrace();
            }
            return add;
            }    
      public void setSession(Map<String, Object> session) {
            // TODO Auto-generated method stub
            this.ses=session;
      }

}
studentdao.java  
package DAO;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.Session;

import util.HibernateUtil;
import master.StudentMaster;

import bean.StudentBean;

public class studentdao {

      Session session;
      public String date;

      public boolean addstudent(StudentMaster studentmaster)
      {
            boolean isInserted = false;
            try
            {
                  session = HibernateUtil.getSession();
                  session.beginTransaction();
                  session.save(studentmaster);
                  session.getTransaction().commit();
                  session.flush();
                  session.close();
                  session = null;
                  isInserted = true;
            }
            catch (Exception e)
            {
                  e.printStackTrace();
            }
            return isInserted;
      }

      @SuppressWarnings("unchecked")
      public List<StudentMaster> getstudent() {
            // TODO Auto-generated method stub
            List<StudentMaster>list = null;
            try {
                  session = HibernateUtil.getSession();
                  session.beginTransaction();
                  session.getTransaction().commit();
                  Query query = session.createQuery(" from StudentMaster");
                  list = query.list();
                  System.out.println("You Now in Student List");
                  System.out.println("List Size : "+list.size());
                  session.flush();
            } catch (Exception e) {
                  e.printStackTrace();
            }
            return list;
           
      }    
}

studentview.jsp

<%@ page pageEncoding="UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib uri="http://displaytag.sf.net" prefix="display"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!doctype html>
<html lang="en">

<head>
<meta charset="utf-8" />
</head>

<body>
<header>
<h3>વિદ્યાર્થી માહિતી</h3>
</header>
<table>
      <s:form action="addStudent!getStudentList.action" id="studentview" name="studentview">
      <display:table id="liststud" list="${liststudent}" width="80%" border="1" pagesize="8" class="">
            <s:hidden name="liststud.studentId" key="studentId" value="%{liststud.studentId}"/>      
                  <display:column title="નંબર"><%=liststud_rowNum%></display:column>
                 
                  <display:column title="નામ" property="studentFname"></display:column>
                  <display:column title="પિતા / પતિ નામ" property="studentMname"></display:column>
                  <display:column title="અટક" property="studentLname"></display:column>
                  <display:column title="કાયમી સરનામું" property="studentPAdd"></display:column>
                  <display:column title="Action">
                  <img src="images/icn_edit.png" id="colorsubmit" onclick="javascript:updateStudent(${liststud.studentId})"></img>
                  &nbsp; &nbsp;
                  <img src="" onclick=""></img>
                  </display:column>

            </display:table>
      </s:form>
</table>
</body>
</html>

Next step is store the value taken from the form onto the hibernate.
Now in the hibernate.cfg.xml if we are using JNDI as a datasource then we have to do some changes in the context.xml of tomcat which is in the conf directory.
Like

<Resource name="jndi_ialds" auth="Container" type="javax.sql.DataSource" removeAbandoned="true"
                                    removeAbandonedTimeout="60" logAbandoned="true"
              maxActive="100" maxIdle="30" maxWait="10000"
               username="root" password="" driverClassName="com.mysql.jdbc.Driver"
               url="jdbc:mysql://localhost/dbname?autoReconnect=true&amp;useUnicode=true&amp;characterEncoding=utf8"/>


and if we are using a driver class in the hibernate.cfg.xml file the we add to property in our hibernate.cfg.xml file like:

<property name="connection.useUnicode">true</property>
<property name="connection.characterEncoding">UTF-8</property>

Now after following these simple steps we can inset or display the Gujarati text.


No comments:

Post a Comment

Comment