Showing posts with label j2EE. Show all posts
Showing posts with label j2EE. Show all posts

Monday, May 13, 2013

How to write JAX-WS WebServices and WebService Client in Java

Today, I am going to explain about how to write JAX-WS Webservice providers(Endpoints) and how to create webservice client which uses published webservices.

JAX-WS is Java Api for XML webservices. APIs for creating webservices in XML formats.

Let's consider that I want to write JAX-WS Service which will publish customer Information and client will use this service and display requested customer Information.

You require to develop following parts :
  1. Create WebService Endpoint Interfaces
  2. Create WebService Endpoint Implementation
  3. Endpoint Publisher
  4. Analyze Created wsdl file
  5. Create WebService Client which will use exposed services.

Sunday, April 21, 2013

Generate BeanName using Spring AnnotationBeanNameGenerator

Developing application with Spring, sometimes require to retrieve bean name which you have either specified in @Bean annotation or bean id which is internally generated by Spring.

Spring by Default generate Bean id same as Bean class name but with first letter in small caps.
Using Spring AnnotationBeanNameGenerator class, one can achieve this using generateBeanName method.

Ex. private AnnotationBeanNameGenerator beanNameGenerator = new AnnotationBeanNameGenerator();
String beanName = this.beanNameGenerator.generateBeanName(definition, registry); 

(1) definition is Spring BeanDefinition. BeanDefinition describes bean instance which has property values, constructor argument values any many more.

In order to retrieve BeanDefinition for bean, method resolveScopeMetadata(BeanDefinition definition) of Spring interface like ScopeMetadatResolver or AnnotationScopeMetadataResolver can be used.

Spring provide interface called AnnotatedBeanDefinition which provide awesome bean information like getMetadata() for those beans which has annotation defined.

(2) registry is of Spring BeanDefinitionRegistry.(Ex. BeanDefinitionRegistry registry)  it's basically interface for registries which holds bean Definition. It's only interface which encapsulate registries of bean Definition

After struggling hours , I finally able to make things working. Hope you find this information useful

Author : Anuj Patel
Blog :

Saturday, March 30, 2013

Prefix mvc for element mvc:annotation-driven is not bound

If you are planning to use <mvc:annotation-driven>  into your Spring MVC application, chances that you may be facing issue for "Prefix mvc for element mvc:annotation-driven is notbound " erorr. Root cause is that your bean definition XML doesn't have names-spaces mentioned below.

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

java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet

While developing SpringMVC application in Eclipse, All require dependencies has been added to maven dependencies in pom.xml. Yet running application encountered with Exception java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet

Solution : 
Even though you have added all required dependencies into pom.xml for your J2EE WebProject you are require to reference maven dependencies to "Web Deployment Assembly"

Right Click J2EE Web Project->Deployment Assembly->Add->Select Maven Dependencies.

java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config

I was working on developing Spring MVC Application with Maven+Tomcat with Spring 3.2. While running application, encountered with Exception : java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config

Solution :
I found that tomcat container doesn't contain jatl library and hence require to explicitly add it to maven dependencies in Pom.xml

Maven Dependencies

After adding maven dependencies as mentioned above, issue is resolved. Hope it might help you.

Monday, February 18, 2013

Apache Solr and SolrJ Maven Dependancies

While I was developing Solr application using Solrj, there was confusion (which is always :) ) of which maven dependencies to be included in Pom.xml. Hence thought to share here.
Please don't miss to add M2_REPO classpath variable pointing to repository directory so you can easily import required library into your Java Project.

Maven Dependencies for Developing application with Solr (version 4.1) are followed as :

1. Solrj Dependencies

2. Solr-core Dependencies

Wednesday, October 03, 2012

Sending Email using Spring MailSender and Gmail SMTP Server

Spring provides interface called "MailSender" (org.springframework.mail.MailSender) to send mail.
Developer can use MailSender method send(SimpleMailMessage simpleMessage)and pass SimpleMailMessage with From,To,Subject, and Text set.

MailSender Documentation : MailSender
SimpleMailMessage Documentation : SimpleMailMessage

Java Program to send Mail using Spring MailSender :
package com.anuj.spring.mail;

import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;

 * @author Anuj Patel
