How to write RESTful web services using spring 3 mvc

Step 1) Update pom.xml to add support of JAXB and Jackson (for xml and json formats).

<dependency>
  <groupid>org.codehaus.jackson</groupid>
  <artifactid>jackson-mapper-asl</artifactid>
  <version>${jackson-mapper-asl.version}</version>
  <scope>runtime</scope>
</dependency>

<dependency>
  <groupid>javax.xml.bind</groupid>
  <artifactid>jaxb-api</artifactid>
  <version>${jaxb-api.version}</version>
  <scope>runtime</scope>
</dependency>

Do not forget to run “mvn eclipse:eclipse -Dwtpversion=2.0” command on command prompt again, to update the project dependencies.

Step 2) Update bean configuration file (spring-mvc-servlet.xml) for view resolvers.

<mvc:annotation-driven />

<context:component-scan  base-package="com.howtodoinjava.web" />

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    <property name="mediaTypes">
      <map>
          <entry key="html" value="text/html"></entry>
          <entry key="json" value="application/json"></entry>
          <entry key="xml"  value="application/xml"></entry>
      </map>
    </property>
     <property name="viewResolvers">
        <list>
          <bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
            <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
            <property name="prefix" value="/WEB-INF/jsp/"></property>
            <property name="suffix" value=".jsp"></property>
          </bean>
        </list>
    </property>
</bean>

Step 3) Add model classes I am writing 2 classes i.e. Users.java and User.java. These classes will be having JAXB annotations, which will be used by marshaller to convert them in appropriate xml or json formats. They are for example only and you can write your own classes.

package com.howtodoinjava.model;

import java.util.Collection;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="users")
@XmlAccessorType(XmlAccessType.NONE)
public class Users
{
    @XmlElement(name="user")
    private Collection<User> users;

    public Collection<User> getUsers() {
        return users;
    }

    public void setUsers(Collection<User> users) {
        this.users = users;
    }
}

Now write User.java.

package com.howtodoinjava.model;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="user")
@XmlAccessorType(XmlAccessType.NONE)
public class User {

    @XmlElement(name="first-name")
    private String firstName;

    @XmlElement(name="last-name")
    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;
    }
}

Step 4) Update the controller Our DemoController.java will modified to have REST specific annotations for path mappings in request parameters mappings. Also, we will specify the header attributes for request and response.

@Controller
@RequestMapping("/users")
public class DemoController
{
    @RequestMapping(method = RequestMethod.GET, value="/{id}", headers="Accept=*/*")
    public @ResponseBody User getUserById(@PathVariable String id)
    {
        User user = new User();
        user.setFirstName("john");
        user.setLastName("adward");
        return user;
    }

    @RequestMapping(method = RequestMethod.GET,  headers="Accept=*/*")
    public @ResponseBody Users getAllUsers()
    {
        User user1 = new User();
        user1.setFirstName("john");
        user1.setLastName("adward");

        User user2 = new User();
        user2.setFirstName("tom");
        user2.setLastName("hanks");

        Users users = new Users();
        users.setUsers(new ArrayList<User>());
        users.getUsers().add(user1);
        users.getUsers().add(user2);

        return users;
    }
}

Now lets re-deploy the application on tomcat and hit the URL on any REST client. I am using RESTClient. This is a firefox plugin for testing the RESTful webservices.

URL : http://localhost:8080/firstSpringApplication/users

URL : http://localhost:8080/firstSpringApplication/users/123

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值