Tags

,

In this post I will show how to create a very simple REST web based application.

My development tool is Eclipse Juno with Spring IDE plugin installed. Also I assumed you have already got some basic idea about

1. Spring

2.Spring MVC

3.Maven

4.Tomcat

OK Let’s go! You can download the source code in

https://github.com/mrtong/MyRESTSample.git

1. Open Eclipse, from SpringSource Dashboard create a Spring MVC Project named as MyRESTSample.

Image

2. If everything goes well it should already generated a basic Spring MVC project for you.

Let’s tweak something.

1) Create a package called com.foo.myrest.controller(I assumed your root package is com.foo.myrest), remove the generated HomeController.java into this folder.

2) Create a package called com.foo.myrest.bean

3) Open the servlet-context.xml file find this line

<context:component-scan base-package=”com.foo.myrest” />

change it to

<context:component-scan base-package=”com.foo.myrest.controller” />

(The reason for this change is, in 1) we’ve moved the HomeController.java to com.foo.myrest.controller )

3. Up to now there is no REST code inserted. Do not worry, make sure the basic Spring MVC project is working at this stage.

right click pom.xml, select Maven build… in the pop up window, use clean install as follows:

Image

4. if everything goes well(make sure you can see “Build Success” in the console), we now have a war file call myrest-1.0.0-BUILD-SNAPSHOT.war, which contains every jar file required for this application. Rename it to myrest.war and put the war file into <Tomcat install folder>\webapps then run tomcat.

If you have any complains here, check your pom.xml file.

5. Open your favorite browser and type http://localhost:8080/myrest The following page is expected;

Image

If you can see the above page, congratulations, you can go ahead.

6. Create a bean called Employee under com.foo.myrest.bean as follows:

package com.foo.myrest.bean;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name=”employee”)
public class Employee {

private long id;
private String name;
private String email;

public Employee() {}

public Employee(long id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}

public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}

}

7.  Create a bean called EmployeeList under com.foo.myrest.bean as follows:

package com.foo.myrest.bean;

@XmlRootElement(name=”employees”)

public class EmployeeList {

private int count;
private List<Employee> employees;

public EmployeeList() {}

public EmployeeList(List<Employee> employees) {
this.employees = employees;
this.count = employees.size();
}

public int getCount() {
return count;
}

public void setCount(int count) {
this.count = count;
}

@XmlElement(name=”employeeABC”)
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}

}

8. As a simple demo, I do not want to access any database. So I just create some mock data here by creating a file called  EmployeeDS under the com.foo.myrest.ds folder.

package com.foo.myrest.ds;

public class EmployeeDS {

private static Map<Long, Employee> allEmployees;
static {
System.out.println(“EmployeeDS statis”);
allEmployees = new HashMap<Long, Employee>();
Employee e1 = new Employee(1L, “Joe Smith”, “jsmith@mycompany.com”);
Employee e2 = new Employee(2L, “Joe Senior Smith”, “joessmith@mycompay.com”);
allEmployees.put(e1.getId(), e1);
allEmployees.put(e2.getId(), e2);
}

public void add(Employee e) {
allEmployees.put(e.getId(), e);
}

public Employee get(long id) {
return allEmployees.get(id);
}

public List<Employee> getAll() {
List<Employee> employees = new ArrayList<Employee>();
for( Iterator<Employee> it = allEmployees.values().iterator(); it.hasNext(); ) {
Employee e = it.next();
employees.add(e);
}
return employees;
}

public void remove(long id) {

allEmployees.remove(id);
}

public void update(Employee e) {
allEmployees.put(e.getId(), e);
}

}

9. Create a controller class called EmployeeController under the com.foo.myrest.controller folder.

Here we will use the @Controller annotation to declare a controller and use @Autowired annotation to link/ref other beans. To enables the Spring MVC @Controller programming model, we need to define
<annotation-driven /> in the xml file.  I will discuss this later.

package com.foo.myrest.controller;

@Controller

public class EmployeeController {
@Autowired
private EmployeeDS employeeDS;

public void setEmployeeDS(EmployeeDS ds) {
this.employeeDS = ds;
}

@Autowired
private Jaxb2Marshaller jaxb2Mashaller;

public void setJaxb2Mashaller(Jaxb2Marshaller jaxb2Mashaller) {
this.jaxb2Mashaller = jaxb2Mashaller;
}

@RequestMapping(method = RequestMethod.GET, value = “/employee/{id}”)

public String getEmployee(@PathVariable String id, Model model) {
Employee e = employeeDS.get(Long.parseLong(id));
System.out.println(“employeeDS=” + employeeDS);
System.out.println(“employee==” + e.getName());
model.addAttribute(“employee”, e);
return “employee”;
}

@RequestMapping(method = RequestMethod.GET, value = “/employees”)
public String getEmployees(Model model) {
List<Employee> employees = employeeDS.getAll();
EmployeeList list = new EmployeeList(employees);
model.addAttribute(“employees”, list);
System.out.println(“get employees”);
return “employees”;
}

}

