Thursday 16 October 2014

Spring MVC with Jqgrid Subgrid using Hibernate ORM

Hello Friends hope you all are fine.today i am going to demonstrate you example of subgrid using spring mvc framework.the table structure will look like given below :

DROP TABLE IF EXISTS `studentdb`.`student`;
CREATE TABLE  `studentdb`.`student` (
  `id` varchar(20) NOT NULL,
  `name` varchar(50) NOT NULL,
  `college` varchar(45) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

DROP TABLE IF EXISTS `studentdb`.`location`;
CREATE TABLE  `studentdb`.`location` (
  `id` varchar(20) NOT NULL,
  `name` varchar(40) NOT NULL,
  `code` varchar(45) NOT NULL,
  `address` varchar(45) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Spring Controller will look given below :

package org.subgrid.controller;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.subgrid.dao.SubgridDaoImpl;
import org.subgrid.handler.JsonMapper;
import org.subgrid.service.SubgridService;


@Controller
public class SubgridController {

   
    //for subgrid demo
    @RequestMapping(value = "/getstudentDetails", method = RequestMethod.GET)
     public @ResponseBody void getstudentDetails( HttpServletRequest req,HttpServletResponse res,String para) throws IOException
     {
         //try{
               int page = Integer.valueOf(req.getParameter("page"));
               int limit =Integer.valueOf(req.getParameter("rows"));
               String sidx = req.getParameter("sidx");
               String sord =req.getParameter("sord");
             
             
               WebApplicationContext context=WebApplicationContextUtils.getWebApplicationContext(req.getSession().getServletContext());
                     
               SubgridDaoImpl dao=(SubgridDaoImpl) context.getBean("SubgridDaoImpl");
               SubgridService service =(SubgridService) context.getBean("SubgridService");
              
               Map<String, Object>map=service.getstudentDetails(dao, page, limit, sidx, sord, req, para);
          
               JsonMapper mapper=(JsonMapper) context.getBean("JsonMapper");
               mapper.WritecInJson(res, map);
             
     }
   
   //for subgrid demo
   
    @RequestMapping(value = "/getLocationDetails", method = RequestMethod.GET)
     public @ResponseBody void getLocationDetails(HttpServletRequest req,HttpServletResponse res,String para) throws IOException
     {
         //try{
             
               String id = req.getParameter("id");
            
               WebApplicationContext context=WebApplicationContextUtils.getWebApplicationContext(req.getSession().getServletContext());
                     
               SubgridDaoImpl dao=(SubgridDaoImpl) context.getBean("SubgridDaoImpl");
               SubgridService service =(SubgridService) context.getBean("SubgridService");

               Map<String, Object>map=service.getLocationDetails(dao, req, para,id);
         
               JsonMapper mapper=(JsonMapper) context.getBean("JsonMapper");
               mapper.WritecInJson(res, map);
     }
   
}

DAO layer will look like given below:
package org.subgrid.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;

import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.subgrid.entity.LocationDetail;
import org.subgrid.entity.Student;


@Repository
public class SubgridDaoImpl {

    private HibernateTemplate template;
   
       
        public SubgridDaoImpl(HibernateTemplate template) {
            this.template = template;
        }   
   
        public Map<String, Object> getstudentDetails(int page, int limit, String sidx,
                String sord, HttpServletRequest req, String para)
        {
            List<Student> acclist=template.find("from Student");
            Map<String, Object> map=new HashMap<String, Object>();
            map.put("page", page);
            map.put("list", acclist);
            return map;   

        }
        public Map<String, Object> getLocationDetails(HttpServletRequest req, String para,
                String id) {
           
            List<LocationDetail> acclist=template.find("from LocationDetail where id='"+id+"'");
            Map<String, Object> map=new HashMap<String, Object>();
            map.put("list", acclist);
            return map;   
           
        }
}
Service Layer:

package org.subgrid.service;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;
import org.subgrid.dao.SubgridDaoImpl;
import org.subgrid.entity.LocationDetail;
import org.subgrid.entity.Student;

@Service
public class SubgridService {


    //for subgrid by nisarg pathak
    public Map<String, Object> getstudentDetails(SubgridDaoImpl dao, int page,
            int limit, String sidx, String sord, HttpServletRequest req,
            String para) {
      
        Map<String, Object> map = dao.getstudentDetails(page, limit, sidx, sord,
                req, para);

        List<Student> list = (List<Student>) map
                .get("list");

        Map<String, Object> AccountingPeriodMap = new LinkedHashMap<String, Object>();
        List<Map<String, Object>> AccountingPeriodList = new ArrayList<Map<String, Object>>();

        Map<String, Object> AccountingPeriodSubMap = null;
        List<String> cell = null;
        int i = 0;
        for (Student supp : list) {
            i++;
            AccountingPeriodSubMap = new LinkedHashMap<String, Object>();
            AccountingPeriodSubMap.put("id", i);
            cell = new ArrayList<String>();
            cell.add(supp.getId()+ "");
            cell.add(supp.getName()+ "");
            cell.add(supp.getCollege()+ "");
           
            AccountingPeriodSubMap.put("cell", cell);
            AccountingPeriodList.add(AccountingPeriodSubMap);
        }
        AccountingPeriodMap.put("rows", AccountingPeriodList);
        AccountingPeriodMap.put("page", map.get("page"));
        AccountingPeriodMap.put("total", map.get("total"));
        AccountingPeriodMap.put("records", map.get("records"));
        return AccountingPeriodMap;
    }
    //for subgrid demo
    public Map<String, Object> getLocationDetails(SubgridDaoImpl dao,
            HttpServletRequest req, String para, String id) {
      
        Map<String, Object> map = dao.getLocationDetails(req, para,id);

        List<LocationDetail> list = (List<LocationDetail>) map
                .get("list");

        Map<String, Object> AccountingPeriodMap = new LinkedHashMap<String, Object>();
        List<Map<String, Object>> AccountingPeriodList = new ArrayList<Map<String, Object>>();

        Map<String, Object> AccountingPeriodSubMap = null;
        List<String> cell = null;
        int i = 0;
        for (LocationDetail supp : list) {
            i++;
            AccountingPeriodSubMap = new LinkedHashMap<String, Object>();
            AccountingPeriodSubMap.put("id", i);
            cell = new ArrayList<String>();
            cell.add(supp.getId() + "");
            cell.add(supp.getName()+ "");
            cell.add(supp.getAddress()+ "");

            AccountingPeriodSubMap.put("cell", cell);
            AccountingPeriodList.add(AccountingPeriodSubMap);
        }
        AccountingPeriodMap.put("rows", AccountingPeriodList);
        AccountingPeriodMap.put("page", map.get("page"));
        AccountingPeriodMap.put("total", map.get("total"));
        AccountingPeriodMap.put("records", map.get("records"));
        return AccountingPeriodMap;
    }

   
}
Json Handler Class:

package org.subgrid.handler;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.http.server.ServletServerHttpResponse;

    public class JsonMapper {
       
        public void WritecInJson(HttpServletResponse res,Object object)
        {
        MappingJacksonHttpMessageConverter jsonConverter = new MappingJacksonHttpMessageConverter();
        MediaType jsonMimeType = MediaType.APPLICATION_JSON;
       
        if(jsonConverter.canWrite(object.getClass(), jsonMimeType)){
            try{
            jsonConverter.write(object , jsonMimeType, new ServletServerHttpResponse(res));
       
            }catch(IOException e){
                e.printStackTrace();
            }catch(HttpMessageNotWritableException e){
                e.printStackTrace();
            }catch(Exception e){
                e.printStackTrace();
            }
        }else{
            System.out.println("reached in else");
        }

        }
    }

 Entity Classes:
package org.subgrid.entity;

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

@Entity
@Table(name="student")
public class Student {

    @Id @Column @GeneratedValue
    private String id;
    public String getId() {
        return id;
    }


    public void setId(String id) {
        this.id = id;
    }


    public String getName() {
        return name;
    }


    public void setName(String name) {
        this.name = name;
    }


    public String getCollege() {
        return college;
    }


    public void setCollege(String college) {
        this.college = college;
    }


    @Column
    private String name;
    @Column
    private String college;
   
   
    public Student() {
        // TODO Auto-generated constructor stub
    }
   
   
}

package org.subgrid.entity;

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


@Entity
@Table(name="location")
public class LocationDetail {

    @Id @Column @GeneratedValue
    private String id;
    @Column
    private String name;
    @Column
    private String code;
    @Column
    private String address;
   
    public LocationDetail() {
        // TODO Auto-generated constructor stub
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
   
   
   
   
   
}

Db Configuration Property File:

jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/studentdb
jdbc.username = root
jdbc.password = admin!@#


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>Optic Solution</display-name>

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

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>



    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationcontext-servlet.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>


    <servlet>
        <servlet-name>applicationcontext</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>applicationcontext</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>


</web-app>

applicationcontext-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context.xsd
     http://www.springframework.org/schema/mvc
     http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="org.subgrid.controller"></context:component-scan>
   
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

         <property name="location"><value>classpath:resources/dbConfig.properties</value> </property>
       
    </bean>

    <!-- Hibernate Configuration -->
    <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <bean id="mySessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="myDataSource" />

        <property name="annotatedClasses">
            <list>

                <value>org.subgrid.entity.LocationDetail</value>
                <value>org.subgrid.entity.Student</value>               
            </list>
        </property>

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect"> org.hibernate.dialect.MySQLDialect</prop>
                    <prop key="hibernate.show_sql">true</prop>
                  <prop key="hibernate.dbcp.initialSize">8</prop>
                  <prop key="hibernate.dbcp.maxActive">20</prop>
                  <prop key="hibernate.dbcp.maxIdle">20</prop>
                  <prop key="hibernate.dbcp.minIdle">0</prop>
                <prop key="hibernate.hbm2ddl.auto">none</prop>
            </props>
        </property>
       
    </bean>
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
        <constructor-arg ref="mySessionFactory" />
    </bean>
   
    <bean id="SubgridDaoImpl" class="org.subgrid.dao.SubgridDaoImpl">
        <constructor-arg ref="hibernateTemplate" />
    </bean>
   
    <bean id="SubgridService" class="org.subgrid.service.SubgridService">
    </bean>
   
    <bean id="JsonMapper" class="org.subgrid.handler.JsonMapper"></bean>
   
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="cacheSeconds" value="0" />
    </bean>
</beans>
   
index.jsp


<link rel="shortcut icon" href="images/icon.png">
<link type="text/css" rel="stylesheet" href="css/layout-default-latest.css" />
<link type="text/css" rel="stylesheet" href="css/bootstrap.min.css" id="default">

<link type="text/css" rel="stylesheet" href="css/font-awesome.min.css">
<link type="text/css" rel="stylesheet" href="css/jquery-ui.css">
<link type="text/css" rel="stylesheet" href="css/style.css" />
<link type="text/css" rel="stylesheet" href="css/ui.jqgrid.css"/>

    <link rel="stylesheet" type="text/css" href="css/smart-forms.css">
  <link rel="stylesheet" type="text/css" href="css/tabs.css">



<script type="text/javascript" src="script/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="script/bootstrap.js"></script>
<script type="text/javascript" src="script/jquery-ui.min.js"></script>
<script type="text/javascript" src="script/jquery.layout-latest.js"></script>
<script type="text/javascript" src="script/local/grid.locale-en.js" ></script>
<script type="text/javascript" src="script/jquery.jqGrid.min.js"></script>
<script type="text/javascript" src="script/jquery-ui-messageBox.js"></script>
<script type="text/javascript" src="script/jquery.blockUI.js"></script>
<script type="text/javascript" src="script/js/tabs.js"></script>


<script type="text/javascript" src="script/js/javascript.js"></script>



<script type="text/javascript">
jQuery(document).ready(function(){
 
    jQuery("#list14").jqGrid({
        url:'getstudentDetails.html',
                datatype: "json",
                colNames:['id',' Name','College'],
                colModel:[ {name:'id',index:'id'},
                           {name:'name',index:'name'},
                           {name:'college',index:'college'}
                           ],
                           rowNum:10,
                           rowList:[10,20,30],
                           pager: '#pager14', sortname: 'id', viewrecords: true,
                           sortorder: "desc", multiselect: false, subGrid : true,
                           subGridUrl: 'getLocationDetails.html?q=3',
                              subGridModel: [{ name : ['id','Name','Address'], width : [55,200,80],
                              params:['id']} ] ,
                              caption: "Subgrid with JSON Data" });
    jQuery("#list14").jqGrid('navGrid','#pager14',{edit:false,add:false,del:false});
});
</script>




<table id="list14"></table> <div id="pager14"></div>


it will look like given below :

Thanks for Reading this article .. For Any Query Ping me on pathak.nisarg@yahoo.com
Haappy Learning

Sunday 20 July 2014

Spring MVC with Jasper Report Integration

Hello Friends Hope you all are Fine.its been long time that i have posted a new post .well Reporting Tool always plays a major role in enterprise applications. I will going to demonstrate you Jasper Reports. for Designing & configuring Jasper Report i am using Ireport Designer 5.5.0 ,i will be using Traditional Student Application for showing reports.
The Project Structure is look like given below :





for connecting to db using ireport you need to go through https://www.netiq.com/documentation/idm401/reporting/data/bpbyf5y.html

The Report Layout in ireport designer will look like given below :

 You can download japer report jars from http://sourceforge.net/projects/jasperreports/files/

you have to put .jrxml and .jasper file into project classpath . Spring Controller will look like given below:

StudentController.java

package org.demo.controller;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.dbcp.BasicDataSource;
import org.dao.StudentDAO;
import org.demo.model.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

       

@Controller

public class StudentController
{
        @RequestMapping(method = RequestMethod.POST , value = "/GenerateReport")
        public @ResponseBody void generatePdfReport(ModelAndView modelAndView,HttpServletRequest request,HttpServletResponse response) throws SQLException{
   
            WebApplicationContext context =WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
            StudentDAO dao=(StudentDAO)context.getBean("studentDAO");
         
            BasicDataSource dataSource = (BasicDataSource)context.getBean("myDataSource");
            String contextPath = request.getServletContext().getRealPath("report/StudentReport.jrxml");
            dao.generatePdfReport(dataSource,contextPath);
         
         }
       
}
Dao Layer will be as given below :
StudentDAO.java

package org.dao;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

import org.apache.commons.dbcp.BasicDataSource;
import org.demo.model.Student;
import org.springframework.orm.hibernate3.HibernateTemplate;



public class StudentDAO
{
    private HibernateTemplate template;

    public HibernateTemplate getTemplate() {
        return template;
    }

    public void setTemplate(HibernateTemplate template) {
        this.template = template;
    }

    public StudentDAO(HibernateTemplate template) {
        this.template = template;
    }

     public void generatePdfReport(BasicDataSource dataSource, String contextPath) throws SQLException {
       
        Connection conn= dataSource.getConnection();
       

 try {
           
           
             InputStream input = new FileInputStream(new File(contextPath));
            
             System.out.println("Context Path is  : ="+contextPath);
              JasperDesign jasperDesign = JRXmlLoader.load(input);

            System.out.println("Compiling Report Designs");
            JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

            System.out.println("Creating JasperPrint Object");
            Map<String, String> parameters = new HashMap<String, String>();
            parameters.put("ReportTitle", "PDF JasperReport");

            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport,null,conn);

           // File f = new File("report/StudentReport.pdf");
         
            File f = new File("d:\\StudentReport.pdf");
             f.createNewFile();
         
            //Exporting the report
            OutputStream output = new FileOutputStream(f);

            JasperExportManager.exportReportToPdfStream(jasperPrint, output);

            System.out.println("Report Generation Complete");
            conn.close();
            }
             catch (Exception e) {
            e.printStackTrace();
            }
    }
}

add_student.jsp



<script type="text/javascript" src="script/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="script/bootstrap.js"></script>
<script type="text/javascript" src="script/jquery-ui.min.js"></script>
<script type="text/javascript" src="script/jquery.layout-latest.js"></script>
<script type="text/javascript" src="script/local/grid.locale-en.js" ></script>
<script type="text/javascript" src="script/jquery.blockUI.js"></script>



<script type="text/javascript" src="script/js/javascript.js"></script>

<script type="text/javascript" src="script/js/InitStudent.js"></script>

<script type="text/javascript" src="script/js/StudentLogic.js"></script>

<script type="text/javascript">

    $(document).ready(function(){
       
 $('#GenerateReport').click(function()
             {  
               
    $.ajax({
       
           url: "GenerateReport.html",
           dataType:'json',
           type:'post',
           data:  {},
           success: function (dataCheck)
           {
              },
               error: function (xhr, ajaxOptions, thrownError) {}
        });             
    });
    });
</script>
   
   
   
        <table>
            <tr>
                <td>id:<input type="text" id="txtid" name="txtid"></td>
            </tr>
           
            <tr>
                <td>Name:<input type="text" id="txtname" name="txtname"></td>
            </tr>
           
            <tr>
                <td><input type="button"  id="AddStudent" name="AddStudent" value="submit"></td>
            </tr>
           
            <tr>
                <td><input type="button"  id="GenerateReport" name="GenerateReport" value="Report"></td>
            </tr>
           
           
        </table>


The First page will look like given below:




 You can Refer my earlier Post redirect get Pattern using spring mvc example for xml configuration required for project .

when you click on generate report button file will be stored on D:/.Report will look like given below:






Thanks for Reading this article. for any query ping me on pathak.nisarg@yahoo.com



Sunday 20 April 2014

Spring Hello World with Apache Maven

Hello Friends .Hope you all are fine .today i am going to demonstrate you how we can develop Maven Based Application .Apache Maven can be used as a build tool which can add dependancy when project is created.the heart of Maven based Application.

You can download Apache Maven from its Official Site us  Maven Installation

This is how you can set your claspath
 


You have to download apache maven from official site of maven as well as you need to set classpath to make maven work,i am posting steps as given below

Project Structure will look like given below :


1)You need to Create Project on Command Line by Invoking Following Command :
mvn archetype:generate -DgroupId=Package_Name -DartifactId=ProjectName -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

2)Convert it into Maven project:
mvn eclipse:eclipse    

