Friday, 14 March 2014

Spring Rest MVC + JSP + Jquery


Spring MVC + REST + JSP + Jquery
This post explains how a application can be made with a combination of Spring  Rest MVC + JSP Jquery.

Below is the pom

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.nihilent.rest</groupId>
  <artifactId>rest-web-app</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>rest-web-app</name>
  <url>http://maven.apache.org</url>
  <build>
  <finalName>rest-web-app</finalName>
 </build>
  <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <spring.version>3.2.2.RELEASE</spring.version>
  <java.version>1.6</java.version>
  <servlet-api.version>2.5.0</servlet-api.version>
 </properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
     <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-web</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>commons-logging</groupId>
   <artifactId>commons-logging</artifactId>
   <version>1.1.1</version>
  </dependency>
  <dependency>
   <groupId>log4j</groupId>
   <artifactId>log4j</artifactId>
   <version>1.2.16</version>
  </dependency>
  <!-- JSTL -->
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>jstl</artifactId>
   <version>1.1.2</version>
  </dependency>

  <dependency>
   <groupId>taglibs</groupId>
   <artifactId>standard</artifactId>
   <version>1.1.2</version>
  </dependency>

  <!-- for compile only, your container should have this -->
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>servlet-api</artifactId>
   <version>2.5</version>
   <scope>provided</scope>
  </dependency>
  <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>4.11</version>
   <scope>test</scope>
  </dependency>
  <dependency>
   <groupId>commons-codec</groupId>
   <artifactId>commons-codec</artifactId>
   <version>1.8</version>
  </dependency>
  </dependencies>
</project>

Below is the web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- * This software is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES 
 OR CONDITIONS OF ANY KIND. -->
<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"
 version="2.5">
 <display-name>Order Web Service</display-name>

 <context-param>
  <param-name>log4jConfigLocation</param-name>
  <param-value>/WEB-INF/classes/log4j.xml</param-value>
 </context-param>

 <listener>
  <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
 </listener>

 <servlet>
  <servlet-name>rest</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>rest</servlet-name>
  <url-pattern>/rest/*</url-pattern>
 </servlet-mapping>
 <welcome-file-list>
 <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
</web-app>

Spring context file rest-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:tx="http://www.springframework.org/schema/tx"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:oxm="http://www.springframework.org/schema/oxm"
 xmlns:util="http://www.springframework.org/schema/util"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
  http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
  http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
  http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"
  default-autowire="byName">
 
 <context:component-scan base-package="com.nihilent.*" />
 <mvc:annotation-driven />

 <bean
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix">
   <value>/WEB-INF/pages/</value>
  </property>
  <property name="suffix">
   <value>.jsp</value>
  </property>
 </bean>
</beans>

XML request message which will be needed to create XSD

<login>
<username>admin</username>
<password>admin</password>
</login>
<response>
<message>login successful</message>
</response>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="response">
    <xs:complexType>
      <xs:sequence>
        <xs:element type="xs:string" name="message"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

The Message XSD that can be created from any online tool from a XML

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="login">
    <xs:complexType>
      <xs:sequence>
        <xs:element type="xs:string" name="username"/>
        <xs:element type="xs:string" name="password"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

Pojo created from the XSD. The POJO can be created by using the xjc command of JDK

package com.nihilent.model;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;


@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "username",
    "password"
})
@XmlRootElement(name = "login")
public class Login {

    @XmlElement(required = true)
    protected String username;
    @XmlElement(required = true)
    protected String password;

    public String getUsername() {
        return username;
    }
    public void setUsername(String value) {
        this.username = value;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String value) {
        this.password = value;
    }

}

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "message"
})
@XmlRootElement(name = "response")
public class Response {

    @XmlElement(required = true)
    protected String message;

   
    public String getMessage() {
        return message;
    }

    
    public void setMessage(String value) {
        this.message = value;
    }

}

Controller class RestController.java

package com.nihilent.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.nihilent.model.Login;
import com.nihilent.model.Response;

@Controller

public class RestController {
 
 @RequestMapping(value = "/login", method = RequestMethod.POST, headers = "Accept=application/xml")
 public @ResponseBody
 Response login(@RequestBody Login login) {
  Response response = new Response();
  if(login.getUsername().equals("admin") && login.getPassword().equals("admin")){
   response.setMessage("login successful");
  }else{
   response.setMessage("login invalid");
  }
  
  return response;
 }
}


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">
<title>Insert title here</title>
<script type="text/javascript" src="scripts/jquery-ui.min.js"></script>
<script type="text/javascript" src="scripts/jquery.js"></script>

<link rel="stylesheet" href="styles/jquery-ui.css" type="text/css" />
</head>
<script>
 $(document).ready(function() {

 });
 function submitfun() {

  $.ajax({
   type : "POST",
   headers : {
    "Content-Type" : "application/xml"
   },
   url : 'rest/login',
   dataType : "xml",
   data : '<?xml version="1.0" encoding="UTF-8"?><login><username>'
     + $('#username').val() + '</username><password>'
     + $('#password').val() + '</password></login>',
   success : function(response) {

    $(response).find('message').each(function() {
     $('#response').html($(this).text());
    });

   },
   error : function(response) {
    alert('error:' + response);
   }
  });
 }
</script>
<body>

 <h1 align="center">Spring 3.0 MVC Rest + Jquery + JSP</h1>
 <table cellpadding="5" cellspacing="5" align="center"
  style="vertical-align: middle; border: 1px solid #ccc; background: #F1F6F6">
  <tr>
   <td>Username</td>
   <td><input id="username" type="text"></input></td>
  </tr>
  <tr>
   <td>Password</td>
   <td><input id="password" type="password"></input></td>
  </tr>
  <tr>
   <td align="center" colspan="2"><input type="button"
    value="Login" onclick="submitfun();" /></td>
  </tr>

 </table>

 <div align="center" id="response"></div>
</html>

The final structure of the project should be like :
Get the source code from here


The same rest service can also be tested using Google chrome app - Advanced Rest Client.
To know how see this blog
The rest service can also be tested using a HTTP client API from Apache which simulates the HTTP request. To see how it can be implemented, refer this blog

For Web Service Introduction click here

Below are some posts that explain how to implement and test SOAP/REST Webservices

Host
SOAP REST
JAX-WS JAX-RS
Spring-ws Spring-MVC-REST
Client
SOAP REST
JAX-WS(wsimport) Google REST APP
SOAP UI Apache REST

Share the post