10. Create a file called employee.jsp and a file called employees.jsp under webapp\WEB-INF\views. The content of employee.jsp is

<%@ page language=”java” contentType=”text/html; charset=UTF-8″ pageEncoding=”UTF-8″%>
<%@ taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core&#8221; %>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>

<title>Employees</title>
</head>
<body>
<table border=1>
<thead><tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr></thead>

<tr>
<td>${employee.id}</td>
<td>${employee.name}</td>
<td>${employee.email}</td>
</tr>

</table>
</body>
</html>

The content of employees.jsp is

<%@ page language=”java” contentType=”text/html; charset=UTF-8″ pageEncoding=”UTF-8″%>
<%@ taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core&#8221; %>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>Employees</title>
</head>
<body>
<table border=1>
<thead><tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr></thead>
<c:forEach var=”employee” items=”${employees.employees}”>
<tr>
<td>${employee.id}</td>
<td>${employee.name}</td>
<td>${employee.email}</td>
</tr>
</c:forEach>
</table>
</body>
</html>

11. edit the servlet-context.xml file

<?xml version=”1.0″ encoding=”UTF-8″?>
<beans:beans xmlns=”http://www.springframework.org/schema/mvc&#8221;
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xmlns:beans=”http://www.springframework.org/schema/beans&#8221;
xmlns:context=”http://www.springframework.org/schema/context&#8221;
xsi:schemaLocation=”http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd”&gt;

<!– Enables the Spring MVC @Controller programming model –>

<annotation-driven />

<!– Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory –>

<resources mapping=”/resources/**” location=”/resources/” />

<!– Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory–>

<beans:bean class=”org.springframework.web.servlet.view.ContentNegotiatingViewResolver”>
<beans:property name=”mediaTypes”>
<beans:map>
<beans:entry key=”xml” value=”application/xml”/>
<beans:entry key=”html” value=”text/html”/>
</beans:map>
</beans:property>
<beans:property name=”viewResolvers”>
<beans:list>
<beans:bean class=”org.springframework.web.servlet.view.BeanNameViewResolver”/>
<beans:bean id=”viewResolver” class=”org.springframework.web.servlet.view.UrlBasedViewResolver”>
<beans:property name=”viewClass” value=”org.springframework.web.servlet.view.JstlView”/>
<beans:property name=”prefix” value=”/WEB-INF/views/”/>
<beans:property name=”suffix” value=”.jsp”/>
</beans:bean>
</beans:list>
</beans:property>
</beans:bean>

<beans:bean id=”employees” class=”org.springframework.web.servlet.view.xml.MarshallingView”>
<beans:constructor-arg ref=”jaxbMarshaller” />
</beans:bean>
<context:component-scan base-package=”com.foo.myrest.controller” />
<beans:bean id=”employeeDS” class=”com.foo.myrest.ds.EmployeeDS” />

<!–Defines the marshaller/unmarshaller that uses JAXB 2 to do the object XML mapping (OXM)–>

<beans:bean id=”jaxbMarshaller” class=”org.springframework.oxm.jaxb.Jaxb2Marshaller”>
<beans:property name=”classesToBeBound”>
<beans:list>
<beans:value>com.foo.myrest.bean.Employee</beans:value>
<beans:value>com.foo.myrest.bean.EmployeeList</beans:value>
</beans:list>
</beans:property>
</beans:bean>

</beans:beans>

Please keep in mind to make ContentNegotiatingViewResolver work, you MUST check the Spring’version in pom.xml, it must be 3.0.5.RELEASE or else you may encounter “NoSuchMethod” exception.

12. All done! Now what you need to do is to re-do step 3,4,5

13. Open a browser, type http://localhost:8080/myrest/employees the following page is expected.

Image

14. type http://localhost:8080/myrest/employee/1, you will see:

Image

15. type http://localhost:8080/myrest/employees.xml you will see below. Why there is a section called employeeABC? Remember in step 7 we have one line

@XmlElement(name=”employeeABC”)

exployees

===

Summary

In this post, I have provided a tutorial on how to create a Spring MVC based REST application.

Advertisements