使用SpringMVC开发RestFul风格接口的java-web项目,tomcat部署并客户端访问

本文介绍如何使用IntelliJ IDEA和Gradle构建一个Spring Web应用程序,包括配置build.gradle文件、搭建web.xml和dispatcher-servlet.xml,实现RESTful API并通过Tomcat部署。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.使用intellij idea开发,gradle构建工程。webcollection模块就是接口所在项目模块,handleMessage类就是接口类。

2.接口项目模块的build.gradle配置文件内容如下:

apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'war'

group = 'com.cloudcollection'
archivesBaseName = 'webcollection'
version = '0.1'
sourceCompatibility = 1.8
targetCompatibility = 1.8
// java编译的时候缺省状态下会因为中文字符而失败
[compileJava,compileTestJava,javadoc]*.options*.encoding = 'UTF-8'
webAppDirName = 'webapp'
war{
    archiveName ="webcollection.war"
}

buildscript {
    repositories {
        maven { url "https://repo.spring.io/libs-release" }
        jcenter()
    }

}


task wrapper(type: Wrapper) {
    gradleVersion = '3.5'
}

idea {
    module {
        downloadJavadoc = false
        downloadSources = false
    }
}


sourceSets {
    main {
        output.resourcesDir = "bin/classes"
    }
}

repositories {
    mavenCentral()
    mavenCentral name: "erichseifert.de", artifactUrls: ["http://mvn.erichseifert.de/maven2"]
}

dependencies {
    compile project(":commons")
    compile project(":model")

    testCompile('junit:junit:4.12')

    compile 'org.springframework:spring-core:4.3.6.RELEASE'
    compile 'org.springframework:spring-web:4.3.6.RELEASE'
    compile 'org.springframework:spring-webmvc:4.3.6.RELEASE'
    providedCompile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.1.0'
}

war {
    from 'src/main/webapp' // adds a file-set to the root of the archive
}

3.web.xml的内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app
        version="3.1"
        metadata-complete="false"
        xmlns="http://xmlns.jcp.org/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

</web-app>

4.接口依赖查找需要用到配置文件dispatcher-servlet.xml,内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="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
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="repository.collect.controller"></context:component-scan>
    <mvc:annotation-driven></mvc:annotation-driven>
</beans>

5.一切就绪,开始服务端接口的开发:handleMessage.java类

@RestController
@RequestMapping("/repository")
public class handleMessage {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    public handleMessage() {}

    /**
     * 获得token接口
     * @param json 不同系统的唯一标识,可以生成唯一token返回
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/getCollectTaskToken",method = RequestMethod.POST,
            produces = "application/json;charset=UTF-8")
    public String getCollectTaskToken(@RequestBody String json) {
        JSONObject jsonObject =  JSONObject.fromObject(json);
        String key = jsonObject.getString("key");

        String token = "";
        String msg = "token生成成功!";
        String response = "true";
        try {
            //先根据key从数据库表中查询,如果有则返回token; 如果没有则创建保存。
            Document doc = Mongodb.getMongoDb().getDatabase(Constant.MONGO_DB_NAME).getCollection(Constant.WEB_COLLECTION_TOKEN)
                    .find(Filters.eq("key",key)).first();
            if (doc!=null) {
                token = doc.getString("token");
            } else {
                //根据key生成唯一token,并生成json返回
                token = StringUtils.hash(key);
                //将系统的标识key和对应的token保存到mongodb中
                Mongodb.getMongoDb().getDatabase(Constant.MONGO_DB_NAME).getCollection(Constant.WEB_COLLECTION_TOKEN)
                        .insertOne(new Document("key",key).append("token",token));
            }
        } catch (Exception e) {
            logger.error("系统生成token失败:", e);
            msg = "token生成失败!";
            response = "false";
        }
        return "{\"msg\":\""+msg+"\",\"response\":\""+response+"\",\"token\":\""+token+"\"}";
    }

6.传递的参数是json字符串,接口处理返回也是json字符串。

7.使用gradle build命令打war包,在tomcat中部署。

8.客户端请求类:

public class TestWebCollection {

    //post提交调用方法
    public static String post(String uri, Map<String,Object> map) throws UnsupportedEncodingException {
        //所有的参数都放在map中,然后转换成json字符串传递到接口中
        String str = JSONObject.fromObject(map).toString();
        System.out.println("json参数:"+str);

        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(uri);
        httpPost.setEntity(new StringEntity(str, Charset.forName("utf-8")));
        try {
            HttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println("http返回码:"+statusCode);
            //如果返回状态是200,打印返回信息
            if (statusCode==200) {
                HttpEntity entity = response.getEntity();
                String entityStr = EntityUtils.toString(entity);
                System.out.println("客户端接收内容:"+entityStr);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        Map<String,Object> map = new HashMap<>();

        //接口1
        map.put("key","IRR2_0");//有多少个参数,都可放在map中
        post("http://localhost:8080/webcollection/repository/getCollectTaskToken", map);
    }
}

客户端调用接口控制台日志内容如下:

json参数:{"key":"IRR2_0"}
http返回码:200

客户端接收内容:{"msg":"token生成成功!","response":"true","token":"d71161a15e23713aedc7cb4bd0438fc5"}

9.特别注意:项目在idea工具中使用关联的tomcat启动服务,接口的url是不需要项目名称的,如下:

"http://localhost:8080/repository/getCollectTaskToken"

而项目在tomcat中单独部署时,接口的url需要加上web项目名称“webcollection”,不然会报404。







评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值