Thursday, July 7, 2011

SPRING - Simple Annotation Example

Spring Annotations are available from 2.5 onward and provides the facility to make the configurations directly in the Java code through annotations. Controllers implementing annotations need not extend any base class or implement any interfaces.

This example is to explain a simple way to use annotations in configuring the Spring Framework instead of making the configurations on the XML file.

1. Follow the steps in Creating a Mavenized Spring Application in Eclipse to start with a fresh Maven based Spring web application.

2. Update the Spring configuration to indicate the dispatcher servlet to look for annotation based controllers in your project. This can be achieved using the spring-context schema.

<?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"
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">
<!--
Tells the Dispatcher Servlet to scan for annotation based
configuration in this package
-->
<context:component-scan base-package="org.mybusiness.annotationportal.controllers" />
</beans>

3. The @Controller annotation is used to indicate that a particular class serves the purpose of a Controller. As you can see these classes need not extend any base class or implement any specific interface.

package org.mybusiness.annotationportal.controllers;
import org.springframework.stereotype.Controller;
/**
 * This class does not extend any base class or implement any interface
 */
@Controller
public class HelloController {
}

4. Use the @RequestMapping annotation to map the URLs to a specific method or an entire class itself. The @RequestMapping annotations defined at the entire class are called as type-level annotations whereas annotations on the method level are called as method-level annotations.

package org.mybusiness.annotationportal.controllers;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;


/**
 * This class does not extend any base class or implement any interface
 */
@Controller
public class HelloController {
 @RequestMapping("/hello.do")
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
return new ModelAndView("Hello");
}
}

5. Define the view to display be displayed. In our case it is Hello.jsp.

<html>
<head>
<title>Hello</title>
</head>
<body>
Welcome to Annotation World!
</body>
</html>

Final Output

No comments:

Post a Comment