Spring MVC Hello World Example

Tuesday, July 6, 2010

I have struggled a lot to set up first Spring MVC example. Usually the first application is the toughest one but once you are there you can progress rapidly. In this post I will show you how to set up and run the first Spring MVC example in Eclipse.

Earlier I tried it on MyEclipse but struggled a lot and then went to Eclipse Europa version on which I finally was able to run the application. This example was created with Spring 3.0 M3 and the application server used is Tomcat 5.0

This example is based on another readymade example Spring MVC Fast Tutorial: Hello World . I started with that example so you will find similarities. I also bumped into many issues which I finally was able to resolve.

Apart from fixing issues, I have extended the example with a small form which submits the user name and that name is printed with the Hello in another JSP.

Little Theory First
In spring the request should be passed through Dispatcher servlet which is part of Spring API. This servlet is provided by Spring directly and we just need to map the url to this servlet. When a request is receive by the Spring enabled application, it is received by the Dispatcher Servlet. Dispatcher Servlet looks for the appropriate controller and the view for the request in the configuration file. The request is then sent to Controller which processes the business logic and forwards the request to the appropriate view.


Workspace Setup

It is important to have all the required files (jars, tld, xml) otherwise you will face numerous issues. I learnt the hard way about the files required for this example hence I am showing the workspace snap which will help you to have all the required files.

In the lib folder copy the jar files shown here. In the WEB-INF directory the tlds are required for jstl, though in this example c.tld is the only one used. So other tld files are optional.

There is another file springmvc-servlet.xml. This file is the spring configuration file which spring uses to determine the controller and view for serving a request. The name of the file is significant here. springmvc should be same as the springmvc which is mentioned for declaring the servlet in the web.xml file.








Here are rest of the files and the Code.
1. HelloWorldController.java
This file is the controller for the hello-world.html resource. This is a virtual resource in the sense this file does not exists. The controller maps the spring configuration maps it to /jsp/hello_world.jsp


package headfirstspring.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class HelloWorldController implements Controller {

public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

ModelAndView modelAndView = new ModelAndView("hello_world");
return modelAndView;
}
}


2. DisplayDetailsController.java
This controller intercepts the request when user submits the form in first page (hello_world.jsp) and creates a message object and attaches it to the view.


package headfirstspring.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class DisplayDetailsController implements Controller {

public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

String name = request.getParameter("name");
String aMessage = "Hello "+name;

ModelAndView modelAndView = new ModelAndView("display_details");
modelAndView.addObject("message", aMessage);

return modelAndView;
}
}


3. hello-world.jsp
This is the initial jsp and shows the form where in user types in a name and submits it.


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>



Name :






4. display_details.jsp

This jsp shows the welcome message with name of the person submitted from the previous jsp.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


Hello Welcome to Spring






5. springmvc-servlet.xml
This is the spring configuration file. This file declares the various controllers. In the view declaration notice how the resource is prefixed with /jsp and suffixed with .jsp.

For example if the resource is hello_world it will become /jsp/hello_world.jsp














6. web.xml





springmvc
org.springframework.web.servlet.DispatcherServlet
1



springmvc
*.html



springmvc
*.do




jsp/index.jsp





http://java.sun.com/jsp/jstl/fmt
/WEB-INF/fmt.tld


http://java.sun.com/jsp/jstl/core
/WEB-INF/c.tld


http://java.sun.com/jsp/jstl/sql
/WEB-INF/sql.tld


http://java.sun.com/jsp/jstl/x
/WEB-INF/x.tld





Now You can Run the Application after deploying it on Tomcat Server.


Here is what should be the response.

Read more...

Inheritance Example in Spring Without Java Super Class

Friday, June 11, 2010

In the last example we saw how parent child relationship (inheritance) can be configured in Spring. In this example we will have a look wherein the parent class will not exist in byte code. This will be represented by the configuration option in Spring.

1. Our example scenario is same as previous scenario. We will see how we can create a bean in the container without explicitly having the java class. The process is simple. While declaring the bean mention it as abstract. Here is the relevant portion in the spring config file.












2. Make the following changes in the Child class.


package headfirstspring;

