Spring Boot AJAX 示例

2017-10-28 19:43:39来源:CSDN作者:gisboygogogo人点击

分享

本文以spring boot框架、thymeleaf引擎为基础,利用jquery.ajax提交HTML表单请求到后台(spring rest api),后台返回一个JSON格式的数据为例进行说明。

开发环境:

  1. Spring Boot 1.5.6.RELEASE
  2. Spring 4.3.6.RELEASE
  3. Maven 3.3
  4. jQuery
  5. Bootstrap 3
  6. eclipse oxygen

更加细致的项目创建过程见前面的一篇文章:Spring Boot + Thymeleaf 创建web项目

1.项目结构

2.项目依赖-pom.xml

包含Spring Boot的依赖和一些webjars资源

<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/xsd/maven-4.0.0.xsd">  <modelVersion>4.0.0</modelVersion>  <groupId>org.thinkingingis</groupId>  <artifactId>spring-boot-ajax-example</artifactId>  <version>0.0.1-SNAPSHOT</version>  <packaging>jar</packaging>  <name>spring-boot-ajax-example</name>  <url>http://maven.apache.org</url>  <properties>    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>    <java.version>1.8</java.version>  </properties>  <parent>  	<groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-parent</artifactId>    <version>1.5.6.RELEASE</version>  </parent>  <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>			<!-- macOS 使用如下plugin  这是告诉可执行的jar文件位置-->			<plugin>				<artifactId>maven-compiler-plugin</artifactId>				<version>3.3</version>				<configuration>					<fork>true</fork>					<executable>/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/bin/java</executable>				</configuration>			</plugin>			<!--windows 系统 使用如下plugin  -->			<!-- 			<plugin>				<groupId>org.springframework.boot</groupId>				<artifactId>spring-boot-maven-plugin</artifactId>			</plugin>			 -->		</plugins>	</build></project>
3.Spring REST API

3.1 SearchController.java

接受查询条件,并返回一个ResponseEntity对象

package org.thinkingingis.controller;import java.util.List;import java.util.stream.Collectors;import javax.validation.Valid;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 org.thinkingingis.model.AjaxResponseBody;import org.thinkingingis.model.SearchCriteria;import org.thinkingingis.model.User;import org.thinkingingis.service.UserService;@RestControllerpublic 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(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);	}}
3.2 POJO

AjaxResponseBody.java

package org.thinkingingis.model;import java.util.List;public class AjaxResponseBody {	private String msg;	private 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;	}}

User.java

package org.thinkingingis.model;public class User {	private String username;	private String password;	private String email;		public User(String username, String password, String email) {		this.username = username;		this.password = password;		this.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;	}	}
3.3 验证---用于对提交的表单进行验证
SearchCriteria.java

package org.thinkingingis.model;import org.hibernate.validator.constraints.NotBlank;public class SearchCriteria {	@NotBlank(message = "用户名不能为空")	String username	;	public String getUsername() {		return username;	}	public void setUsername(String username) {		this.username = username;	}}

3.4 service层 

package org.thinkingingis.service;import java.util.ArrayList;import java.util.List;import java.util.stream.Collectors;import javax.annotation.PostConstruct;import org.springframework.stereotype.Service;import org.thinkingingis.model.User;@Servicepublic class UserService {	private List<User> users;		public List<User> findByUserNameOrEmail(String username){		List<User> result = users.stream()				.filter(x -> x.getUsername().equalsIgnoreCase(username))				.collect(Collectors.toList());		return result;	}		//初始化一些user	@PostConstruct	private void initDataForTesting() {		users = new ArrayList<User>();		User user1 = new User("Thinking", "password111", "thinking@gis.com");		User user2 = new User("in", "password222", "in@gis.com");		User user3 = new User("gis", "password333", "gis@gis.com");				users.add(user1);		users.add(user2);		users.add(user3);	}}
3.5 IndexController.java
package org.thinkingingis.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.GetMapping;@Controllerpublic class IndexController {	@GetMapping("/")	public String index() {		return "index";	}}
3.6SpringBootWebApplication.java
package org.thinkingingis;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class SpringBootWebApplication {	public static void main(String[] args) {		SpringApplication.run(SpringBootWebApplication.class, args);	}}
4.HTML页面 + jquey ajax 
4.1 html页面用到了thymeleaf引擎,集成了bootstrap
index.html

<!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head>    <title>Spring Boot ajax example</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="#">ThinkingInGIS</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 >ThinkingInGIS</a> 2017        </p>    </footer></div><script type="text/javascript" src="webjars/jquery/2.2.4/jquery.min.js"></script><script type="text/javascript" src="main.js"></script></body></html>

4.2 将查询条件转换成JSON格式,并通过$.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();	$("#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);					}	})}

5.启动项目
5.1 通过终端启动的话进入该项目 spring-boot-ajax-example下输入:
mvn spring-boot:run

5.2 浏览器访问 http://localhost:8080/


5.3 如果用户名为空时 提交

5.4如果用户名不存在

5.5 如果用户名存在可以找到



源码:https://github.com/ThinkingInGIS/spring-boot-ajax-example


至此,一个简单的spring boot + thymeleaf + ajax 程序 就搭建好了。
(如遇到问题,请留言给作者,以便共同探讨gis知识。thinkingingis@qq.com)
更多干货 欢迎关注微信公众号: ThinkingInGIS




最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台