Monday 3 February 2014

Spring mvc with jqgrid simplified

Spring mvc with jqgrid simplified
Hello Friends.hope you all are fine.today i am going to demonstrate jqgrid functionality of jquery & how can we intract with database using spring mvc .jqgrid represents data in tabular  format.i am using json data for forwarding request & response to the client..
 
well i have included  jquery.jqGrid.min.js,jquery.min.js,jquery-ui.custom.js java script files into the classpath.
i am posting my code as given below :


Entity Class:
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
    private int studentid;

    @Column
    private String name;
    @Column
    private String college;
   
    public Student() { }
   
    public Student(int id, String name,String college)
    {
        this.studentid=id;
        this.name=name;
        this.college=college;
    }

    public int getStudentid() {
        return studentid;
    }

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

    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;
    }

}
Controller :

package org.demo.controller;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.demo.dao.StudentDAO;
import org.demo.model.Student;
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 com.orb.Utills.JsonMapper;

@Controller
public class StudentController {

    @RequestMapping(value = "/Data", method = RequestMethod.GET)
    public @ResponseBody
    void getStudent(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        // to get applicationcontext associated with ioc container -use to get
        // specific beans

        WebApplicationContext context = WebApplicationContextUtils
                .getWebApplicationContext(request.getServletContext());
        StudentDAO dao = (StudentDAO) context.getBean("StudentDAO");

        List<Student> list = dao.saveAllStudents();
        Map<String, Object> personMap = new LinkedHashMap<String, Object>();
        List<Map<String, Object>> personList = new ArrayList<Map<String, Object>>();
        Map<String, Object> personSubMap = null;
        List<String> cell = null;
        int i = 0;
        for (Student p : list) {
            i++;
            personSubMap = new LinkedHashMap<String, Object>();
            personSubMap.put("id", p.getStudentid());
            cell = new ArrayList<String>();
            cell.add(p.getStudentid() + "");
            cell.add(p.getName());
            cell.add(p.getCollege());

            personSubMap.put("cell", cell);
            personList.add(personSubMap);
        }
        personMap.put("rows", personList);
        personMap.put("records", i);
        JsonMapper json = (JsonMapper) context.getBean("JsonMapper");

        json.WritecInJson(response, personMap);

        /* return personMap; */
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public @ResponseBody
    void edit(HttpServletRequest request, HttpServletResponse res) {
        WebApplicationContext context = WebApplicationContextUtils
                .getWebApplicationContext(request.getServletContext());

        System.out.println("inside");

        int id = Integer.parseInt(request.getParameter("id"));
        String name = request.getParameter("name");
        String college = request.getParameter("college");
        String operation = request.getParameter("oper");

        StudentDAO dao = context.getBean("StudentDAO", StudentDAO.class);

        Student s = new Student(id, name, college);
        if (operation.equals("add")) {
            dao.insert(s);
            System.out.println(name);

            Map<String, Student> studentMap = new HashMap<String, Student>();
            studentMap.put("data", new Student(id, name, college));

            JsonMapper json = (JsonMapper) context.getBean("JsonMapper");

            json.WritecInJson(res, studentMap);

        }
        if (operation.equals("edit")) {
            System.out.println(name);

            dao.edit(id, name, college);

            Map<String, Student> studentMap = new HashMap<String, Student>();
            studentMap.put("data", new Student(id, name, college));

            JsonMapper json = (JsonMapper) context.getBean("JsonMapper");

            json.WritecInJson(res, studentMap);
        }
        if (operation.equals("del")) {
           dao.delete(id);
        }
   }
}
DAO:
package org.demo.dao;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.demo.model.Student;
import org.hibernate.Query;
import org.springframework.orm.hibernate3.HibernateTemplate;

public class StudentDAO
{
    private    HibernateTemplate template;
   
