码迷,mamicode.com
首页 > 编程语言 > 详细

Spring Boot Ajax实例

时间:2017-08-02 11:07:20      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:googl   classic   parent   pass   name   return   终端   enc   lease   

本文将展示如何使用jQuery.ajax将HTML表单请求发送到Spring REST API并返回JSON响应。

使用的工具 :

  1. Spring Boot 1.5.1.RELEASE
  2. Spring 4.3.6.RELEASE
  3. Maven 3
  4. jQuery
  5. Bootstrap 3

1. 项目结构

创建一个标准的Maven项目:ajax-example,用于演示在Spring Boot中使用Ajax技术,搜索用户信息。其结构如下图所示 -

2. 项目依赖

文件:pom.xml

<?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
    http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.yiibai</groupId>
<artifactId>ajax-example</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.1.RELEASE</version>
</parent>

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

<dependencies>

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

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>

    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>jquery</artifactId>
        <version>2.2.4</version>
    </dependency>

    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>bootstrap</artifactId>
        <version>3.3.7</version>
    </dependency>

</dependencies>

<build>
    <plugins>
        <!-- Package as an executable jar/war -->
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</project>
XML

3. Spring REST API

REST控制器,接受一个SearchCriteria并返回一个ResponseEntity

一个正常的Spring Boot依赖和一些webjars资源。文件:SearchController.java 如下所示 -

package com.yiibai.controller;

import com.yiibai.model.AjaxResponseBody;
import com.yiibai.model.SearchCriteria;
import com.yiibai.model.User;
import com.yiibai.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class SearchController {

    UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/api/search")
    public ResponseEntity<?> getSearchResultViaAjax(@Valid @RequestBody SearchCriteria search, Errors errors) {

        AjaxResponseBody result = new AjaxResponseBody();

        //If error, just return a 400 bad request, along with the error message
        if (errors.hasErrors()) {

            result.setMsg(errors.getAllErrors().stream().map(x -> x.getDefaultMessage()).collect(Collectors.joining(",")));
            return ResponseEntity.badRequest().body(result);

        }

        List<User> users = userService.findByUserNameOrEmail(search.getUsername());
        if (users.isEmpty()) {
            result.setMsg("no user found!");
        } else {
            result.setMsg("success");
        }
        result.setResult(users);

        return ResponseEntity.ok(result);
    }
}
Java

一些其它的POJO类,它们分别如下所示 -
文件:AjaxResponseBody.java

package com.yiibai.model;

import java.util.List;

public class AjaxResponseBody {

    String msg;
    List<User> result;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public List<User> getResult() {
        return result;
    }

    public void setResult(List<User> result) {
        this.result = result;
    }
}
Java

文件:User.java

package com.yiibai.model;

public class User {

    String username;
    String password;
    String email;

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

    @Override
    public String toString() {
        return "User{" +
                "username=‘" + username + ‘\‘‘ +
                ", password=‘" + password + ‘\‘‘ +
                ", email=‘" + email + ‘\‘‘ +
                ‘}‘;
    }

    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 String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}
Java

验证器类:SearchCriteria.java

package com.yiibai.model;

import org.hibernate.validator.constraints.NotBlank;

public class SearchCriteria {

    @NotBlank(message = "username can‘t empty!")
    String username;

    public String getUsername() {
        return username;
    }

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

用于初始化一些用户进行搜索的服务。文件:UserService.java 如下所示 -

package com.yiibai.services;

import com.yiibai.model.User;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserService {

    private List<User> users;

    // Love Java 8
    public List<User> findByUserNameOrEmail(String username) {

        List<User> result = users.stream().filter(x -> x.getUsername().equalsIgnoreCase(username)).collect(Collectors.toList());

        return result;

    }
    /*public List<User> findByUserNameOrEmail(String username, String email) {

        List<User> result = new ArrayList<User>();

        for (User user : users) {

            if ((!StringUtils.isEmpty(username)) && (!StringUtils.isEmpty(email))) {

                if (username.equals(user.getUsername()) && email.equals(user.getEmail())) {
                    result.add(user);
                    continue;
                } else {
                    continue;
                }

            }
            if (!StringUtils.isEmpty(username)) {
                if (username.equals(user.getUsername())) {
                    result.add(user);
                    continue;
                }
            }

            if (!StringUtils.isEmpty(email)) {
                if (email.equals(user.getEmail())) {
                    result.add(user);
                    continue;
                }
            }
        }
        return result;

    }*/

    // Init some users for testing
    @PostConstruct
    private void iniDataForTesting() {
        users = new ArrayList<User>();
        User user1 = new User("maxsu", "password111", "maxsu@yahoo.com");
        User user2 = new User("yiflow", "password222", "yflow@yahoo.com");
        User user3 = new User("minaxu", "password333", "minaxu@yahoo.com");
        User user4 = new User("minalee", "password333", "minalee@yahoo.com");
        User user5 = new User("yiiflow", "password333", "yiiflow@gmail.com");

        users.add(user1);
        users.add(user2);
        users.add(user3);
        users.add(user4);
        users.add(user5);
    }
}
Java

Spring Boot启动器(程序入口),参考以下代码实现。文件:SpringBootWebApplication.java 如下所示 -

package com.yiibai;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootWebApplication {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(SpringBootWebApplication.class, args);
    }
}
Java