3)Import Project Into Eclipse

4) Run the Application

here it is Hello World is Ready .Output will look like given below

Thanks For Reading This Article






Wednesday 9 April 2014

Spring Roo-Basic Application


Hello Friends.Hope you all are fine.i am going to introduce you a new topic called Spring Roo. Spring Roo is a tool to facilitate Rapid Application Development.it is based on Roo shell.we can perform action by invoking commands on Roo Shell. well i have used Spring Tool Suite(STS) IDE in order to make simple Application & one thing more to note about it is Maven Based Application.

The Sample Project Structure will look like given below;

everything from creating model bojects to creatingtroller everything is based on invoking commands on Roo Shell.The general way to make Spring Roo Application is as given below:

1) we need to setup Database Provider as well as Database that we will going to use by invoking following command on Roo Shell.
jpa setup --provider HIBERNATE --database MYSQL

after invoking above command all dependancy related to provider will be  downloaded.


2)Create Entity class by invoking following command on Roo Shell.
 entity jpa --class org.student.Student
 [Note: above command will create blank Student Model]

3) add fields into Entity by invoking following command on Roo Shell.
field string --fieldName id
field string --fieldName name
field string --fieldName  college 



4)Create DAO Layer by invoking following command on Roo Shell. :
repository jpa --interface org.student.StudentDAO --entity org.student.Student

