JAX-RS Web Service + JAXB Example

JAX-RS Web Service + JAXB Example

JAXB API helps to map java object to xml and xml to java objects, in this example we are using JAXB to convert java objects to xml  
 
In this example we will see how the object to xml mapping is working using JAXB.
 

1. Create a maven project using the quick start archetype and add below dependencies in your pom.xml file
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>9.2.3.v20140905</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>9.2.3.v20140905</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-jetty-http</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
<version>2.7</version>
</dependency>

2. Create a simple service 

package com.vinod.vinod_rest_examples;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/state")
public class JaxRsJaxBController {
    //http://localhost:8080/state/KL
    @GET
    @Path("/{param}")
    @Produces(MediaType.APPLICATION_XML)
    public State getStateXML(@PathParam("param") String code) {
        State state = new State();
        state.setCode("KL");
        if (code.equals("KL")) {
            state.setName("KERALA");
        }
        return state;
    }
}
  

3. Create a java class to start jetty server

package com.vinod.vinod_rest_examples;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

/**
 * Hello world!
 *
 */

public class App {
    public static void main(String[] args) {
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");

        Server jettyServer = new Server(8080);
        jettyServer.setHandler(context);

        ServletHolder jerseyServlet = context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/*");
        jerseyServlet.setInitOrder(0);

        // Setting pacakge name over here to load services
        jerseyServlet.setInitParameter("jersey.config.server.provider.packages", "com.vinod.vinod_rest_examples");
        try {
            jettyServer.start();
            jettyServer.join();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            jettyServer.destroy();
        }
    }
}
  

4. Hit the urls for testing

 
 
 
 

JAX-RS WebService @FormParam Example

JAX-RS @FormParam example

JAX-RS Binding values to method parameters

To call any service we need to bind the request to the resource method, in order to bind this JAX-RS has provided few parameter types, the data will be taken from these parameters by using the annotaions. Whenever JAX-RS provider receives an http request, it finds an appropriate java method  that can service this request.
In this example we will see how to use @formparam

1. Create a maven project using the quick start archetype and add below dependencies in your pom.xml file
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>9.2.3.v20140905</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>9.2.3.v20140905</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-jetty-http</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
<version>2.7</version>
</dependency>

2. Create a simple service 

package com.vinod.vinod_rest_examples;

import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.POST;

@Path("/stateform")
public class FormParmController {
    @POST
    @Path("/state")
    @Produces("application/xml")
    public Response getMsg(@FormParam("country") String country, @FormParam("state") String state) {
        String stateDetails = null;
        if (country.equals("India") & state.equals("KL")) {
            stateDetails = "<State><name>KERALA</name><shortname>KL</shortname>"
                    + "<headq>TRIVANDRUM</headq><language>MALAYALAM</language></State>";
        } else {
            stateDetails = "Data not found";
        }
        return Response.ok().entity(stateDetails).build();

    }
}
  

3. Create a java class to start jetty server

package com.vinod.vinod_rest_examples;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

/**
 * Hello world!
 *
 */

public class App {
    public static void main(String[] args) {
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");

        Server jettyServer = new Server(8080);
        jettyServer.setHandler(context);

        ServletHolder jerseyServlet = context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/*");
        jerseyServlet.setInitOrder(0);

        // Setting pacakge name over here to load services
        jerseyServlet.setInitParameter("jersey.config.server.provider.packages", "com.vinod.vinod_rest_examples");
        try {
            jettyServer.start();
            jettyServer.join();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            jettyServer.destroy();
        }
    }
}
  

4. Hit the urls for testing

http://localhost:8080/stateform/state


Done!!!

Spring AOP Annotation Based Example

Spring AOP Example

Aspect Oriented Programming
Aspect Oriented Programming entails breaking down program logic into distinct parts called so-called concerns. The functions that span multiple points  of an application are called cross-cutting concerns and these cross-cutting concerns are conceptually separate from the application's business logic
Important Terms
Aspect- A module which has a set of APIs providing cross-cutting requirements.
Join point- This represents a point in your application where you can plug-in AOP aspect
Advice- This is the actual action to be taken either before or after the method execution.
Point cut - This is a set of one or more join points where an advice should be executed

Example

1. Create a class to define aspect module

package com.vinod.test.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class MyObserver {

    /**
     *
     * This method will execute before executing any method in side
     * com.vinod.test.aop package
     *
     */


    @Before("execution(* com.vinod.test.aop.*.*(..))")
    public void beforeAdvice(JoinPoint jp) {
        System.out.println("Creating  object" + jp.getTarget().getClass().getName());
    }

    /**
     * This method will execute after executing any method
     *
     */

    @After("execution(* com.vinod.test.aop.*.*(..))")
    public void afterAdvice(JoinPoint jp) {
        System.out.println("Created  object" + jp.getTarget().getClass().getName());
    }

}

2. Create an employee entity

package com.vinod.test.aop;

import org.springframework.stereotype.Component;

@Component
public class Employee {

    public String getName() {
        return "Raju";
    }

    public String getAddress() {
        return "Banaglore";
    }
}
  

3. Create Spring configuration

package com.vinod.test.aop;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@ComponentScan("com.vinod.test.aop")
@EnableAspectJAutoProxy
public class MySpringAOPConifg {
   
}
  

4. Create a Test class 

package com.vinod.test.aop;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MyAOPMain {

    public static void main(String[] args) {

        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(MySpringAOPConifg.class);
        context.refresh();
        Employee emp = context.getBean(Employee.class);
        System.out.println(emp.getName());

    }

}
  

5. Output


Creating  objectcom.vinod.test.aop.Employee

Created  objectcom.vinod.test.aop.Employee

Raju

 

Done!!!

Download example

https://github.com/kkvinodkumaran/spring/tree/master/vinod-spring-core

Spring MVC Interceptor Example

Spring MVC Interceptor

HandlerInterceptor

Workflow interface that allows for customized handler execution chains. Applications can register any  number of existing or custom interceptors for certain groups of handlers, to add common preprocessing behavior without needing to modify each handler implementation.

See More about interceptor

Software Used

1. Eclipse Juno

2. Tomcat 7

3. Spring 3.0.3 

Example

Create one Web application and follow below steps

1. Create an interceptor class which implements HandlerInterceptor

package com.pretech; 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; 
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView; 
public class HelloIntercepter implements HandlerInterceptor  {
    @Override
    public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {
        System.out.println("Executing preHandle method");
        return true;
    } 
    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
            Object arg2, ModelAndView arg3) throws Exception {
        System.out.println("Executing postHandle method");
    }
    @Override
    public void afterCompletion(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        System.out.println("Executing afterCompletion method");
    } 
} 

2. Create a Controller class

package com.pretech; 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView; 
@Controller
public class HelloController {
    @RequestMapping("/hello")
    public ModelAndView helloWorld() {
        return new ModelAndView("hello", "message", "Hello World.. Spring 3");
    } 
} 

3. Create a JSP page 

<html>
<head>
<title>Pretech</title>
</head>
<body>
    <h1>Helloworld Example</h1>
<hr/>
    <form action="hello">
         <input type="submit" value="Click here to Say Helloworld">
    </form>
${message}
</body>
</html>


4. Create spring config file (spring-context.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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
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">
<!-- Application Message Bundle -->
    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="/WEB-INF/messages" />
        <property name="cacheSeconds" value="3000" />
    </bean>
    <context:component-scan base-package="com.pretech" />
    <mvc:annotation-driven />
<mvc:interceptors>
      <bean class="com.pretech.HelloIntercepter" />
    </mvc:interceptors> 
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
    </bean> 
</beans> 

5. Add Spring Dispatcher servlet details in to web.xml

<context-param>
       <param-name>contextConfigLocation</param-name>
       <param-value>/WEB-INF/spring-context.xml</param-value>
   </context-param>
   <servlet>
       <servlet-name>springDispatcher</servlet-name>
       <servlet-class>
           org.springframework.web.servlet.DispatcherServlet
       </servlet-class>
     <init-param>
           <param-name>contextConfigLocation</param-name>
           <param-value>/WEB-INF/spring-context.xml</param-value>
       </init-param>        
       <load-on-startup>1</load-on-startup>
   </servlet>
   <servlet-mapping>
       <servlet-name>springDispatcher</servlet-name>
       <url-pattern>/</url-pattern>
   </servlet-mapping>

5. Run the application on Tomcat Server


http://localhost:8080/Spring3HelloWorld/hello 




image 


Download this example Spring Interceptor Example

Spring 3 Form handling example

Softwares Used

1. Eclipse Juno

2. Tomcat 7

3. Spring 3.0.3

Example

Create one Web application and follow below steps

1. Create a class to define form attributes

package com.pretech.form; 
public class SimpleForm {
private String name;
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getAddress() {
    return address;
}
public void setAddress(String address) {
    this.address = address;
}
private String address;
} 

2.Create a Controller class

package com.pretech; 
import java.util.Map; 
import javax.validation.Valid; 
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; 
import com.pretech.form.SimpleForm; 
@Controller
@RequestMapping("simpleform.html")
public class SimpleFormController {
    @RequestMapping(method = RequestMethod.GET)
    public String showForm(Map<String, SimpleForm> model) {
        SimpleForm simpleForm = new SimpleForm();
        model.put("simpleForm", simpleForm);
        return "simpleform";
    } 
    @RequestMapping(method = RequestMethod.POST)
    public String processForm(@Valid SimpleForm simpleForm, BindingResult result,
            Map model) {
        if (result.hasErrors()) {
            return "simpleform";
        }
        simpleForm = (SimpleForm) model.get("simpleForm");
        model.put("simpleForm", simpleForm);
        return "simpleform";
    } 
} 

2.Create a JSP Page

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!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>Spring mvc simple form example</title>
</head>
<body>
<h3>Simple Form</h3>
<h3>Welcome ${simpleForm.name} </h3>
<form:form action="simpleform.html"  commandName="simpleForm">
    <table>
        <tr>
            <td>Enter your Name:</td>
        </tr>
        <tr>
            <td><form:input path="name" /> <FONT color="red"><form:errors    path="name" /></FONT></td>
        </tr>
        <tr>
            <td>Enter your address:<FONT color="red"><form:errors    path="address" /></FONT></td>
        </tr>
        <tr>
            <td><form:input path="address" /></td>
        </tr>
        <tr>
            <td><input type="submit" value="Submit" /></td>
        </tr>
    </table>
</form:form>
</body>
</html>

4. Create spring config file (dispatcher-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"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    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
    "> 
    <mvc:annotation-driven />
    <context:component-scan base-package="com.pretech" />
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
    </bean> 
    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="/WEB-INF/messages" />
    </bean>
    <!-- Configure the multipart resolver -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">      
    </bean> 
</beans> 

5. Add Spring Dispatcher servlet details in to web.xml

<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>/</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/dispatcher-servlet.xml</param-value>
    </context-param>

5. Run the application on Tomcat Server


http://localhost:8080/Spring3SimpleFormExample/simpleform.html 




image


Enter your name , addres and click on submit button


image




Download this example Spring Form Handling

Confusion Matrix + Precision/Recall (Super Simple, With Examples)

  Confusion Matrix + Precision/Recall (Super Simple, With Examples) 1) Binary Classification Setup Binary classification means the model p...

Featured Posts