5分鐘構建基于Spring Web MVC REST風格HelloWorld示例

jopen 10年前發布 | 62K 次閱讀 Spring MVC Web框架

當然寫本文的目的不是為了速度,只是表明現在構建一個Spring web mvc Rest風格的HelloWorld應用會很簡單。不過如果看過Spring Boot這個項目,可能只需要最多3分鐘就能構建一個簡單的Rest風格應用。回頭研究下,然后分享下。

 

我的構建環境

JDK 7

Maven 3

Servlet3容器

 

創建項目

首先使用Maven創建一個普通Maven應用即可,不必是web的。

 

添加依賴

        <!-- servlet 3 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
        </dependency>

        <!--spring context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>4.0.0.RELEASE</version>
        </dependency>

        <!--spring webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.0.0.RELEASE</version>
        </dependency>

        <!--jackson -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.2.3</version>
        </dependency>

 servlet3依賴scope是provided表示環境提供,然后添加spring-context-support和spring-webmvc依賴,最后用于json的jackson依賴。非常簡單明了。

 

添加maven插件

為了方便測試,添加jetty的maven插件,這樣直接使用mvn jetty:run即可運行。

    <build>
        <finalName>springmvc</finalName>
        <plugins>
            <plugin>
                <groupId>org.mortbay.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>8.1.8.v20121106</version>
                <configuration>
                    <reload>manual</reload>
                    <webAppConfig>
                        <contextPath>/${project.build.finalName}</contextPath>
                    </webAppConfig>
                    <connectors>
                        <connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector">
                            <port>9080</port>
                            <!--<maxIdleTime>60000</maxIdleTime>-->
                        </connector>
                    </connectors>
                </configuration>
            </plugin>
        </plugins>
    </build>

  

實體 

package com.sishuok.entity;

import java.io.Serializable;

/**
 * <p>User: Zhang Kaitao
 * <p>Date: 13-12-19
 * <p>Version: 1.0
 */
public class User implements Serializable {
    private Long id;
    private String name;

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

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        User user = (User) o;

        if (id != null ? !id.equals(user.id) : user.id != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        return id != null ? id.hashCode() : 0;
    }
}

 

控制器

package com.sishuok.controller;

import com.sishuok.entity.User;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>User: Zhang Kaitao
 * <p>Date: 13-12-19
 * <p>Version: 1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public User view(@PathVariable("id") Long id) {
        User user = new User();
        user.setId(id);
        user.setName("zhang");
        return user;
    }
}

 

SpringMVC注解風格配置

@Configuration
@EnableWebMvc
@ComponentScan
public class AppConfig {
}

 

 

Servlet3容器啟動初始化器

在Servlet容器啟動時編程式注冊Servlet

package com.sishuok;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

/**
 * <p>User: Zhang Kaitao
 * <p>Date: 13-12-19
 * <p>Version: 1.0
 */
public class AppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext webApplicationContext =
                new AnnotationConfigWebApplicationContext();
        webApplicationContext.register(AppConfig.class);


        DispatcherServlet dispatcherServlet = new DispatcherServlet(webApplicationContext);
        ServletRegistration.Dynamic dynamic = servletContext.addServlet("dispatcherServlet", dispatcherServlet);
        dynamic.addMapping("/");

    }
}

 

 

然后運行 mvn jetty:run運行即可,瀏覽器輸入如下地址即可得到我們的json數據。

http://localhost:9080/springmvc/user/1

 

參考示例的github地址:springmvc-rest-helloworld

 

非常簡單的一個Rest風格的web應用就搭建完了,接下來再完善即可。

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!