5)Create Service Layer  by invoking following command on Roo Shell:
service all --interfacePackage org.student

 6)configure controller by invoking following command on Roo Shell. :
web mvc setup
web mvc scaffold --class org.student.StudentController --backingType



your application is ready & you can perform crud operations on your model.


Thanks for reading this Post
For any query ping me on pathak.nisarg@yahoo.com




 

Monday 10 March 2014

Spring MVC +AJAX +Jersey with Database Integration

Hello Friends today i am going to demonstrate you how you can integrate spring with restful jersey web services.well you can manually hit url inorder to make url restul,here i have used ajax to remove complexity & calling web service without manually hitting url.

you need to have spring jar as well as jersey jar to make this example working. if you are making ajax calls than you need to have jquery javascript into your classspath.


Project Structure will look like given below:

detail code is as given below:

Model Class:
package org.bean;

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

@Entity
@Table(name="student")

public class Student
{
    @Id
    @Column(name="id")
    public int id;
    @Column(name="name")
    public String name;
   
    public Student(){ }
    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;

}

DAO LAYER:

package org.dao;

import java.util.List;

import org.hibernate.Query;
import org.bean.Student;
import org.springframework.orm.hibernate3.HibernateTemplate;

public class StudentDAO
{
   
    HibernateTemplate template;
    StudentDAO(HibernateTemplate template){
        this.template = template;
    }