    public StudentDAO(HibernateTemplate template) throws Exception
    {
        this.template=template;
    }
   
public List<Student> saveAllStudents() throws Exception
{
    List<org.demo.model.Student> StudentList=template.find("FROM Student");
   
    return StudentList;
/*    System.out.println("Done");*/
}

public void insert(Student s)
{
    template.save(s);
}

public void edit(int id,String name,String college)
{
        
      Query query =template.getSessionFactory().openSession().createSQLQuery("update Student set name=? ,college=?  where studentid=? ");
      query.setString(0,name);
      query.setString(1,college);
     
      query.setInteger(2,id);
      
      int success=query.executeUpdate();
      System.out.println("updated SUCCESSFULLY!!!" +success);
   
}

public void delete(int id)
{       
        Query query =template.getSessionFactory().openSession().createSQLQuery("delete from  Student where studentid=? ");
                   
          query.setInteger(0,id);
          
          int success=query.executeUpdate();
          System.out.println("Deleted SUCCESSFULLY!!!");   
   
}
}
Mapper class: user defined json coverter 
package com.orb.Utills;

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");
        }

    }
}
JqgridDemo.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>
<script type="text/javascript" src="script/jquery.min.js"></script>
<script type="text/javascript" src="script/jquery.jqGrid.min.js"></script>
<script type="text/javascript" src="script/jquery-ui.custom.min.js"></script>



<link type="text/css" rel="stylesheet" href="css/style.css" />

<link type="text/css" rel="stylesheet" href="css/jquery-ui-1.10.0.custom.css"/>

<link type="text/css" rel="stylesheet" href="css/ui.jqgrid.css" />

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>JQGrid Demo</title>

<script type="text/javascript">

jQuery().ready(function (){
   

    /*
    $("#dialog").dialog({
        autoOpen : false,
        width : 650,
        resizable:false,
        modal : true,
        close : function(ev, ui) {
           
            alert("closed");
        }
    });
   
    $("#btn").click(function(){
       
       
        $("#dialog").dialog('open');
       
    }); */
   
   
    jQuery("#list1").jqGrid({
        url:'Data.html',
        editurl:'edit.html',
                datatype: "json",
                colNames:['ID','NAME','COLLEGE'],
                colModel:[
                         
                           {name:'id',index:'id', width:80,align:"right",editable:true,editoptions:{rows:"2",cols:"20"}},
                           {name:'name',index:'name', width:80,align:"right",editable:true,editoptions:{rows:"2",cols:"20"}},
                           {name:'college',index:'college', width:150, sortable:false,editable:true, editoptions:{rows:"2",cols:"20"}} ],
                           rowNum:10,
                           autowidth: true,
                           rowList:[10,20,30],
                           pager: jQuery('#pager1'),
                           sortname: 'id',
                           viewrecords: true,
                           sortorder: "desc",
                           caption:"CRUD" }).navGrid('#pager1',{ 'cellEdit': true,add : true,edit :true,save :true,addtext: 'Add',edittext:'edit',searchtext:'Search',deletetext:'delete',savetext:'Save',canceltext: 'Cancel',editable:true},{});
       
   


});

 $.jgrid.edit = {
        addCaption: "Add Student",
        editCaption: "Edit Student",
     
        bSubmit: "Submit",
        bCancel: "Cancel",
        bClose: "Close",
        bYes : "Yes",
        bNo : "No",
        bExit : "Cancel",
        closeAfterAdd:true,
        closeAfterEdit:true,
        reloadAfterSubmit:true,
       
        errorTextFormat: function (response) {
            if (response.status != 200) {
                return "Error encountered while processing. Please check the accuracy of data entered.";
            }
        },
      
        afterSubmit : function(response,postdata) {
                            return(true,"ok");
                            }
    };

 $("#dedata").click(function(){ var gr = jQuery("#delgrid").jqGrid('getGridParam','selrow'); if( gr != null ) jQuery("#list").jqGrid('delGridRow',gr,{reloadAfterSubmit:false}); else alert("Please Select Row to delete!"); });