4. HTML表单+ jQuery Ajax

一个简单的HTML表单,用 bootstrap 框架装饰。
文件:ajax.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Spring Boot Ajax实例</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

    <link rel="stylesheet" type="text/css"
          href="webjars/bootstrap/3.3.7/css/bootstrap.min.css"/>
</head>
<body>

<nav class="navbar navbar-inverse">
    <div class="container">
        <div class="navbar-header">
            <a class="navbar-brand" href="http://www.yiibai.com">易百教程</a>
        </div>
    </div>
</nav>

<div class="container" style="min-height: 500px">
    <div class="starter-template">
        <h1>Spring Boot AJAX 示例</h1>
        <div id="feedback"></div>
        <form class="form-horizontal" id="search-form">
            <div class="form-group form-group-lg">
                <label class="col-sm-2 control-label">用户名:</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" id="username"/>
                </div>
            </div>

            <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                    <button type="submit" id="bth-search"
                            class="btn btn-primary btn-lg">搜索
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>
<div class="container">
    <footer>
        <p>
            ? <a href="http://www.yiibai.com">Yiibai.com</a> 2017
        </p>
    </footer>
</div>
<script type="text/javascript"
        src="webjars/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
HTML

获取HTML表单,并通过JSON.stringify将搜索条件转换为JSON格式,并通过jQuery.ajax发送POST请求。
文件:main.js 如下所示 -

$(document).ready(function () {
    $("#search-form").submit(function (event) {
        //stop submit the form, we will post it manually.
        event.preventDefault();
        fire_ajax_submit();
    });

});

function fire_ajax_submit() {
    var search = {}
    search["username"] = $("#username").val();
    //search["email"] = $("#email").val();
    $("#btn-search").prop("disabled", true);
    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: "/api/search",
        data: JSON.stringify(search),
        dataType: ‘json‘,
        cache: false,
        timeout: 600000,
        success: function (data) {
            var json = "<h4>Ajax Response</h4><pre>"
                + JSON.stringify(data, null, 4) + "</pre>";
            $(‘#feedback‘).html(json);
            console.log("SUCCESS : ", data);
            $("#btn-search").prop("disabled", false);
        },
        error: function (e) {
            var json = "<h4>Ajax Response</h4><pre>"
                + e.responseText + "</pre>";
            $(‘#feedback‘).html(json);
            console.log("ERROR : ", e);
            $("#btn-search").prop("disabled", false);
        }
    });
}
Js

5. 运行示例

启动 Spring Boot 运行项目并测试结果。打开终端,进入到项目目录下(pom.xml文件所在目录),执行以下命令 -

F:\worksp\springboot\ajax-example> mvn spring-boot:run
... ...
02:57:41,425 |-INFO in ch.qos.logback.core.joran.action.AppenderRefAction - Attaching appender named [STDOUT] to Logger[ROOT]
02:57:41,425 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction - End of configuration.
02:57:41,425 |-INFO in ch.qos.logback.classic.joran.JoranConfigurator@7cf10a6f - Registering current configuration as safe fallback point


  .   ____          _            __ _ _
 /\\ / ___‘_ __ _ _(_)_ __  __ _ \ \ \ ( ( )\___ | ‘_ | ‘_| | ‘_ \/ _` | \ \ \  \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  ‘  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
::Spring Boot::       (v1.5.1.RELEASE)

2017-03-28 02:57:42 INFO  com.yiibai.SpringBootWebApplication - Starting SpringBootWebApplication on MY-PC with PID 7656 (F:\worksp\springboot\ajax-example\target\classes started by Administrator in F:\worksp\springboot\ajax-example)
2017-03-28 02:57:42 DEBUG com.yiibai.SpringBootWebApplication - Running with Spring Boot v1.5.1.RELEASE, Spring v4.3.6.RELEASE
2017-03-28 02:57:42 INFO  com.yiibai.SpringBootWebApplication - No active profile set, falling back to default profiles: default
2017-03-28 02:57:46 INFO  com.yiibai.SpringBootWebApplication - Started SpringBootWebApplication in 5.007 seconds (JVM running for 6.084)

打开浏览器,访问以下地址:http://localhost:8080/ , 应该会看到如下页面 -
技术分享

如果没有输入用户名,直接点击“搜索”,那么应该会看到以下结果 -
技术分享

如果输入一个存在的用户名:maxsu,直接点击“搜索”,那么应该会看到以下结果 -
技术分享

Spring Boot Ajax实例

标签:googl   classic   parent   pass   name   return   终端   enc   lease   

原文地址:http://www.cnblogs.com/ITMan-blogs/p/7272689.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!