    public List<Student> getStudentinfo(String param, StudentDAO dao)
    {
        String query = "from student where name = ?";
        return template.find(query,param);   
    }
   
    public void insert(Student student)
    {
        template.save(student);
    }

    public void update(Student student,String name)
    {
       
       
        Query query =template.getSessionFactory().openSession().createSQLQuery("update student set name=?  where  id='"+student.getId()+"'");

            query.setString(0, student.getName());
       
            int i =query.executeUpdate();
            System.out.println("Updated Succesfully..."+i);
    }

    public void delete(Student student,int studentid)
    {
   
    Query query =template.getSessionFactory().openSession().createSQLQuery("delete student where  id='"+student.getId()+"'");

        int i =query.executeUpdate();
       
       
    }

}

Controller: 
package org.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.bean.*;
import org.dao.*;

@Controller
@Path("/Student")
public class StudentController
{

      @GET
      @Produces({ MediaType.TEXT_PLAIN})
      @RequestMapping(value="{id}/{name}")
      public Response InsertStudent(@QueryParam("studentid") int studentid,@QueryParam("studentname") String studentname,@Context HttpServletRequest request)
      {
          WebApplicationContext context  = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
        
         StudentDAO dao = (StudentDAO) context.getBean("StudentDAO");
   
        
         System.out.println("ID:->"+studentid);
         System.out.println("NAME:->"+studentname);
         Student student = new Student();
         student.setId(studentid);
         student.setName(studentname);
         dao.insert(student);
        
        
        
         return Response.ok("Student id: "+studentid+"Student name :"+studentname).build();
      
        }

