侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

SpringMVC环境下实现的Ajax异步请求JSON格式数据

微信(小程序)  /  管理员 发布于 3年前   150

一 环境搭建

首先是常规的spring mvc环境搭建,不用多说,需要注意的是,这里需要引入jackson相关jar包,然后在spring配置文件“springmvc-servlet.xml”中添加json解析相关配置,我这里的完整代码如下:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"><!-- 避免IE执行AJAX时,返回JSON出现下载文件 --><bean id="mappingJacksonHttpMessageConverter"class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"><property name="supportedMediaTypes"><list><value>text/html;charset=UTF-8</value><value>application/json;charset=UTF-8</value></list></property><property name="objectMapper"><bean class="org.codehaus.jackson.map.ObjectMapper"><property name="dateFormat"><bean class="java.text.SimpleDateFormat"><constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss"></constructor-arg></bean></property></bean></property></bean><!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --><beanclass="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"><property name="messageConverters"><list><ref bean="mappingJacksonHttpMessageConverter" /><!-- json转换器 --></list></property></bean><mvc:annotation-drivencontent-negotiation-manager="contentNegotiationManager" /><bean id="contentNegotiationManager"class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean"><!-- true,开启扩展名支持,false关闭支持 --><property name="favorPathExtension" value="false" /><!-- 用于开启 /userinfo/123?format=json的支持 --><property name="favorParameter" value="true" /><!-- 设置为true以忽略对Accept Header的支持 --><property name="ignoreAcceptHeader" value="false" /><property name="mediaTypes"><value>atom=application/atom+xmlhtml=text/htmljson=application/jsonxml=application/xml*=*/*</value></property></bean><context:annotation-config /><!-- 启动自动扫描该包下所有的Bean(例如@Controller) --><context:component-scan base-package="cn.zifangsky.controller" /><mvc:default-servlet-handler /><!-- 定义视图解析器 --><bean id="jspViewResolver"class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="requestContextAttribute" value="rc" /><property name="viewClass"value="org.springframework.web.servlet.view.JstlView" /><property name="prefix" value="/WEB-INF/jsp/" /><property name="suffix" value=".jsp" /><property name="order" value="1"></property></bean></beans>

项目结构:

注:我这里测试使用的完整jar包:http://pan.baidu.com/s/1dEUwdmL

二 测试实例

(1)在WEB-INF/jsp目录下新建了一个index.jsp文件,包含了简单的jQuery的ajax请求,请求数据的格式是JSON,具体代码如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()+ path + "/";%><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><base href="//article/<%=basePath%>"><script type="text/javascript" src="//article/scripts/jquery/jquery-1.6.2.min.js"></script><script type="text/javascript" src="//article/scripts/jquery/jquery.i18n.properties-min-1.0.9.js"></script><script type="text/javascript" src="//article/scripts/jquery/jquery.autocomplete.js"></script><script type="text/javascript" src="//article/scripts/jquery/jquery.loadmask.js"></script><script type="text/javascript" src="//article/scripts/jquery/jquery.form.js"></script><script type="text/javascript" src="//article/scripts/jquery/jquery.timers.js"></script><title>jQuery i18n</title><script type="text/javascript">$().ready(function() {$("#sub").click(function() {var name = $("#username").val();var age = 18;var user = {"username":name,"age":age};$.ajax({url : 'hello.json',type : 'POST',data : JSON.stringify(user), // Request body contentType : 'application/json; charset=utf-8',dataType : 'json',success : function(response) {//请求成功alert("你好" + response.username + "[" + response.age + "],当前时间是:" + response.time + ",欢迎访问:http://www.zifangsky.cn");},error : function(msg) {alert(msg);}});});});</script></head><body><input type="text" id="username"style="width: 100px; height: 30px; font-size: 20px; font-weight: bold;"><input type="button" id="sub" value="Go"style="height: 40px; height: 30px;"><br></body></html>

(2)一个简单的model类User,代码如下:

package cn.zifangsky.controller;public class User {private String username;private int age;public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}

(3)controller类TestController.java:

package cn.zifangsky.controller;import java.text.Format;import java.text.SimpleDateFormat;import java.util.Date;import java.util.HashMap;import java.util.Map;import org.springframework.context.annotation.Scope;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.servlet.ModelAndView;@Controller@Scope("prototype")public class TestController {/*** 转到页面*/@RequestMapping(value = "/hello.html")public ModelAndView list() {ModelAndView view = new ModelAndView("index");return view;}/*** ajax异步请求, 请求格式是json*/@RequestMapping(value = "/hello.json", method = { RequestMethod.POST })@ResponseBodypublic Map<String, String> hello(@RequestBody User user) {// 返回数据的Map集合Map<String, String> result = new HashMap<String, String>();Format format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 返回请求的usernameresult.put("username", user.getUsername());// 返回年龄result.put("age", String.valueOf(user.getAge()));// 返回当前时间result.put("time", format.format(new Date()));return result;}}

关于具体的执行步骤我简单说一下:

i)项目启动后,在浏览器中访问:http://localhost:8089/SpringDemo/hello.html,然后会转到执行controller中的list方法,接着会转到/WEB-INF/jsp/index.jsp(PS:在controller中返回的是逻辑视图,跟在springmvc-servlet.xml文件中定义的路径前缀和后缀进行拼接后合成文件的真正路径)

