Spring REST Template

夙愿已清 提交于 2019-12-17 03:00:04

简介

我们之前都使用过HttpClient来发送HTTP请求,但我们很多时间都需要将HttpClient请求或者响应的数据转换为Java对象,HttpClient需要我们自己手动来解析。我们今天要介绍的Spring REST Template比HttpClient用起来更加方便简洁。

思路:

一、后台主要提供RESTFUL Service服务
二、门户,也就是前端系统,用来处理浏览器提交的请求,接收到用户请求会使用Spring REST Template来提交RESTFUL Service请求
在这里插入图片描述
基于Maven构建,使用Spring Boot 2.x开发

项目开发

management+portal
managerment项目架构:
在这里插入图片描述
porm:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.lucas</groupId>
    <artifactId>management</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>management</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
<!--        <dependency>-->
<!--            <groupId>org.springframework</groupId>-->
<!--            <artifactId>spring-web</artifactId>-->
<!--            <version>5.2.2.RELEASE</version>-->
<!--        </dependency>-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

注意:porm中的web和thymeleaf均为boot的,注意不要依赖错误
实体类:
User:

package com.lucas.management.controller;

/**
 * @Author Lucas
 * @Date 2019/12/13 17:44
 * @Version 1.0
 */
public class User {
    private Integer id;
    private String username;
    private String password;

    public User() {
    }

    public User(Integer id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public boolean matchUsernameAndPassword(String username, String password) {
        if(this.username.equals(username) && this.password.equals(password)) {
            return true;
        }else {
            return false;
        }
    }
}

ResResult

package com.lucas.management.controller;

/**
 * @Author Lucas
 * @Date 2019/12/16 9:16
 * @Version 1.0
 */
public class ResResult {
    private boolean success;
    private String message;

    public ResResult() {
    }

    public ResResult(boolean success, String message) {
        this.success = success;
        this.message = message;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

dao:相当于真正干活的
接口UserDao:

package com.lucas.management.controller;

import java.util.List;

/**
 * @Author Lucas
 * @Date 2019/12/16 9:28
 * @Version 1.0
 */
public interface UserDao {
    void save(User user);
    User findone(String username,String password);
    List<User> findAll();
}

UserDao的实现类UserDaoImpl:

package com.lucas.management.controller;

import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author Lucas
 * @Date 2019/12/16 9:31
 * @Version 1.0
 */
@Repository
public class UserDaoImpl implements UserDao {
    //添加一些测试数据


    public UserDaoImpl() {
        User user1 = new User();
        user1.setId(1);
        user1.setUsername("zhangsan");
        user1.setPassword("0");

        User user2 = new User();
        user2.setId(2);
        user2.setUsername("lisi");
        user2.setPassword("0");

        users.add(user1);
        users.add(user2);

    }

    private List<User> users = new ArrayList<>();

    @Override
    public void save(User user) {
        users.add(user);
    }

    @Override
    public User findone(String username, String password) {
        User userTmp = new User();
        userTmp.setUsername(username);
        userTmp.setPassword(password);

        for(User user: users) {
            if(user.matchUsernameAndPassword(username,password)) {
                return user;
            }
        }

        return null;
    }

    @Override
    public List<User> findAll() {
        return users;
    }
}

service:服务,本工程有哪些服务项
UserServie接口:

package com.lucas.management.controller;

import java.util.List;

/**
 * @Author Lucas
 * @Date 2019/12/16 9:10
 * @Version 1.0
 */

public interface UserService {
    void regist(User user);
    User login(String username, String password);
    List<User> findAll();
}

UserService的实现类UserServiceImpl:

package com.lucas.management.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author Lucas
 * @Date 2019/12/16 9:27
 * @Version 1.0
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;

    @Override
    public void regist(User user) {
        userDao.save(user);
    }

    @Override
    public User login(String username, String password) {
        return userDao.findone(username,password);
    }

    @Override
    public List<User> findAll() {
        return userDao.findAll();
    }
}

向外界提供的接口Controller:
UserRestService:

package com.lucas.management.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author Lucas
 * @Date 2019/12/16 9:09
 * @Version 1.0
 */
@RestController
@RequestMapping("/user")
public class UserRestService {
    @Autowired
    private UserService userService;

    /**
     * 注册服务
     * @param user
     * @return
     */
    @RequestMapping(method = RequestMethod.POST)
    public ResResult regist(@RequestBody User user) {
        System.out.println("----regist----");
        try {
            userService.regist(user);
            return new ResResult(true,"添加成功!");
        } catch (Exception e){
            e.printStackTrace();
            return new ResResult(false, "添加失败!");
        }
    }