      @Path("/updatestudent")
      @GET
      @Produces({ MediaType.TEXT_PLAIN})
      @RequestMapping(value="{id}/{name}")
      public Response UpdateStudent(@QueryParam("studentid") int studentid,@QueryParam("studentname") String studentname,@Context HttpServletRequest request)
      {
          WebApplicationContext context  = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
        
         StudentDAO dao = (StudentDAO) context.getBean("StudentDAO");
   
        
         System.out.println("in update");

         Student student = new Student();
         student.setId(studentid);
         student.setName(studentname);
        
         dao.update(student,student.getName());        
        
         return Response.ok("Student id: "+studentid+"Updated Successfully").build();
      
        }
     

      @Path("/deletestudent")
      @GET
      @Produces({ MediaType.TEXT_PLAIN})
      @RequestMapping(value="{id}/{name}")
      public Response DeleteStudent(@QueryParam("studentid") int studentid,@QueryParam("studentname") String studentname,@Context HttpServletRequest request)
      {
          WebApplicationContext context  = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
        
         StudentDAO dao = (StudentDAO) context.getBean("StudentDAO");
   
         System.out.println("in delete");
        
         Student student = new Student();
         student.setId(studentid);
         student.setName(studentname);

          dao.delete(student,studentid);        
         return Response.ok("Student id: "+studentid+"Deleted Successfully...").build();
      
        }    
}