public class Child {

private String firstName;
private String lastName;

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 void showFullName(){
System.out.println(" full="" name="" is="">
}
}


3. Here is the program to test it. TestParentChild.java

package headfirstspring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestParentChild {
public static void main(String args[]){
// create and configure beans
ApplicationContext context =
new ClassPathXmlApplicationContext(" xml="">
// retrieve configured instance
Child child = (Child)context.getBean("child");
child.showFullName();
}
}

Read more...

Simple Inheritance Example in Spring

Inheritance is a very commonly used feature in Java to extended the functionality of an existing class. Let us see a very simple example how inheritance can be achieved in Spring.

Step 1. Create two Java classes with one class extending the other.

In this example we have Father and Child class. The Father class has two properties firstName and lastName. In the Child class we will only have one property firstName since we want to override the value.

Also, in the Father class we have a method which shows full name using the first and last name values. We will inherit the same method in the child class and use it to display the full name. Here is the code for both the Java classes.
Father.java


package headfirstspring;

public class Father {

private String firstName;
private String lastName;

public void showFullName(){
System.out.println("Full name is : "+getFirstName() + " " + getLastName());
}

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;
}
}


Child.java

package headfirstspring;

public class Child extends Father{

private String firstName;

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

}


Step 2 : Configure the beans in the config file.

In the configuration file, child bean definition should refer the parent bean with the attribute parent. In case this is not mentioned child bean will not know from where to get the value for last name and it will remain with a value null.

 










Step 3: Run the Test Program.
Here is the code.


package headfirstspring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestInheritance {
public static void main(String args[]){
// create and configure beans
ApplicationContext context =
new ClassPathXmlApplicationContext("config.xml");

Father father = (Father)context.getBean("father");
father.showFullName();
Child child = (Child)context.getBean("child");
child.showFullName();

}
}


Related Posts
Inheritance Example in Spring Without Java Super Class

Read more...

Autowiring By Bean Type or Bean Name

Thursday, June 10, 2010

In the previous example of autowiring, we saw how autowiring works based on constructor arguments.

Autowiring feature is used to supply property values to bean without explicitly mentioning which bean which will be injected. In this example we will see how autowiring happens by bean type.

Let us say Customer class is dependent on Identity and Address classes. In the previous post we saw how we can inject the dependencies through the constructor using the




In the Customer class we had a constructor like the following…

public Customer(Identity identity, Address address) {
this.address = address;
this.identity = identity;
}

Since we now want to inject the dependency using the bean type, here is how the bean definition will look like in the configuration file.





Here is the Configuration file.





















When we declare autowire="byType" as above, Spring will search for beans whose data type match with the data type of dependencies in Customer class. It finds that there are two beans with ids "identity" and "address" which are declared with matching data type and these are injected in the Customer bean.

Another change will be introducing a default constructor in the Customer class. Otherwise Spring will try to create the bean with the existing constructor and that needs two objects. Since we are now going to use the setter method for the dependency we also added the setter methods.

Here is the code for the Customer class.


package headfirstspring;

public class Customer {

private Address address;
private Identity identity;

public Customer() {
}

public Customer(Identity identity, Address address) {
this.address = address;
this.identity = identity;
}

public String showStateInfo(){
return (identity.getFirstName() + " stays in "+address.getState() + " state.");
}

public Address getAddress() {
return address;
}

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

public Identity getIdentity() {
return identity;
}

public void setIdentity(Identity identity) {
this.identity = identity;
}
}


Remaining code and classes remain the same as the previous example.

Autowiring By Bean Name
If you want to inject the dependency using bean name which is already declared in the configuration file, make the following change in the Customer bean definition.




This will work since the bean id of the Identity and Address beans in the configuration file matches with the property name defined in the Customer class and the bean type also match.

Related Posts
Configuration Based Autowiring Example in Spring
Annotation base Autowiring Example in Spring

Read more...

Configuration Based Autowiring Example in Spring

Tuesday, June 8, 2010

In the last post I showed how annotations can be used for autowiring. In this example I will show how you can used configuration file(xml) based autowiring. I am taking the exact scenario as in last example but moving the control of autowiring from Java to the coniguration file.

For this we need to change only two file and I am sharing the code for this two file.

1. Customer.java. We remove the annotation declaration. Remember that even if the annotation is present it will not make any difference. When ever autowiring is configured from both Java and XML, XML autowiring is applied later and therefore overwrites the Java based configurations.


package headfirstspring;

public class Customer {

private Address address;
private Identity identity;

public Customer(Identity identity, Address address) {
this.address = address;
this.identity = identity;
}

public String showStateInfo(){
return (identity.getFirstName() + " stays in "+address.getState() + " state.");
}
}


2. config.xml. See how we need to just add one attribute in the Customer bean declaration and that is all we need to do. It really is simple, isn't it?



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">
















Apply these two changes and you are ready to test the program as per the last post since everything else remains the same.

Related Posts
Annotation Based Autowiring Example in Spring

Read more...

Annotation base Autowiring Example in Spring

As you may be aware one of the highlight of Spring is autowiring. Autowiring means, beans are injected with proper dependency objects without explicit declaration. This is done by the Spring container based on information available to it.

For autowiring to take place, Spring container needs to be notified. It can happen either from configuration file which is present in form of xml, or Java base autowiring where in annotations is used.

In this example I am showing how annotation can be used in Java code to support autowiring.

Take a scenario where in there is a Customer class which has dependency on two other classes, which are Identity, which contains customer name etc. and Address class which maintains customer address information. In the Customer class we declare the autowiring to container using the @Autowire annotation on the constructor. This means that the container will supply appropriate beans for the constructor parameters from the context.

We declare two other classes Identity and Address which are simple Java POJO classes.

In the configuration file we mention the tag which will allow container to look for annotations.



Here are the source codes.

1. Code for Customer.java class. Notice the @Autowired annotation on the constructor.


package headfirstspring;

import org.springframework.beans.factory.annotation.Autowired;

public class Customer {

private Address address;
private Identity identity;

@Autowired
public Customer(Identity identity, Address address) {
this.address = address;
this.identity = identity;
}

public void showStateInfo(){
System.out.println(identity.getFirstName() + " stays in "+address.getState() + " state.");
}
}



2. Here is the code for Identity.java


package headfirstspring;

public class Identity {
private String firstName;
private String lastName;
private String ssn;
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 getSsn() {
return ssn;
}
public void setSsn(String ssn) {
this.ssn = ssn;
}
}



3. Here is the Address.java


package headfirstspring;

public class Address {
private String street;
private String state;
private String zip;
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
}


4. Here is the config.xml. If you look carefully we do not mention the dependencies of the Customer in this file here. We simply declare the customer bean

















5. Finally here is the test program TestAutoWiring.java


package headfirstspring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestAutoWiring {
public static void main(String args[]){
// create and configure beans
ApplicationContext context =
new ClassPathXmlApplicationContext("config.xml");
// retrieve configured instance
Customer customer = (Customer)context.getBean("customer");
customer.showStateInfo();
}
}

Read more...

Creating a Hello World program in Spring with Eclipse

Thursday, June 3, 2010

Hello World programs are usually the first steps in learning any new technology. Though the programs are simple are rarely do anything significant, they are important from two angles.
a) Your IDE becomes ready for more complex programs because of the setup/configuration you need to perform before you are able to run the Hello World program.
b) It gives you a real feel of though minuscule, how the technology works.