    @RequestMapping(value="/{username}/{password}",method = RequestMethod.GET)
    public User login(@PathVariable("username") String username, @PathVariable("password") String password) {
        try {
            return userService.login(username,password);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping(method = RequestMethod.GET)
    public List<User> findAll() {
        System.out.println("----get----");
        return userService.findAll();
    }
}

applacation.yml:

server:
  port: 9001
servlet:
  context-path: /

RESTFUL Service接口调用URL

  • 添加用户 Requsest URL: http://localhost:9001/user/ Request Method: POST
  • 根据用户名密码查询用户 Requsest URL: http://localhost:9001/user/用户名/密码 Request
    Method: GET
  • 查询所有用户 Requeset URL: http://localhost:9001/user/ Request Method: GET

portal项目架构:
在这里插入图片描述
porm:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.lucas</groupId>
    <artifactId>portal</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>portal</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

IndexController:主要目的为了打开login.html页面

package com.lucas.portal.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @Author Lucas
 * @Date 2019/12/16 11:08
 * @Version 1.0
 */
@Controller
@RequestMapping("/")
public class IndexController {
    @RequestMapping(value = {"", "login.html"})
    public String login() {
        return "login";
    }

    @RequestMapping(value="success.html")
    public String success(Model model) {
        model.addAttribute("message","username");
        return "success";
    }
}


实体类:User和ResResult
User:

package com.lucas.portal.controller;

/**
 * @Author Lucas
 * @Date 2019/12/13 17:44
 * @Version 1.0
 */
public class User {
    private Integer id;
    private String username;
    private String password;

    public User() {
    }

    public User(Integer id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public boolean matchUsernameAndPassword(String username, String password) {
        if(this.username.equals(username) && this.password.equals(password)) {
            return true;
        }else {
            return false;
        }
    }
}

ResResult:

package com.lucas.portal.controller;

/**
 * @Author Lucas
 * @Date 2019/12/16 9:16
 * @Version 1.0
 */
public class ResResult {
    private boolean success;
    private String message;

    public ResResult() {
    }

    public ResResult(boolean success, String message) {
        this.success = success;
        this.message = message;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

UserController:

package com.lucas.portal.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author Lucas
 * @Date 2019/12/16 10:04
 * @Version 1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private RestTemplate restTemplate;

    private String USERSERVICE_URL="http://localhost:9001/user";

    @RequestMapping("/login")
    public Map login(String username, String password) {
        System.out.println("---login---");
        System.out.println("username:" + username + "  password:" + password);
        Map<String,String> params = new HashMap<String,String>();
        params.put("username",username);
        params.put("password",password);
        //发送GET请求
        User user = restTemplate.getForObject(USERSERVICE_URL+"/{username}/{password}",User.class,params);
        Map<String, Object> result = new HashMap<>();
        if(user != null) {
            result.put("success",true);
        } else {
            result.put("success",false);
            result.put("message","登录失败!");
        }
        return result;
    }

    @RequestMapping("/regist")
    public ResResult login(@RequestBody User user) throws IOException {
        return restTemplate.postForObject(USERSERVICE_URL+"/",user,ResResult.class);
    }
}

前台页面login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
   
<table class="table">
           
    <tr>
                   
        <td>用户名</td>
                   
        <td><input type="text" id="username"></td>
               
    </tr>
           
    <tr>
                   
        <td>密码</td>
                   
        <td><input type="text" id="password"></td>
               
    </tr>
           
    <tr>
                   
        <td></td>
                   
        <td>
                           
            <button id="btn">登录</button>
                           
            <button id="btn1">注册</button>

            <button id="btn2">测试</button>
                       
        </td>
               
    </tr>


       
</table><script type="text/javascript">
    $(function () {
        $('#btn2').click(function () {
            alert("test")
            var url = 'user/login?usernmae=' + $('#username').val() + '&password=' + $('#password').val()
            $.get(url, function (data) {
                alert(data.success + '' + data.message)
            })
        });
        $('#btn').click(function () {
            $.get('user/login?username=' + $('#username').val() + '&password=' + $('#password').val(), function (data) {
                if (!data.success) {
                    alert(data.message);
                } else {
                    window.location.href = "success.html";
                }
            });
        });
        $('#btn1').click(function () {
            var user = {
                username: $('#username').val(),
                password: $('#password').val()
            };
            $.ajax({
                type: 'POST',
                url: 'user/regist',
                dataType: "json",
                contentType: "application/json",
                data: JSON.stringify(user),
                success: function (data) {
                    if (!data.success) {
                        alert(data.message);
                    } else {
                        alert("注册成功!");
                    }
                }
            });
        });
    });
</script>
</body>
</html>

success.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录成功</title>
</head>
<body>
<h1>登录成功,欢迎<p th:text="${message}"></p></h1>
</body>
</html>

配置文件:applacation.yml:

server:
  port: 9002
servlet:
  context-path: /

总结:

Spring REST Template比
HttpClient更加快捷方便的调用RS服务,它自动封装和解析Java对象。而且可以很方便的与Spring整合,快速注入Spring的bean对象。
注意Jquery .get.get、.post、$.ajax的区别

  • $.get(url, json对象)表示发送一个get请求,使用queryString的方式提交。url?username=tom…
  • $.post(url, json对象)表示发送一个post请求,数据部分类似于提交表单。
  • .ajaxjsonspringmvc@RequestBody使.ajax可以选择数据传递的格式、类型等。我们要将一个json串发送到spring mvc @RequestBody来接收需要使用.ajax。下面是示例代码
$.ajax({
  type:'POST',
  url:'user/regist',
  dataType:"json",
  contentType:"application/json",
  data:JSON.stringify(user),
  success:function(data){
    if(!data.success) {
      alert(data.message);
    }
    else {
      alert("注册成功!");
    }
  }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!