Here's the web.xml file:
<?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>SIMS</display-name>
  <welcome-file-list>
    <welcome-file>test.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>Jersey REST Service</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>com.sun.jersey.config.property.packages</param-name>
      <param-value>org.controller</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Jersey REST Service</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>WEB-INF/context-conf.xml</param-value>
  </context-param>
  <servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>*.html</url-pattern>
  </servlet-mapping>
</web-app>


spring-servlet.xml : should be in /WEB-INF

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context.xsd
     http://www.springframework.org/schema/mvc
     http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="org.controller" />

    <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    <property name="mediaTypes">
      <map>
          <entry key="html" value="text/html"></entry>
          <entry key="json" value="application/json"></entry>
          <entry key="xml"  value="application/xml"></entry>
      </map>
    </property>
     <property name="viewResolvers">
        <list>
          <bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
            <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
            <property name="prefix" value="/WEB-INF/jsp/"></property>
            <property name="suffix" value=".jsp"></property>
          </bean>
        </list>
    </property>
</bean>

</beans>

context-config.xml :Context Configuration file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context.xsd
     http://www.springframework.org/schema/mvc
     http://www.springframework.org/schema/mvc/spring-mvc.xsd">


    <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
   
        <property name="url" value="jdbc:mysql://localhost:3306/studentdb" />
        <property name="username" value="root" />
        <property name="password" value="admin!@#" />
    </bean>
    <bean id="mySessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="myDataSource" />
        <property name="annotatedClasses">
            <list>
                <value>org.bean.Student</value>
              
            </list>
        </property>

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">none</prop>
            </props>
        </property>
    </bean>

    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
        <constructor-arg ref="mySessionFactory" />
    </bean>   
    <bean id="StudentDAO" class="org.dao.StudentDAO">
        <constructor-arg ref="hibernateTemplate" />
    </bean>