Thus it is important that you create a small program and execute it once you gain the preliminary knowledge of any Technology. Here is a simple program and steps for how to set it up. The IDE I have used for this example is Eclipse which is one of the most popular IDEs.

Step 1 : Create a Java Project.Click the following : File -> New -> Java Project

  • In the project name mention “SpringTest”. Click Next
  • Click the Libraries Tab. Click “Add External Jars” button.
  • Now the file browser go to the directory where Spring jars are present. Usually it is “dist” directory under the spring uninstall directory. Though you may not need to add all the jar for a hello world program, they will be useful when you create more complex examples using the more advanced features of Spring.
  • You also need asm.jar. You can download them from
  • http://download.forge.objectweb.org/asm/asm-3.2-bin.zip
  • Another library which is required is antlr. Here is the path : https://m2proxy.atlassian.com/repository/public/org/antlr/com.springsource.org.antlr/3.0.1/com.springsource.org.antlr-3.0.1.jar


Step 2 : Create the Files

a) Under the src create a file : "config.xml". Here is the content.







This xml file is the Spring configuration file which our application will use. We declare a bean with id “helloWorld” which refers to HelloWorld class.

b) Create a package. Right click on src folder and select New->Package. Name it “headfirstspring”
c) Create a Java file and name it as “HelloWorld.java” under the “headfirstspring” package. This is a simple java file with just one method sayHello(). Here is the code.

package headfirstspring;

public class HelloWorld {
public void sayHello(){
System.out.println("Hello World");
}
}


d) Create another Java file “TestHelloWorld.java” under the “headfirstspring” package. This file contains main method. In the method load we first load the configuration file which create the bean container. Next, we just access the bean from the container and call the sayHello method. Here is the code for that.

package headfirstspring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestHelloWorld {
public static void main(String args[]){
// create and configure beans
ApplicationContext context =
new ClassPathXmlApplicationContext("config.xml");
// retrieve configured instance
HelloWorld firstBean = (HelloWorld)context.getBean("helloWorld");
firstBean.sayHello();
}
}

Step 3 : Run the Example
This is the simplest step. Right click on “TestHelloWorld.java” -> Run As -> Java Application. You should see the following output.

Read more...

  © Blogger template On The Road by Ourblogtemplates.com 2009

Back to TOP