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

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