</beans>


test.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>CRUD USING SPRING + JERSEY</title>>
<script src="script/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="script/jquery-ui.custom.min.js"></script>

<script>




$(document).ready(function()
 {
    alert("inside");
     $('#updatedata').click(function()
     {
         
         $.ajax({
              
                url: "rest/Student/updatestudent?"+$('#studentdetailform').serialize(),
                dataType:'json',
                type:'get',
                 
                
            });            
         
        });
   
     $('#savedata').click(function()
             {
                  alert("inside delete");
                 $.ajax({
                      
                        url: "rest/Student?"+$('#studentdetailform').serialize(),
                        dataType:'json',
                        type:'get',
                         
                         
                    });            
                 
                });
   
     $('#deletedata').click(function()
             {
                  alert("inside delete");
                 $.ajax({
                      
                        url: "rest/Student/deletestudent?"+$('#studentdetailform').serialize(),
                        dataType:'json',
                        type:'get',
                         
                        success: function(data)
                        { 
                          
                        } 
                    });            
                 
                });
   
});


</script>


</head>
<body>
   
    <form id="studentdetailform" method="get">
   
        <table border="2">
            <tr>
                <td>ID:<input type="text" id="studentid" name="studentid"></td>
                </tr>
                <tr>
                <td>NAME:<input type="text" id="studentname" name="studentname"></td>
                </tr>
                <tr>
                <td><input type="button" value="update" id="updatedata"  name="updatedata"></td>
                <td><input type="button" value="save" name="savedata" id="savedata"></td>
                <td><input type="button" value="delete" name="deletedata" id="deletedata"></td>
                </tr>
        </table>
    </form>

</body>

</html>

here there is no need to have output screenshots .so i am simply ignoring it.if you want more explanation than ping me.

thanks for reading this article.i hope you get something from it
for any query ping me on pathak.nisarg@yahoo.com
Regards

Friday 28 February 2014

Duplicate form submission Prevention using Spring MVC

Hello Friends  hope you all are doing well.today i am going to demonstrate how to prevent duplicate form submission using spring mvc.if url returns successview & if you refresh success page again and again than it might lead to multiple callback to database if method is interacting with url.

if you redirect to another page than request parameter will not be available to you.spring mvc will resolve both mentioned issues using Post Redirect Get pattern.


Spring mvc provides flash attributes in order to  resolve issue of duplicate form submission. you can put attributes into flashmap that you want to get into success view page & get that values into success page.

Project structure is as follows:


limitation of flash attribute is it is pertaining to single request only.for each single request ,flash attributes are available.i am posting code as given below : 


Model

package org.demo.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="student")
public class Student
{
   
    @Id @Column(name="id")
    private String studentid;
    @Column
    private String name;
   

   
    public Student(){}
    public String getStudentid() {
        return studentid;
    }


    public void setStudentid(String studentid) {
        this.studentid = studentid;
    }


    public String getName() {
        return name;
    }


    public void setName(String name) {
        this.name = name;
    }
   

}


DAO:

package org.dao;


import java.util.List;

import org.demo.model.Student;
import org.springframework.orm.hibernate3.HibernateTemplate;
public class StudentDAO
{
    private HibernateTemplate template;

    public HibernateTemplate getTemplate() {
        return template;
    }

    public void setTemplate(HibernateTemplate template) {
        this.template = template;
    }

