spring mvc 与前端ajax通信

  1. 解决ajax跨域操作
  2. ajax与spring通信中,json字符串和js对象及java对象之间的转化。


前端和后端分离是一种趋势,但前端和后端的通信,其实大多由ajax来承担。


spring mvc 中,由ajax 传递来的json字符串,在本文中用的是spring mvc的注解:@RequestBody来解析成java对象。

spring中返回的对象,自动传递给前端json字符串的操作,我们用spring web的配置:

<mvc:annotation-driven>
    <mvc:message-converters>
    	<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter" />
    </mvc:message-converters>
 </mvc:annotation-driven>

这里,我们选择了
FastJsonHttpMessageConverter
来使得我们的对象自动转换为json字符串,并返回到前端。


在本例子中,我用maven 的jetty插件运行一个web 服务,用web storm 写了一个简单的html5页面。

由于ajax跨域操作的原因,虽然web请求返回200,但是,前端始终不能正确执行,所以,我在spring mvc那层解决跨域操作,在web.xml配置一个过滤器:

<filter>
		<filter-name>CORS</filter-name>
		<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>CORS</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

,这个过滤器就解决了ajax跨域操作。

记得添加maven依赖:

<dependency>
			<groupId>com.thetransactioncompany</groupId>
			<artifactId>cors-filter</artifactId>
			<version>2.4</version>
		</dependency>


spring mvc 那层写了一个简单controller测试:


@Controller
public class SImpleController {

	@RequestMapping("/getAString.do")
	@ResponseBody
	public ModelResult<String> getAString() {

		ModelResult<String> modelResult = new ModelResult<>();
		modelResult.setModel("hello doctor");
		return modelResult;
	}

	@RequestMapping("/update.do")
	@ResponseBody
	public ModelResult<UserInfo> updateUserInfo(@RequestBody UserInfo userInfo) {
		ModelResult<UserInfo> modelResult = new ModelResult<>();
		userInfo.setName("hello doctor");
		userInfo.setPasswd("1235678");
		userInfo.setSex("man");
		modelResult.setModel(userInfo);
		return modelResult;
	}

	 

}

html5,ajax请求代码:

function getString(){

    $.ajax({
        url:"http://localhost:8080/getAString.do",
        type:"POST",
        dataType:'json',
        success: function( data ) {
            if(data.success == true) {
                $(".divget").html("<strong>" + data.model + "</strong>  ");

            }else{
                var errorInfo = data.error;
                var str = "";
                for(var p in errorInfo){
                    str += p +":" + errorInfo[p];
                }
                $( ".divget" ).html( "<strong>" + str + "</strong>  " );

            }

        },

    });
}


function update(){
    var info ={
        name:"",
        passwd:"",
        sex:""
    };

    $.ajax({
        url:"http://localhost:8080/update.do",
        type:"POST",
        dataType:'json',
        contentType:"application/json",
        data:JSON.stringify(info),
        success: function( data ) {
            if(data.success == true) {
                $(".update").html("<strong>" + JSON.stringify(data.model) + "</strong>  ");

            }else{
                var errorInfo = data.error;
                var str = "";
                for(var p in errorInfo){
                    str += p +":" + errorInfo[p];
                }
                $( ".update" ).html( "<strong>" + str + "</strong>  " );

            }

        }
    });
}

dataType:'json',
代表返回的内容格式。


contentType:"application/json",
data:JSON.stringify(info),
这个两行代表我们请求数据的格式是json字符串。js对象转json字符串的操作也有函数执行。

代码运行结果:

代码:https://github.com/sdcuike/springmvc-ajax

今天中秋,写的粗略了点,前端也没怎么接触过。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Dreamer who

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值