Search This Blog

Sunday, June 5, 2011

Use Spring 3.0 into your Servlet based application (No MVC framewrok plugin only Servlet/Jsp application)

Use Spring 3.0 into your Servlet based application (No MVC framewrok plugin only Servlet/Jsp application)

Note : Spring3.0 is also having support to use annotation based configuration unlike configuration file based support in earlier version of Spring

Step 1: Create a Service Class Calculator
public class Calculator {
private String sum;
public Double add(String one , String two){
sum = parseDouble(one) + parseDouble(two);
}
public String getSum(){
return sum;
}

}

Step 2: Create a Class MySpringConfig to use annotation based configuration

package com.spring.web.config;
import org.springframework.context.annotation.*;

@Configuration
public class MySpringConfig {
@Bean()
@Scope(value="request")
public Calculator calculator() { return new Calculator(); }

}

Step 3: Use following contextListeners and Custom Configurations class into your web.xml (deployment descriptor)
as below
:

<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>

<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.spring.web.config.MySpringConfig</param-value>
</context-param>

Step 4: Use following code to load calculator instance form the Spring configuration into your JSP scriplet or in your servlet

ApplicationContext beanFactory =
WebApplicationContextUtils
.getRequiredWebApplicationContext(getServletContext());

Calculator calc =
(Calculator)beanFactory
.getBean("calculator", Calculator.class);

String clickedButton = request.getParameter("command");
String num1= request.getParameter("num1");
String num2= request.getParameter("num2");
if (clickedButton != null && clickedButton.equals("add")) { calc.add(calc.add()); }

Step 5 : HTML code

<html>
<body>

<form action="index.jsp">
<input type="text" name="num1">
<input type="text" name="num2">
<input type="submit" name="command" value="ClickToCount!">
</form>

Sum : <%=calc.getSum()%>

</body>
</html>

Now Your app is ready with Spring 3.0 and simple JSP Servlet web application

Cheers

Kapil

1 comment:

  1. Above steps are very effective to learn spring 3.0 into your servlet based app. After 2 hours searching i get these important steps from this page. event app iphone

    ReplyDelete

Thanks for your comment, will revert as soon as we read it.

Popular Posts