$.jgrid.del = {
        caption: "Delete Student",
        msg: "Delete selected student?",
        bSubmit: "Delete",
        bCancel: "Cancel",
        reloadAfterSubmit:true,
        closeOnEscape:true,
        onclickSubmit : function(eparams) {
                                var rowData = $("#list").jqGrid('getRowData', 1);
                                var retarr = {'id':rowData['id']};
                                return retarr;
                                }  
    };
 jQuery("#list1").jqGrid('editRow',1,
        {
            keys : true,
            oneditfunc: function() {
                alert ("edited");
            }
        }); 
jQuery("#list1").jqGrid('navGrid', '#pager1', {edit : false,add : false,del : false,search : false});
jQuery("#list1").jqGrid('inlineNav',"#pager1",{add : true,edit :false,save :true,addtext: 'Add',savetext:'Save',canceltext: 'Cancel'});
    </script>
</head>
<body>
<div id="dialog">
<table id="list1"></table> <div id="pager1"></div>
</div>
<button id="btn" value="show"></button>

</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_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>TestJquery</display-name>
  <welcome-file-list>
       <welcome-file>jqgridDemo.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>

context 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/demo" />
        <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">
            <!-- <props>
                <prop key="classes" >org.demo.model.Student</prop>
            </props>
            <list>
                <value>org.demo.model.Student</value>
            </list> -->
        </property>

        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">false</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="JsonMapper" class="com.orb.Utills.JsonMapper"></bean>
 
    <bean id="StudentDAO" class="org.demo.dao.StudentDAO">
        <constructor-arg ref="hibernateTemplate" />
    </bean>
  
</beans>

the output will look like as given below :






hope you will get my point .thanks for reading this post
for any query ping me on pathak.nisarg@yahoo.com
Regards


Wednesday 29 January 2014

Hibernate JSF integration

Hibernate JSF integration

                         Hello Friends,today i am going to demonstrate you how hibernate orm framework can be integrated with JavaServerFaces.well for sake of simplicity i am not using annotation based configuration.i am pasting my code as given below.i am going to use traditional Student class for demonstrating the concept :

ManagedBean

package org.managedbean;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import org.dao.StudentDAO;


@ManagedBean(name="student")
@SessionScoped
public class StudentBean
{

        private int id;
        private String name;
        private String college;
        @ManagedProperty(value="#{studentDAO}")
        private StudentDAO dao;
       
       
        public StudentDAO getDao() {
            return dao;
        }
        public void setDao(StudentDAO dao) {
            this.dao = dao;
        }
        public StudentBean() {
            // TODO Auto-generated constructor stub
           
        }
        public StudentBean(int id,String name,String college)
        {
            this.id=id;
            this.name=name;
            this.college=college;
           
        }
       
        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 getCollege() {
            return college;
        }
        public void setCollege(String college) {
            this.college = college;
        }
       
        public void insert()
        {
            getDao().insert(this);

        }
       
}
 

DAO LAYER:
package org.managedbean;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import org.dao.StudentDAO;

@ManagedBean(name="student")
@SessionScoped
public class StudentBean
{

        private int id;
        private String name;
        private String college;
        @ManagedProperty(value="#{studentDAO}")
        private StudentDAO dao;
      
      
        public StudentDAO getDao() {
            return dao;
        }
        public void setDao(StudentDAO dao) {
            this.dao = dao;
        }
        public StudentBean() {
            // TODO Auto-generated constructor stub
          
        }
        public StudentBean(int id,String name,String college)
        {
            this.id=id;
            this.name=name;
            this.college=college;
          
        }
      
        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 getCollege() {
            return college;
        }
        public void setCollege(String college) {
            this.college = college;
        }
      
        public void insert()
        {
            getDao().insert(this);

        }
     
}

Util class:( for creating session factory)
package org.util;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

@ManagedBean
@SessionScoped
public class HibernateUtil
{
   
    private static final SessionFactory sessionfactory=buildSessionFactory();

