Tag Archives: Spring

Creating a Spring MVC REST WebService

To get started let’s create a simple dynamic web project in Eclipse.

1. Modify web.xml to let it know about Spring

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

<servlet-mapping>
<servlet-name>springapp</servlet-name>
<url-pattern>/service/*</url-pattern>
</servlet-mapping>

Additional Step: Add Spring Jars or Maven dependencies for Spring- core, aop, context, web and webmvc jars.

2. create springapp-servlet.xml

<?xml version=”1.0″ encoding=”UTF-8″?>

<beans xmlns=”http://www.springframework.org/schema/beans”
xmlns:mvc=”http://www.springframework.org/schema/mvc” 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-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd”
>
<!– the application context definition for the springapp DispatcherServlet –>

<mvc:annotation-driven />
<context:annotation-config />

<context:component-scan base-package=”com.kamal.test” />

<!–   <bean name=”/hello.app” class=”com.kamal.test.Hello”/> –>

</beans>

Note that we are using annotation driven implementation. where our package com.kamal.test would be scanned for any available components.

3. Create the service

package com.kamal.test;

import java.io.IOException;
import javax.servlet.ServletException;
import org.springframework.stereotype.Controller;
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(“/sample”)
public class SampleService {
@RequestMapping(method = RequestMethod.GET, value=”/details/{id}”)

public @ResponseBody String LepService(@PathVariable(“id”) String id )
throws ServletException, IOException {
String success=”Sucess”;
//Do something here
return success;
}
}

 

Spring Framework- Basics

The question which I asked 4 years back when I was to use Spring framework for project was- Why Spring? I was using Struts for few years and was in love that, so why to try something new.

Over the time I have found a very convincing answer which I will share.

    1.Empowering POJO’s
    2.Dependency Injection
    3.It is more than web application development framework
    4.Support for Aspect oriented programming

1. For me most important feature which Spring provides is use of POJOs (Plain Old Java Objects). Working with frameworks like Struts, you need to follow a very strict format, for example for each controller servlet you need to extend action class and override execute method with fixed number of parameters. Even if you are creating simple servlet you need to have get and post methods to handle client requests in a particular format. Spring finally gives you freedom to use plain java classes and convert to controllers or request handlers using simple annotations.

2. Dependency injection is implementation of inversion of control principle which helps maintain loose coupling and move away dependencies from the current class and let it focus on its real goal. Read more on dependency injection-http://kamalmeet.com/2012/03/dependency-injection-simplified/, http://kamalmeet.com/2013/03/more-on-dependency-injection/, http://kamalmeet.com/2013/03/spring-implementation-of-dependency-injection/

3. As I said, Spring is not just for handling request response or implementing MVC like struts, it goes much beyond that. It is kind of a bouquet providing end to end solution for an application like it provides Spring Security for controlling access to application, provides Spring MVC for handling request/ response in MVC mode, provide Workflow to handle control flow, support for webservices through Spring Restful templates etc.

4. Finally support for aspect oriented programming (AOP). Spring supports AOP, that means you can separate some aspects of code so that your classes can focus on the responsibility given to them. For example creating logs is one aspect of a code, which we need to write in every class to make sure proper logs are maintained. Spring helps you pull this aspect out of the code and handle through some configuration making sure logging occurs whenever required.

Spring Implementation of Dependency Injection

In last post I explained what is dependency injection (DI). Now I will focus on how the concept is implemented in Spring framework. If we are clear on the concept of DI, remaining is piece of cake.

There are 2 ways to implement DI in Spring

1. Using annotations

Spring is basically annotation driven language (see here). @Autowired is the annotation which will help us inject dependencies in Spring. @Autowired will tell the code to look for given object somewhere in code. The dependency injection can be implemented in 3 ways

a. Using my previous Employee- Address example for dependency injection, adding address dependency through constructor

Class Employee

{

public Address address;

public String name;//other stuff

@Autowired
Employee(Address address)
{
this.address=address
}

}

And In application context xml add

<bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

	<bean id="EmployeeBean" class="com.test.Employee">
		<property name="name" value="kamal" />

	</bean>

	<bean id="AddressBean" class="com.test.Address">
           <property name="street" value="43rd" />
		<property name="apt" value="29" />
		<property name="city" value="New york" />
	</bean>

b. using Setter- similar to constructor

Class Employee

{

public Address address;

public String name;//other stuff

Employee()
{
}

@Autowired
public void setAddress(Address address)
{
this.address=address;
}

}

c. Using Field

Class Employee

{
@Autowired
public Address address;

public String name;//other stuff

Employee()
{
}

}

2. Using XML configuration (application context)

Same as above (almost), we will not use @Autowired but add the dependency in the xml itself

<bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

	<bean id="EmployeeBean" class="com.test.Employee">
		<property name="name" value="kamal" />
<property name="address" ref="AddressBean" />

	</bean>

	<bean id="AddressBean" class="com.test.Address">
           <property name="street" value="43rd" />
		<property name="apt" value="29" />
		<property name="city" value="New york" />
	</bean>

Finally to run your example add these lines to code

ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {“SpringBeans.xml”});

Customer cust = (Customer)context.getBean(“EmployeeBean”);

Further References

http://www.vogella.com/articles/SpringDependencyInjection/article.html

http://www.mkyong.com/spring/spring-auto-wiring-beans-with-autowired-annotation/

Spring MVC- Getting Started

For understanding anything it is best to gets hand on. Let us try creating a simple spring app using spring MVC framework (This tutorial assumes Eclipse IDE)

0. Create a sample J2EE project (or Spring project if you already have it installed)

1. Download Spring http://www.springsource.org/spring-community-download and include jars to lib folder.

2. Modify web.xml to direct all the requests ending with .do to spring MVC’s fromt controller servlet (DispatcherServlet)


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

  <servlet-mapping>
    <servlet-name>springapp</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

3. Spring by default assumes webapplication context to be present in <servletname>-servlet.xml. In this case create springapp-servlet.xml.

4. Spring is mostly annotation driven, to take advantage of same add following to springapp-servlet.xml

<?xml version=”1.0″ encoding=”UTF-8″?>
<beans xmlns=”http://www.springframework.org/schema/beans”
xmlns:mvc=”http://www.springframework.org/schema/mvc” 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-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd”
>

<!– JSR-303 support will be detected on classpath and enabled automatically –>
<mvc:annotation-driven />
<!– Activates various annotations to be detected in bean classes –>
<context:annotation-config />

<!– Tell Spring where to automatically detect controllers –>
<context:component-scan base-package=”spring.sample.controllers” />
<!– Define Simple View Resolvers –>
<bean id=”viewResolver” class=”org.springframework.web.servlet.view.InternalResourceViewResolver”>
<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>

</beans>

We have done two things, first, we told spring that all our controllers will be in spring.sample.controllers and second look for view files under /WEB-INF/jsp folder

5. As we are going for annotations driven approach, we can use any POJO file as controller. It just needs to be in spring.sample.controller.

package spring.sample.controllers;

@Controller
/*this url automatically gets redirected here*/
@RequestMapping(value = “/mylink”)
public class SampleController {

@RequestMapping(method = RequestMethod.GET)
public ModelAndView login() {
String message = “Welcome to the Spring 3.0 version!”;
return new ModelAndView(“welcome”, “message”, message);
}

6. And finally a simple welcome.jsp

<%@ page language=”java” contentType=”text/html; charset=UTF-8″
pageEncoding=”UTF-8″
%>
<!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=UTF-8″>
<title>Welcome to Spring</title>
</head>
<body>${message}
</body>
</html>