Spring MVC:Ajax和JQuery

今天,我想演示如何将AJAX集成到Spring MVC应用程序中。 我将在客户端使用JQuery来发送请求和接收响应。 本教程将基于我以前关于Spring MVC和REST服务的教程之一。 在本文中,您将了解如何在异步请求的帮助下使Web应用程序更具交互性。

准备工作

我需要通过删除不再需要的方法来修改SmartphoneController类。 这是AJAX集成的第一步。

//imports are omitted
@Controller
@RequestMapping(value="/smartphones")
public class SmartphoneController {

	@Autowired
	private SmartphoneService smartphoneService;

	@RequestMapping(value="/create", method=RequestMethod.GET)
	public ModelAndView createSmartphonePage() {
		ModelAndView mav = new ModelAndView("phones/new-phone");
		mav.addObject("sPhone", new Smartphone());
		return mav;
	}

	@RequestMapping(value="/create", method=RequestMethod.POST, 
			produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public Smartphone createSmartphone(@RequestBody Smartphone smartphone) {
		return smartphoneService.create(smartphone);
	}

	@RequestMapping(value="/edit/{id}", method=RequestMethod.GET)
	public ModelAndView editSmartphonePage(@PathVariable int id) {
		ModelAndView mav = new ModelAndView("phones/edit-phone");
		Smartphone smartphone = smartphoneService.get(id);
		mav.addObject("sPhone", smartphone);
		return mav;
	}

	@RequestMapping(value="/edit/{id}", method=RequestMethod.PUT, 
			produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public Smartphone editSmartphone(@PathVariable int id, 
			@RequestBody Smartphone smartphone) {
		smartphone.setId(id);
		return smartphoneService.update(smartphone);
	}

	@RequestMapping(value="/delete/{id}", method=RequestMethod.DELETE, 
			produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public Smartphone deleteSmartphone(@PathVariable int id) {
		return smartphoneService.delete(id);
	}

	@RequestMapping(value="", method=RequestMethod.GET,
			produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public List< Smartphone > allPhones() {
		return smartphoneService.getAll();
	}

	@RequestMapping(value="", method=RequestMethod.GET)
	public ModelAndView allPhonesPage() {
		ModelAndView mav = new ModelAndView("phones/all-phones");
		List< Smartphone > smartphones = new ArrayList< Smartphone >();
		smartphones.addAll(allPhones());
		mav.addObject("smartphones", smartphones);
		return mav;
	}

}

您可以将新版本的SmartphoneController与旧版本进行比较。 删除了处理PUT,POST,DELETE请求并返回ModelAndView对象的方法。 由于AJAX调用可以直接寻址到REST方法,因此删除了这些方法。 现在,控制器仅包含两种类型的方法:

  • 第一种将用户定向到可以执行CRUD操作的页面。
  • 第二种类型执行CRUD操作(REST方法)

客户端

使用AJAX意味着在Web应用程序的客户端上有很多代码。 在本节中,我将演示一个基础知识,这些基础知识将帮助您了解实现AJAX调用需要执行的步骤。 让我们检查一下在应用程序中创建新智能手机的情况。

首先,我需要将JQuery库添加到HTML页面:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

HTML的主要部分进行了一次重要的更新-将表单操作属性的扩展名更改为.json

<div id="container">
<h1>Create new Smartphone</h1>
<div>
<p>Here you can create new Smartphone:</p>
<div id="sPhoneFromResponse"></div>
</div>
<form:form id="newSmartphoneForm" action="${pageContext.request.contextPath}/smartphones/create.json" commandname="sPhone">
<table>
<tbody>
<tr>
<td>Producer:</td>
<td>
<form:select path="producer">
	<form:option value="NOKIA">Nokia</form:option>
	<form:option selected="selected" value="IPHONE">iPhone</form:option>
	<form:option value="HTC">HTC</form:option>
	<form:option value="SAMSUNG">Samsung</form:option>
</form:select>
</td>
</tr>
<tr>
<td>Model:</td>
<td><form:input path="model"></form:input></td>
</tr>
<tr>
<td>Price:</td>
<td><form:input path="price"></form:input></td>
</tr>
<tr>
<td><input value="Create" type="submit"></td>
<td></td>
</tr>
</tbody>
</table>
</form:form>
<a href="${pageContext.request.contextPath}/index.html">Home page</a>
</div>

现在,女士们,先生们,我希望介绍一段用于创建新智能手机的JQuery代码:

$(document).ready(function() {

      $('#newSmartphoneForm').submit(function(event) {

    	  var producer = $('#producer').val();
    	  var model = $('#model').val();
    	  var price = $('#price').val();
    	  var json = { "producer" : producer, "model" : model, "price": price};

        $.ajax({
        	url: $("#newSmartphoneForm").attr( "action"),
        	data: JSON.stringify(json),
        	type: "POST",

        	beforeSend: function(xhr) {
        		xhr.setRequestHeader("Accept", "application/json");
        		xhr.setRequestHeader("Content-Type", "application/json");
        	},
        	success: function(smartphone) {
        		var respContent = "";

		  		respContent += "<span class="success">Smartphone was created: [";
		  		respContent += smartphone.producer + " : ";
		  		respContent += smartphone.model + " : " ;
		  		respContent += smartphone.price + "]</span>";

        		$("#sPhoneFromResponse").html(respContent);   		
        	}
        });

        event.preventDefault();
      });

    });

我不会停止这段代码并详细解释它,因为您可以在官方网站上阅读有关AJAX和JQuery的信息。

简要说明:当某人想要提交具有指定ID的表单时,所有表单字段都分配给适当的变量。 之后,根据表单字段变量生成一个新的JSON文档。 然后执行AJAX调用。 它指向在表单标签的action属性中指定的URL。 JSON用作需要处理的数据。 请求的类型为POST(它可以根据操作而有所不同,例如,对于更新,它将具有PUT值)。 在beforeSend函数中,我明确指定了JSON格式所需的标头。 最后,我制定一个响应并将其插入DOM。

创造新的智能手机

就是与智能手机的创作有关的东西。 智能手机的更新与此类似,只是请求的类型需要更改。

现在,让我们看看如何处理DELETE类型的请求。 和以前一样,我需要将URL扩展名更改为.json

<a href="${pageContext.request.contextPath}/smartphones/delete/${sPhone.id}.json">Delete</a>

与POST和PUT相比,用于DELETE操作的JQuery代码将有所不同。

$(document).ready(function() {

	var deleteLink = $("a:contains('Delete')");

	$(deleteLink).click(function(event) {

		$.ajax({
			url: $(event.target).attr("href"),
			type: "DELETE",

			  beforeSend: function(xhr) {
			  	xhr.setRequestHeader("Accept", "application/json");
			  	xhr.setRequestHeader("Content-Type", "application/json");
			  },

			  success: function(smartphone) {
			  	var respContent = "";
			  	var rowToDelete = $(event.target).closest("tr");

			  	rowToDelete.remove();

			  	respContent += "<span class="success">Smartphone was deleted: [";
			  	respContent += smartphone.producer + " : ";
			  	respContent += smartphone.model + " : " ;
			  	respContent += smartphone.price + "]</span>";

			  	$("#sPhoneFromResponse").html(respContent);   		
			  }
		});

		event.preventDefault();
	});

});

第一个区别是元素的选择器。 如果使用DELETE,我想使用链接,但不使用表单。 AJAX调用的类型更改为DELETE值。 没有与请求一起发送的任何数据。 最后,我删除了需要删除的智能手机行。

删除智能手机

摘要

我希望这份简短的AJAX概述对您有所帮助。 AJAX可以在任何Web应用程序中实现很多功能,因此请不要忽略这种与服务器通信的便捷方法。 您可以在GitHub上找到此应用程序。

参考: Spring MVC: Fruzenshtein的便笺博客中来自JCG合作伙伴 Alexey Zvolinskiy的Ajax&JQuery

翻译自: https://www.javacodegeeks.com/2013/09/spring-mvc-ajax-jquery.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值