    public static SessionFactory buildSessionFactory()
    {   
       
        try {
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    public static SessionFactory getSessionfactory() {
        return sessionfactory;
       
    }
  }
hibernate.cfg.xml-Configuration file
<?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>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/sample</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">admin!@#</property>
    <property name="hibernate.current_session_context_class">org.hibernate.context.ThreadLocalSessionContext</property>
    <mapping resource="Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>

Student.cfg.xml -mapping file
 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
     <class name="org.managedbean.StudentBean" table="student" catalog="sample">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity" />
        </id>
        <property name="name" type="string">
            <column name="name" length="45" not-null="true" />
        </property>
        <property name="college" type="string">
            <column name="college" length="45" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

data.xhtml
 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:f="http://java.sun.com/jsf/core"     
      xmlns:h="http://java.sun.com/jsf/html">

    <h:head>
        <title>Hibernate + JSF CRUD</title>
    </h:head>
    <h:body>
       
        <h:form>
        <table>
        <tr>
        <td><h:outputLabel value="id"> </h:outputLabel>
       
        <h:inputText id="id" value="#{student.id}"></h:inputText></td>
        </tr>
       
        <tr>
        <td><h:outputLabel value="name"> </h:outputLabel>
       
        <h:inputText id="name" value="#{student.name}"></h:inputText></td>
        </tr>
       
        <tr>
        <td><h:outputLabel value="college"> </h:outputLabel>
       
        <h:inputText id="college" value="#{student.college}"></h:inputText></td>
        </tr>
       
        </table>
           <h:commandButton value="Insert"   action="#{student.insert}"></h:commandButton>
        </h:form>
    </h:body>
</html>

index.jsp
<jsp:forward page="data.xhtml"></jsp:forward>



here is the entry in the mysql:


i hope you will get my point.for any query related to this topic ping me on pathak.nisarg@yahoo.com
thanks for reading  this post,in the next post i am going to demonstrate  how we can reverse engineer on hibernate ORM.
Regards



Monday 20 January 2014

Spring MVC+ Ajax + Itext PDF

Spring MVC+ Ajax + Itext PDF
 
Hello Friends.hope you all are doing well.today i am going to demonstrate you how to display pdf using spring mvc and itext library.well i am taking my traditional Student class to demonstrate the concept.i am making ajax call to the controller from where view will be returned &  pdf will be displayed on browser.

you need to have itext library along with spring jars into your classpath.

Model Class:-  Student.java
package org.demo.model;

public class Student
{
private String id;

private String name;
private String college;

public Student() {}
public Student(String id,String name,String college)
{
    this.id=id;
    this.name=name;
    this.college=college;
   
}

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;
}
 
}

Controller :StudentController.java

package org.demo.controller;

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

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

import org.demo.model.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.servlet.ModelAndView;

@Controller
public class StudentController
{

        @RequestMapping(value="/test",method=RequestMethod.POST)
        public ModelAndView processAjax(HttpServletRequest request,HttpServletResponse response)
        {
           
           
           
            String id=request.getParameter("id");
            String username=request.getParameter("name");
            String college=request.getParameter("college");
           
            System.out.println("ID:"+id);
           
            Student s=new Student(id,username,college);
            List<Student> studList =new ArrayList<Student>();
           
            studList.add(s);
           
           
            return new ModelAndView("PdfView","listStudent",studList);
           
        }
}

User Defined View Resolver class: PdfViewHandler.java


package org.demo.view;

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

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

import org.demo.model.Student;
import org.springframework.web.servlet.view.document.AbstractPdfView;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Font;
import com.itextpdf.text.Font.FontFamily;
import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Rectangle;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.PdfWriter;

public class PdfViewHandler extends AbstractPdfView
{

    @Override
    protected void buildPdfDocument(Map<String, Object> model, Document document,
            PdfWriter arg2, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        List<Student> listStudent=(List<Student>)model.get("listStudent");
       
        //adding Response header inorder to change default name of .pdf file
        response.addHeader("content-disposition","inline;filename=StudentReport.pdf");
       
       
        Table table=new Table(3);
        table.addCell("Id");       
        table.addCell("Name");
        table.addCell("College");
       
        for(Student  s: listStudent)
        {
            table.addCell(s.getId()+"");
            table.addCell(s.getName());
            table.addCell(s.getCollege());
        }
       
        document.add(table);
       
    }

}
index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<title>Sample pdf code</title>