ii)在index.jsp页面输入文字然后点击按钮,将会触发ajax请求,这个请求会获取输入框中的数据和默认的“age”参数拼接成json格式字符串最后提交到“hello.json”这个请求,也就是执行controller中的hello方法

iii)hello方法执行完毕后会返回一系列数据最后在页面中显示出来

(4)效果如下:

以上所述是小编给大家介绍的SpringMVC环境下实现的Ajax异步请求JSON格式数据的相关内容,希望对大家有所帮助!


  • 上一条:
    通过构造AJAX参数实现表单元素JSON相互转换
    下一条:
    微信小程序bindtap事件与冒泡阻止详解
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 2023年9月1日起:微信小程序必须备案才能上线运营(0个评论)
    • 腾讯官方客服回应了:微信好友上限约10000个!(0个评论)
    • 2023年做微信小程序的老铁注意:新增收费项、微信小程序获取手机号也收费了(0个评论)
    • 小程序开发之跳转微信直播示例api(0个评论)
    • 在uni_app中开发小程序之常用功能示例代码汇总(0个评论)
    • 近期文章
    • Laravel 11版本抢先看,看将有什么新功能发布(0个评论)
    • goose数据库迁移工具介绍及使用流程步骤(0个评论)
    • 中国程序员“翻墙”为海外软件公司打工,105.8万工资被罚没!转知乎(0个评论)
    • 在go语言gin框架中使用Sharding(Gorm分表中间件)实现分表流程步骤(0个评论)
    • 在PHP提高性能方式之开启OPCache扩展及OPCache配置参数详解(0个评论)
    • 在js的websocket客户端开发中遇到代码割裂情况解决方案(0个评论)
    • Laravel框架中适用于Eloquent的日期过滤软件包:lara-date-filter(0个评论)
    • Laravel 10.24版本发布(0个评论)
    • go语言多项目批量更新依赖及自动调用jenkins构建流程步骤(0个评论)
    • 在go语言中实现数学pow(x^y 的幂次)代码示例(0个评论)
    • 近期评论
    • 路人 在

      php中使用hyperf框架调用讯飞星火大模型实现国内版chatgpt功能示例中评论 教程很详细,如果加个前端chatgpt对话页面就完美了..
    • 博主 在

      科学上网翻墙之v2rayN-Core客户端免费公益节点使用教程中评论 @ mashrdn 多切换几个节点测试,免费ssr是没那么稳..
    • mashrdn 在

      科学上网翻墙之v2rayN-Core客户端免费公益节点使用教程中评论 V2rayn免费节点添加上去了,youtobe无法打开网页,是怎么回事..
    • 张伟 在

      科学上网翻墙之v2rayN-Core客户端免费公益节点使用教程中评论 3q!有用,不过免费节点隔天就要去git上复制新的导进去..
    • 博主 在

      科学上网翻墙访问Google , 上外网神器佛跳墙VPN(永久免费)使用流程步骤中评论 该篇教程已不能用了,告知大家,免的老有老铁问我!..
    • 2016-10
    • 2017-10
    • 2018-01
    • 2020-03
    • 2021-06
    • 2021-10
    • 2022-03
    • 2023-02
    • 2023-06
    • 2023-07
    • 2023-08
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客