springmvc java中转发_SpringMVC框架如何实现请求转发和重定向呢?

2a2edeb3b58e761ecf81068070241f5c.png

SpringMVC中Json数据开发的方式添加 json 依赖 jar 包

修改 servlet-context.xml,添加 json 转换器配置

使用注解进行数据绑定@RequestBody @ResponseBody

案例实操

1.添加 json 依赖 jar 包

com.fasterxml.jackson.core

jackson-core

2.7.0

com.fasterxml.jackson.core

jackson-databind

2.7.0

com.fasterxml.jackson.core

jackson-annotations

2.7.0

2.修改 servlet-context.xml

添加 json 转换器配置

class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">

或者

class="org.springframework.http.converter.StringHttpMessageConverter" />

class="org.springframework.http.converter.json.MappingJackson2HttpMessageConver

ter" />

3.Json 数据绑定的支持

@Controller

@RequestMapping("/user")

public class UserLoginController {

@RequestMapping("/addUser")

@ResponseBody

public User addUser(@RequestBody User user){

System.out.println(user);

return user;

}

@RequestMapping("/getUser")

@ResponseBody

public User getUser(User user){

System.out.println(user);

return user;

}

}

Jsp 页面定义

String path = request.getContextPath();

String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

My JSP 'test.jsp' starting page

function test1(){

$.ajax({

type:"post",

url:"user/addUser.do",

dataType:"json",

contentType:"application/json;charset=utf-8",

data:'{"userName":"xxx","userPwd":"123456"}',

success:function(data){

alert(data.userName+"--"+data.userPwd);

}

})

}

function test2(){

$.ajax({

type:"post",

url:"user/getUser.do",

data:"userName=xxx&userPwd=123456",

dataType:"json",

success:function(data){

alert(data.userName+"--"+data.userPwd);

}

})

}

扩展

@ResponseBody

该注解用于将 Controller 的方法返回的对象,通过适当的 HttpMessageConverter转换为指定格式后,写入到 Response 对象的 body 数据区。

返回的数据不是 html 标签的页面,而是其他某种格式的数据时(如 json、xml 等) 使用(通常用于 ajax 请求)

@RequestBody

该注解用于读取 Request 请求的 body 部分数据,使用系统默认配置的 HttpMessageConverter 进行解析,然后把相应的数据绑定到要返回的对象上 ,再把 HttpMessageConverter 返回的对象数据绑定到 controller 中方法的参数上

Json 数据使用好处

Json 在企业开发中已经作为通用的接口参数类型,在页面(客户端)解析很方便。

SpringMvc 对于 json 提供了良好的支持,这里需要修改相关配置,添加 json 数据支持功能

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值