 <script type="text/javascript">

$(document).ready(function(){
   
    $('#btn1').click(function() {
       
        $.ajax({
            url: "${pageContext.request.contextPath}/test.html",
            dataType:'json',
            method:'post',
            data:{id:$('#txtid').val(),name:$('#txtname').val(),college:$('#txtcollege').val()}
            });
       
    });
   
});




</script>


</head>
<body>
<form id="f1" 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>College:<input type="text"  id="txtcollege" name="txtcollege"></td>
    </tr>
     <tr>
        <td><input type="button"  id="btn1" value="submit"> </td>
    </tr>
   
</table>
</form>
</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_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>SpringwithPdf</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
 
 <servlet>
     <servlet-name>dispatcherservlet</servlet-name>
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 </servlet>

 <servlet-mapping>
    
     <servlet-name>dispatcherservlet</servlet-name>
     <url-pattern>*.html</url-pattern>
 </servlet-mapping>
</web-app>

view.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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    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">
   
    <bean id="PdfView" class="org.demo.view.PdfViewHandler"></bean>
   
    </beans>
dispatcherservlet-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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    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">
   
   <context:annotation-config></context:annotation-config>
  
  
   <context:component-scan base-package="org.demo.controller"></context:component-scan>
  
   <bean class="org.springframework.web.servlet.view.XmlViewResolver">
       <property name="order" value="1"></property>
       <property name="location">
          <value>/WEB-INF/view.xml</value>
       </property>
    </bean>  
  
   </beans>

the output will look like given below:
1) Ajax Call 



2)dowload dialog box opened & ask to download pdf ,pdf gets opened


i hope you will get my point.
for any query related to post ping me on pathak.nisarg@yahoo.com
Thanks
Regards


Saturday 18 January 2014

AbstractExcelView Using Spring MVC


 AbstractExcelView Using Spring MVC

Hello Friends Hope you all are fine.today i am going to demonstrate how we can work with Excel using Spring mvc.i am using AbstractExcelView using which we can add/display excel data. i am putting sample code here:

Model :
package org.demo.model;

public class Student
{
    private int id;
    private String name;
    private String college;
   
   
    public Student() { }
   
      public Student(int id,String name,String college)
      {
          this.id=id;
          this.name=name;
          this.college=college;
      }
    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 getCollege() {
        return college;
    }

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



Controller Class:


package org.demo.controller;

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

import org.demo.model.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class MainController
{
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String viewHome()
    {
        return "home";
    }
   
    @RequestMapping(value = "/downloadExcel", method = RequestMethod.GET)
    public ModelAndView downloadExcel()
    {
        // create some sample data
        List<Student> listStudents= new ArrayList<Student>();
        listStudents.add(new Student(1,"Nisarg","Semcom"));
        listStudents.add(new Student(2,"Raj","GLS"));
        listStudents.add(new Student(3,"Kinjal","Semcom"));
      

        // return a view which will be resolved by an excel view resolver
        return new ModelAndView("excelView", "listStudents", listStudents);
    }

}

ExcelBuilder.java which prepares view to be resolved


package org.demo.view;

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

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

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.demo.model.Student;
import org.springframework.web.servlet.view.document.AbstractExcelView;

public class ExcelBuilder extends AbstractExcelView
{

