Spring REST控制器示例

学习创建可在任何Spring MVC应用程序中处理REST API调用的Spring REST控制器。它邀请添加@Controller@RequestMapping注解。

为了编写此应用程序,我正在修改Spring MVC示例中编写的源代码。因此,如果需要,您可以从给定的链接下载源代码。

1.更新Maven依赖项

更新pom.xml以添加对JAXB和Jackson的支持(针对xmljson格式)。

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

2.添加ContentNegotiatingViewResolver

更新用于视图解析器的bean配置文件,并添加ContentNegotiatingViewResolver

<mvc:annotation-driven />
<context:component-scan  base-package="com.how2codex.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>

3.在模型类中添加JAXB注解

我正在写2类,即Users.javaUser.jav。这些类将具有JAXB注解,marshaller将使用它们将其转换为适当的xml或json格式。

它们仅作为示例,您可以编写自己的类。

Users.java
package com.how2codex.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;
    }
}
User.java
package com.how2codex.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;
    }
}

4.创建REST控制器

DemoController.java具有用于在请求参数映射路径映射REST特定注解。另外,我们将为请求和响应指定头属性。

DemoController.java
@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;
    }
}

5.Spring托示例的演示

现在,让我们在tomcat上重新部署应用程序,并在任何REST客户端上访问URL。我正在使用RESTClient。这是一个用于测试RESTful Web服务的firefox插件。

  • 网址:http:// localhost:8080 / firstSpringApplication / usershttp:// localhost:8080 / firstSpringApplication / users
  • 网址:http:// localhost:8080 / firstSpringApplication / users / 123http:// localhost:8080 / firstSpringApplication / users / 123

如果确实有帮助,请给我评论,或者您有任何疑问。

快乐的学习!

saigon has written 1445 articles

Leave a Reply