public class NotifyImpl {
    private MailSender mailsender;
    public MailSender getMailsender() {
        return mailsender;
    public void setMailsender(MailSender mailsender) {
        this.mailsender = mailsender;
    public void sendMail(String from, String to, String subject, String message) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();

Wednesday, September 26, 2012

Spring - java.lang.ClassNotFoundException: org.aopalliance.aop.Advice

Even after adding all Spring 3.1 jar i was getting excpetion as below :

Exception in thread "main" org.springframework.beans.factory.CannotLoadBeanClassException:
Caused by: java.lang.ClassNotFoundException: org.aopalliance.aop.Advice
    at$ Source)
    at Method)
    at Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 49 more
Solution :

As part of, Removed AOP Alliance interfaces from spring-aop.jar and
the aopalliance.jar needs to be added explicitly. Instead of using jar from any other sources, it's better to use jar from official maven repository.

Saturday, July 28, 2012

How to load multiple Spring bean configuration file

When you are working on large project where stracturized  folder structure is being used for Spring Beans configuration files ex. Spring-Core.xml in Core Folder, Spring-Common.xml in Common folder etc

You may load multiple Spring bean configuration files in code :
ApplicationContext context = 
     new ClassPathXmlApplicationContext(new String[] {"Spring-Core.xml",

This way is not properly organized.It will be better if we can import multiple xml into one xml and then define single main XML into ClassPathXmlApplicationContext
<beans xmlns="" xmlns:xsi="" xsi:schemaLocation="">    
       <import resource="common/Spring-Core.xml"/>  
      <import resource="connection/Spring-Common.xml"/> 

Sunday, June 10, 2012

Deep Dive into Spring Setter Injection

Spring setter injection provide you to set value of different types of Data which you use while developing application. If you are not aware of Constructor or Setter Injection concept, please refer Spring Setter Injection and Constructor Injection before going through tutorial.

I will show you how to use it Spring setter Injection for different types of data.somehow due to formatting String is displayed as string.please use String in your example.

1. Create
package com.anuj.spring.core.injection;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

 * @author Anuj J Patel
public class PropertyTest {
    private int intData;
    private double doubleData;
    private float floatData;
    private String stringData;
    private int[] intArr;
    private String[] stringArr;
    private List listdata;
    private Map map;
    private Properties properties;
    private Set setData;

    public PropertyTest() {
        System.out.println("Constructor Called");
    public String toString() {
        return "PropertyTest{" + "intData=" + intData + ", doubleData=" + doubleData + ", floatData=" + floatData + ", stringData=" + stringData + ", intArr=" + intArr + ", stringArr=" + stringArr + ", listdata=" + listdata + ", map=" + map + ", properties=" + properties + ", setData=" + setData + '}';
    public double getDoubleData() {
        return doubleData;

    public void setDoubleData(double doubleData) {
        this.doubleData = doubleData;

    public float getFloatData() {
        return floatData;

    public void setFloatData(float floatData) {
        this.floatData = floatData;

    public int[] getIntArr() {
        return intArr;

    public void setIntArr(int[] intArr) {
        this.intArr = intArr;

    public int getIntData() {
        return intData;

    public void setIntData(int intData) {
        this.intData = intData;

    public List getListdata() {
        return listdata;

    public void setListdata(List listdata) {
        this.listdata = listdata;

    public Map getMap() {
        return map;

    public void setMap(Map map) { = map;

    public Properties getProperties() {
        return properties;

    public void setProperties(Properties properties) { = properties;

    public Set getSetData() {
        return setData;

    public void setSetData(Set setData) {
        this.setData = setData;

    public String[] getStringArr() {
        return stringArr;

    public void setStringArr(String[] stringArr) {
        this.stringArr = stringArr;

    public String getStringData() {
        return stringData;

    public void setStringData(String stringData) {
        this.stringData = stringData;

Saturday, May 26, 2012

Spring JdbcTemplate and Spring SimpleJdbcTemplate difference with Example

To use the SimpleJdbcTemplate you need to use JDK 1.5 or higher. SimpleJdbcTemplate takes advantage of the Java 5 language features like varargs, autoboxing, generics and covariant returns.

Following example shows you how to use SimpleJdbcTemplate and advantage of it over JdbcTemplate
package com.anuj.spring.db;

import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;

 * @author Anuj J Patel
public class ForumDAOSimpleJDBCImpl implements ForumDAO{

     * Simple JDBCTemplate
     * 1.When using SimpleJDBCTemplate there is no need to typecast from int to Integer
     * and you can pass variable length arguments instead of Object array
     * 2.There is no need to typecast return object, parameterizedRowMapper object's type parameter 
     * will be taken by default
    private SimpleJdbcTemplate simpleJDBCTemplate;
    public void setDataSource(DataSource dataSource){
        this.simpleJDBCTemplate = new SimpleJdbcTemplate(dataSource);
    public void insert(Forum forum) {
        String query = "insert into tbforum(forumId,forumName,forumDesc) values(?,?,?)";
        simpleJDBCTemplate.update(query, forum.getForumId(),forum.getForumName(),forum.getForumDesc());
        System.out.println("Record Inserted successfully");

    public Forum selectForum(int forumId) {
        String query="select * from tbforum where forumId=?";
        return simpleJDBCTemplate.queryForObject(query, 
                new ParameterizedRowMapper(){
                        public Forum mapRow(ResultSet rs, int rowNum) throws SQLException {
                            return new Forum(rs.getInt("forumId"),rs.getString("forumName"), rs.getString("forumDesc"));

Friday, April 27, 2012

JAX-RS Handling XML using JAXB Annotation

In this tutorial, I will show you how to create an “user” object, convert it into XML file,
and return it back to the client.

Create an object, annotate with JAXB annotation to support XML file conversion.

POJO Class with JAXB annotation :
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "user")
public class User {

String username;
String password;
int pin;

public String getUsername() {
return username;

public void setUsername(String username) {
this.username = username;

public String getPassword() {
return password;

public void setPassword(String password) {
this.password = password;

public int getPin() {
return pin;

public void setPin(int pin) { = pin;


File Download in JAX-RS

In JAX-RS, for user to download a file, annotate the method with @Produces("text/plain") :

Put @Produces(“text/plain”) on service method, with a Response return type. It means the output is a text file.
Set “Content-Disposition” in Response header to tell browser pop up a download box for user to download.

Download File in JAX-RS :

See a full example to download a text file in JAX-RS.


public class FileService {

private static final String FILE_PATH = "c:\\file.log";

public Response getFile() {
File file = new File(FILE_PATH);

ResponseBuilder response = Response.ok((Object) file);
response.header("Content-Disposition","attachment; filename=\"file_from_server.log\"");

@HeaderParam Implementation in JAX-RS

There are 2 ways to get HTTP request header in JAX-RS :
Inject directly with @HeaderParam
Pragmatically via @Context

Implementation using @HeaderParam :

In this example, it gets the browser “user-agent” from request header.


public class UserService {

public Response addUser(@HeaderParam("user-agent") String userAgent) {
  return Response.status(200)
.entity("addUser is called, userAgent : " + userAgent)

Access via URI pattern “/users/get“, with FireFox, see following result :
addUser is called, userAgent : Mozilla/5.0 (Windows NT 6.1; rv:5.0) Gecko/20100101 Firefox/5.0

@MatrixParam Implementation in JAX-RS

In this tutorial , i will show usage of @MatrixParam. Matrix parameters are a set of “name=value” in URI path, for example, /books/2012;author=anuj
In above URI, the matrix parameter is “author=anuj“, separate by a semi colon “;“.

@MatrixParam example

public class BookService {

 public Response getBooks(@PathParam("year") String year,
   @MatrixParam("author") String author,
   @MatrixParam("country") String country) {

  return Response
   .entity("getBooks is called, year : " + year
    + ", author : " + author + ", country : " + country)


Saturday, January 14, 2012

Spring Setter Injection and Constructor Injection

In this post i am going to demonstrate you how to set bean property using spring setter injection and constructor. First i will demonstrate Happy scenario and later will be complex. This will force you to think deeply about bean.xml

Consider i have class User containing 3 property name,age and country. Using spring i want to display value of user with all it's property.
package com.anuj.spring.injection;
 * @author Anuj J Patel
public class User {

    private String name;
    private int age;
    private String country;

    public String getName() {
        return name;

    public void setName(String name) { = name;

    public int getAge() {
        return age;

    public void setAge(int age) {
        this.age = age;

    public String getCountry() {
        return country;

    public void setCountry(String country) { = country;

    public String toString()
        String output = "Name : " + name + " Age: " + age + " Country:" + country;
        return output;

Sunday, December 18, 2011

Spring IOC and Dependancy Injection

In Spring, Inversion of Control(IOC) is implemented using Dependancy Injection(DI) Design Pattern. Let's understand DI with java example and then I will see how DI can solve tightly coupled problem and Spring container will inject dependency.

What is Inversion of Control?
IOC allows you to decouple your program into separate components that don't know each other. supposed if I have two classes which implements common interface then In order to use, In my Java class i need to create instance of those classes. which looks like tightly coupled.

If we can define which class to use at runtime using Injecting dependency at runtime then it will be good , right? This is where IOC comes to Picture.

Concept IoC that the Spring Framework uses is "Injection of required resources or dependency at Run-time into the dependent resource," which is also known as Dependency Injection.

There are three forms or styles of Dependency Injection.
1.Constructor Injection
2.Setter Injection
3.Interface Injection

1. Constructor Injection: Here, IoC container uses the constructor to inject the dependency. Since All dependencies are declared in one constructor, it's added advantage.
- here, handling over dependencies takes during instantiation of the dependent object.

2. Setter Injection: Here, DI uses Setters to inject the required resources or dependencies.Meaning class will have setters, the IoC container will use the setters to provide the resource at run-time.
-  here, handling over dependencies takes after the dependent object is instantiated

Monday, December 12, 2011

What is Spring and why came into Picture ?

In order to start with Spring, it's very important to clear concepts about what is Spring and why it came into picture. Once you have idea about Spring picture, you will be sure able to easily understand 7 Spring modules described here as well. So Let's Jump into Spring :)

Java Enterprise Edition (JEE) component that was used to implement business logic was Enterprise Java Beans (EJB). However, EJBs are heavy weight components that require application servers to run. 

This was the scenario before the Spring Framework came into the picture. The Spring Framework provides a lightweight container to run the objects implementing business logic. In other words, Spring Framework-based business objects do not require an application server to run.

Spring Framework: What is it? Spring Framework is “An open-source layered Java/J2EE application framework having a light-weight container implementing Inversion-of-Control and Aspect Oriented Programming.” The key points here are “layered application framework” and “Inversion of Control and Aspect Oriented Programming.” and they are divided into two broad categories:
  1. Patterns
  2. Components of the Framework

Spring has two patterns at its core. They are:
    • Inversion-of-Control(IOC)
    • Aspect Oriented Programming(AOP)

Inversion-of-Control - refer to Spring DI and IOC concept and Example

Aspect Oriented Programming(AOP) is “An approach to programming that attempts the separation of concerns, specifically cross-cutting concerns, as an advance in modularization.” Here, the key point is separation of concerns. 

Separation of concerns means that the applications are divided into modules that do not overlap in terms of functionality.Logging is an example of such a using AOP a developer can encapsulate cross cutting concerns.

Thursday, September 29, 2011

Using Spring JdbcTemplate to store and retrive values into DB

In This example i will demonstrate you Spring example to insert and select values from oracle DB. The insertForum() method below shows the amount of code you need to write to insert data using JDBC.

1. Create Java POJO Class ex. Forum which contains getter and setter method for field as mentioned below.
    private int forumId;
    private String forumName;
    private String forumDesc;

1.1 create parameterized constructor as below.
  public Forum(int forumId, String forumName, String forumDesc) {
        this.forumId = forumId;
        this.forumName = forumName;
        this.forumDesc = forumDesc;

2. Create Interface ex. ForumDAO which contains insert and select methods
package com.learning.dao;
import com.learning.core.Forum;
public interface ForumDAO {

    public void insertForum(Forum forum);
    public Forum selectForum(int forumId);

Monday, August 29, 2011

Hibernate - Store and Retrieve Data along with BLOB as XML

Hibernate is an object-relational mapping (ORM) library for the Java language, providing a framework for mapping an object-oriented domain model to a traditional relational database.

Here, i have demostrated basic example to store data along with blob into Database and retrieve from Database.File logic is used to display Blob Data only. While writing your own Logic, you should avoid it.

Before Using this tutorial, You need know how hibernate Configuration "hibernate.cfg.xml" should look like. Read related blog post - Hibernate config file - Pojo file containing getter and setter methods.

package com.core;

import java.sql.Blob;

 * @author Anuj Patel
 * Java Core POJO class to map to database Contact Table
public class Contact implements Serializable{
    private String firstName;
    private String lastName;
    private String email;
    private int id;  
    private Blob contactData;
    public Blob getContactData() {
        return contactData;
    public void setContactData(Blob contactData) {
        this.contactData = contactData;
    public String getFirstName() {
        return firstName;
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    public String getLastName() {
        return lastName;
    }    public void setLastName(String lastName) {
        this.lastName = lastName;
    }    public String getEmail() {
        return email;
    }    public void setEmail(String email) { = email;
    public int getId() {
        return id;
    public void setId(int id) { = id;