    @Override
    protected void buildExcelDocument(Map<String, Object> model,HSSFWorkbook workbook, HttpServletRequest arg2, HttpServletResponse arg3)
            throws Exception
    {
    List<Student> listStudents=(List<Student>) model.get("listStudents");
       
        HSSFSheet sheet=workbook.createSheet("listStudents");
        sheet.setDefaultColumnWidth(30);
       
        HSSFRow header=sheet.createRow(0);
        header.createCell(0).setCellValue("id");
        header.createCell(1).setCellValue("Name");
        header.createCell(2).setCellValue("College");

        int r=1;
       
        for(Student s: listStudents)
        {
            HSSFRow arow=sheet.createRow(r++);
           
            arow.createCell(0).setCellValue(s.getId());
            arow.createCell(1).setCellValue(s.getName());
            arow.createCell(2).setCellValue(s.getCollege());
           
        }
       
    }

}


home.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>
<h3><a href="/downloadExcel">Download Excel Document</a></h3>
</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>SpringExcelView</display-name>

 
  <servlet>
      <servlet-name>dispatcherservlet</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
 
  <servlet-mapping>
      <servlet-name>dispatcherservlet</servlet-name>
      <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

 
View.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    
    <bean id="excelView" class="org.demo.view.ExcelBuilder" />
    
</beans>

dispatcherservlet-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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

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

   <bean id="viewResolver1" class="org.springframework.web.servlet.view.XmlViewResolver">
        <property name="order" value="1"/>
        <property name="location" value="/WEB-INF/views.xml"/>
    </bean>
    
    <bean id="viewResolver2"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="order" value="2"/>
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
    </bean>

    
</beans>

the output will look like as given below:








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




Thursday 16 January 2014

Xml Marshalling/Unmarshaling using Spring Castor

 Spring Castor

Hello Friends hope you are fine .there are two ways using which we can perform Marshalling of java objects into xml and unmarshalling of xml element into tree of java object using spring framework.

there are two ways of unmarshalling/marshalling using spring:
(1)Spring Xstream
(2) Spring Castor

i am going to demonstrate Spring Castor.The Key differance between spring castor and oxm is that in cse of Spring castor one extra configuration file is required inorder to map java object with xml.

You need to add castor-1.3 jar and other core spring jars required to run spring base  application:

Project Structure :

sample code is given below :


Pojo Class
package org.castor.pojo;
//object that we want to marshal
public class Student
{
    private int id;
    private String name;
    private String college;
   
    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;
    }

    public String getCollege() {
        return college;
    }

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

}

applicationcontext.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" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">


<bean id="CastorMarshelingBean" class="org.springframework.oxm.castor.CastorMarshaller">
<property name="targetClass" value="org.castor.pojo.Student"></property>
<property name="mappingLocation"  value="mapping.xml"></property>
</bean>



</beans>



mapping.xml : to map java objets with corresponding xml element
<?xml version="1.0" encoding="UTF-8"?>
      
    <mapping> 
        <class name="org.castor.pojo.Student"> 
          <map-to xml="Student"/> 
          <field name="id" type="integer"> 
             <bind-xml name="id" node="element"/> 
          </field> 
          <field name="name" type="string"> 
             <bind-xml name="name" node="element"/> 
          </field> 
          <field name="college" type="string"> 
             <bind-xml name="college" node="element"/> 
          </field> 
            </class> 
    </mapping>

Client Class

package org.castor.client;

import java.io.FileWriter;
import java.io.IOException;

import javax.xml.transform.stream.StreamResult;

import org.castor.pojo.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.XmlMappingException;

public class Client
{
    public static void main(String args[]) throws XmlMappingException, IOException
    {
   
        ApplicationContext context= new ClassPathXmlApplicationContext("applicationcontext.xml");
        Marshaller m=(Marshaller) context.getBean("CastorMarshelingBean");
       
        Student s=new Student();
        s.setId(1);
        s.setName("nirali");
        s.setCollege("Semcom");
       
        m.marshal(s,new StreamResult(new FileWriter("D:\\Student.xml")));
       
       
        System.out.println("Task Completed!!!");
       
    }

}

 the console will look like given below:





Thanks for reading this artilcle  for any query ping me  related to this post ping me on pathak.nisarg@yahoo.com
Regards
 


 




Monday 13 January 2014

ContentNagotiationViewResolver example using Spring MVC

ContentNagotiationViewResolver  using Spring MVC

