Saturday, August 8, 2009

Stereotype Annotations Cut Down XML Configuration in Spring

getname.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>

"http://www.w3.org/TR/html4/loose.dtd">



Greeting Request



Your name please:







---------------------------------------------------
HelloWorldController.java

package com.intertech.mvc;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class HelloWorldController {

@ModelAttribute("name")
public String populateName(
@RequestParam(value = "name", required = false) String name) {
return name;
}

@RequestMapping(value = "/greeting.request", method = RequestMethod.POST)
protected String sayHello() {
return "greet";
}

@RequestMapping(value = "/greeting.request", method = RequestMethod.GET)
protected String showForm() {
return "getname";
}
}

---------------------------------------------------
web.xml


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"
id="WebApp_ID" version="2.5">
HelloWorldAnnotated

dispatcher


org.springframework.web.servlet.DispatcherServlet

contextConfigLocation
/WEB-INF/mvc-beans.xml



dispatcher
*.request
*.xls


index.html


---------------------------------------------------
mvc-beans.xml


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-2.5.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-2.5.xsd">












class="org.springframework.web.servlet.view.InternalResourceViewResolver">




---------------------------------------------------
greet.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>

"http://www.w3.org/TR/html4/loose.dtd">



Greeting


Hello ${name}




---------------------------------------------------
Note :

Add the commons-logging.jar, spring.jar and spring-webmvc.jar (Spring 2.5 or better) to the

/WEB-INF/lib folder.

To run HelloWorld, deploy the application to a Web Container, then request getname.jsp with the

following URL:
http://localhost:8080/HelloWorldAnnotated/getname.jsp

Because the controller has RequestMapping for both POST and GET HTTP methods, you can also

run HelloWorld by requesting the following URL:
http://localhost:8080/HelloWorldAnnotated/greeting.request

No comments: