Spring Boot AJAX 示例

本文以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.项目结构

Spring Boot AJAX 示例_第1张图片

2.项目依赖-pom.xml

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


  4.0.0

  org.thinkingingis
  spring-boot-ajax-example
  0.0.1-SNAPSHOT
  jar

  spring-boot-ajax-example
  http://maven.apache.org

  
    UTF-8
    1.8
  

  
  	org.springframework.boot
    spring-boot-starter-parent
    1.5.6.RELEASE
  

  
  	
    		org.springframework.boot
        spring-boot-starter-thymeleaf
    
    
        org.springframework.boot
        spring-boot-devtools
        true
    
    
        org.webjars
        jquery
    		2.2.4
    
    
        org.webjars
        bootstrap
    		3.3.7
    
  
  
	
		
			
			
				maven-compiler-plugin
				3.3
				
					true
					/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/bin/java
				
			
			
			
		
	

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;

@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(errors.hasErrors()) {
			result.setMsg(errors.getAllErrors()
					.stream().map(x -> x.getDefaultMessage())
					.collect(Collectors.joining(",")));
			return ResponseEntity.badRequest().body(result);
		}
		
		List 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 result;
	
	public String getMsg() {
		return msg;
	}
	
	public void setMsg(String msg) {
		this.msg = msg;
	}
	
	public List getResult() {
		return result;
	}
	
	public void setResult(List 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;

@Service
public class UserService {
	private List users;
	
	public List findByUserNameOrEmail(String username){
		List result = users.stream()
				.filter(x -> x.getUsername().equalsIgnoreCase(username))
				.collect(Collectors.toList());
		return result;
	}
	
	//初始化一些user
	@PostConstruct
	private void initDataForTesting() {
		users = new ArrayList();
		User user1 = new User("Thinking", "password111", "[email protected]");
		User user2 = new User("in", "password222", "[email protected]");
		User user3 = new User("gis", "password333", "[email protected]");
		
		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;

@Controller
public 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;

@SpringBootApplication
public class SpringBootWebApplication {
	public static void main(String[] args) {
		SpringApplication.run(SpringBootWebApplication.class, args);
	}

}
4.HTML页面 + jquey ajax 
4.1 html页面用到了thymeleaf引擎,集成了bootstrap
index.html





    Spring Boot ajax example
    

    





Spring Boot AJAX 示例


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 = "

Ajax Response

"
				+ JSON.stringify(data, null, 4) + "
"; $('#feedback').html(json); console.log("SUCCESS : ", data); $("#btn-search").prop("disabled", false); }, error: function(e){ var json = "

Ajax Response

"
                + e.responseText + "
"; $('#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/

Spring Boot AJAX 示例_第2张图片


5.3 如果用户名为空时 提交

Spring Boot AJAX 示例_第3张图片

Spring Boot AJAX 示例_第4张图片

5.4如果用户名不存在

Spring Boot AJAX 示例_第5张图片

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

Spring Boot AJAX 示例_第6张图片

Spring Boot AJAX 示例_第7张图片


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


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

Spring Boot AJAX 示例_第8张图片


你可能感兴趣的:(spring,boot)