Hello Friends.hope you are doing well.today i am going to demonstrate you ContentNagotiationViewResolver .suppose i want to access the same resource with differant media types.than client can access the resource using ContentNagotiationViewResolver.suppose client want xml form of resouce than he can get it using ContentNagotiationViewResolver  feature of spring mvc.

Spring oxm and jackson Api should be on classpath for execution of above code:

Sample code i am going to demonstrate is given below:

Model Class (jaxb annotated)


package org.demo.model;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Student
{
   
    int id;
   
    String name;
   

    public Student() { }
    public Student(int id,String name)
    {
        this.id=id;
        this.name=name;
    }
    public int getId() {
        return id;
    }
   
    @XmlElement
    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }
    @XmlElement
    public void setName(String name) {
        this.name = name;
    }


}

StudentController.java

package org.demo.controller;

import org.demo.model.Student;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value="/Student")
public class StudentController
{

@RequestMapping(value="{id}/{name}",method=RequestMethod.GET,produces="application/json")
public String getStudent(@PathVariable int id,@PathVariable String name,ModelMap model)
{
        Student s=new Student(id,name);
    model.addAttribute("student", s);
       
    return "Data";
   
}
}
 

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>SpringContentNagotioationViewResolver</display-name>
  <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
  <servlet-name>ContentNagotiation</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  <servlet-name>ContentNagotiation</servlet-name>
      <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

ContentNagotiation-servlet.xml


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


 <context:component-scan base-package="org.demo.controller"></context:component-scan>
 <mvc:annotation-driven/>
 <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
 <property name="order" value="1"></property>

 <property name="mediaTypes">
 <map>
         <entry key="json" value="application/json"></entry>
         <entry key="xml" value="application/xml"></entry>
   </map>
 </property>

 <property name="defaultViews">
        <list>
          <!-- JSON View -->
          <bean
            class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
          </bean>

       

          <!-- JAXB XML View -->
          <bean class="org.springframework.web.servlet.view.xml.MarshallingView">
            <constructor-arg>
                <bean class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
                   <property name="classesToBeBound">
                    <list>
                       <value>org.demo.model.Student</value>
                    </list>
                   </property>
                </bean>
            </constructor-arg>
          </bean>
         </list>
      </property>
      <property name="ignoreAcceptHeader" value="true" />

    </bean>

   
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="order" value="2" />
        <property name="prefix">
            <value>/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

 </beans>


Data.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>

Student Id: ${student.id}
Student Name: ${student.name}
</body>
</html>

The output of the code is look like below:








i hope you will get my point.for any query ping me on pathak.nisarg@yahoo.com.
Thanks for reading this article.
Regards.

Sunday 12 January 2014

Fetching RSS Feed Data

 Fetching RSS Feed Data 

Hello Friends ,today i am going to demonstrate you how to get RSS Feed using ROME API.in this example i am going to show you feeds from my blogspot.jars required for implementing below code is ROME.jar ,jdom 1.1 jar,purl-org-content-0.3.jar.
 
ROME represents syndication feeds (RSS and Atom) as instances of the com.sun.syndication.synd.SyndFeed interface.

Sample Code:


package org.demo.rssfeed;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;

import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;

public class RssDemo
{
    public static void main(String args[]) throws IOException, IllegalArgumentException, FeedException
    {
        //you can define url as per your requirement
         //URL url  = new URL("http://nisargpathak.blogspot.com/feeds/6414895901982451683/comments/default");
        URL url  = new URL("http://nisargpathak.blogspot.com/feeds/5437369693711411335/comments/default");
         XmlReader reader = null;
           
            try {
               
                reader = new XmlReader(url);
                SyndFeed feed = new SyndFeedInput().build(reader);
                System.out.println("Feed Title: "+ feed.getAuthor());
          
               for (Iterator i = feed.getEntries().iterator(); i.hasNext();)
               {
                  SyndEntry entry = (SyndEntry) i.next();
                  System.out.println(entry.getTitle());
                      }
                  } finally {
                      if (reader != null)
                          reader.close();
                  }
    }
 

}
Sample Output is given below:









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

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...