    public StudentDAO(HibernateTemplate template) {
        this.template = template;
    }

    public void insert(Student student)
    {
      template.save(student);    
    }
    public List<Student> getStudents()
    {
        return template.find("from student");
            
    }   

}


Controller

package org.demo.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dao.StudentDAO;
import org.demo.model.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller

public class StudentController
{
   
    @RequestMapping(value="/showform", method=RequestMethod.GET)
    public String showForm(@ModelAttribute("student") Student stud) {
        return "add_student";
    }
        
        @RequestMapping(value="/add_student", method=RequestMethod.POST)
        public String addStudent(@ModelAttribute("student1") Student student1,
                final RedirectAttributes redirectAttributes,HttpServletRequest request,HttpServletResponse response)
        {
           
        WebApplicationContext context=WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
       
       
        StudentDAO studentdao =(StudentDAO) context.getBean("studentDAO");
        String  id=request.getParameter("txtid");
        String name=request.getParameter("txtname");
            
       
        Student student= new Student();
        student.setStudentid(id);
        student.setName(name);
       
       
           studentdao.insert(student);
   
            redirectAttributes.addFlashAttribute("student1", student);
            redirectAttributes.addFlashAttribute("message","Added successfully.");
             
           return "redirect:show_student.html";   
           
        }  
        @RequestMapping(value="/show_student", method=RequestMethod.GET)
        public String showStudent(@ModelAttribute("student1") Student student) {
          
            return "show_student";
        }
}

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>PostRedirectGetUsingSpringMVC</display-name>
 <welcome-file-list>
        <welcome-file>add_student.jsp</welcome-file>
       
    </welcome-file-list>
   <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
   
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/context-conf.xml</param-value>
    </context-param>
      
  <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
</web-app>

dispatcher-servlet.xml:->  place it in WebContent/WEB-INF/

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

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc  http://www.springframework.org/schema/mvc/spring-mvc.xsd">
  
  
   <context:component-scan base-package="org.demo.controller" />
    
    <mvc:annotation-driven/>
   
    <bean id="viewResolver"
              class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
              <property name="prefix">
                  <value>/</value>
               </property>
              <property name="suffix">
                 <value>.jsp</value>
              </property>
        </bean>
       
    </beans>


context-conf.xml: place it in WebContent/WEB-INF/

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context.xsd
     http://www.springframework.org/schema/mvc
     http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
     <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/studentdb" />
        <property name="username" value="root" />
        <property name="password" value="admin!@#"/>
</bean>

    <bean id="mySessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="myDataSource" />

        <property name="annotatedClasses">
           
                    <value>org.demo.model.Student</value>   
           
        </property>

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">none</prop>
            </props>
        </property>
    </bean>
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
        <constructor-arg ref="mySessionFactory" />
    </bean>
   
    <bean id="studentDAO" class="org.dao.StudentDAO">
        <constructor-arg ref="hibernateTemplate" />
    </bean>  
    
    
     </beans>



showform.jsp: -> homepage
<%
response.sendRedirect("add_student.jsp");

%>





add_student.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>Post->Redirect->get example </title>
</head>
<body>
   
    <form action="add_student.html" method="POST">
   
        <table>
            <tr>
                <td>id:<input type="text" id="txtid" name="txtid"></td>
            </tr>
           
            <tr>
                <td>Name:<input type="text" id="txtname" name="txtname"></td>
            </tr>
           
            <tr>
                <td><input type="submit"  value="submit"></td>
            </tr>
           
        </table>
    </form>
</body>
</html>





show_student.jsp

<html>
<body>
   
   <h2>${student1.name}added successfully..</h2>
</body>
</html>

the output will look like given below :

(1) simple form with id ,name


(2) after posting data to server  ,data will be stored in flash map,success view is returned & data will be stored into database.

(3) if you resubmit the form again when success view appears,it will simply remove flash attribute from flash map & just display added successfully. this is how you can prevent duplicate form submission.


thanks for reading. 
for any query ping me on pathak.nisarg@yahoo.com.
Enjoy Coding.

Spring Boot SSL configuration -Tomcat Server

Hi Friends hope you all are doing well. Today I am going to demonstrate about how to configure SSL in Spring boot web Application. Need o...