@getrequestbodyy request.getinputstream为什么不能同时使用

Have a Java spring MVC web app, and am making a jquery ajax post request. My Controller is setup to receive and send json data. Everything works, the JSON string is well formatted, and the Controller can create and populate a Command object and populate it with the contents of the JSON request data. However, I am updating data for a Contact object, and my JSP form element only contains a subset of all the data required for the DB update. In my initial GET request for the JSP page with the form I retrieve all the necessary data from the DB, populate a Contact Command object, and then bind that command object to the Model.
If I were doing a normal POST submit form submission, I believe that just declaring my command object as @SessionAttribute, and referencing that Command object using @ModelAttribute in my onSubmit() POST method would be sufficient. Spring would retrieve the already populated command object from my session and then bind (overwrite) those values that have changed as a result of the POST request. This updated command object could then be used as the parameter for a DB update.
However, I am using Spring 3 and leveraging @RequestBody paramater type. I cannot get Spring to both give me the session object and automatically bind the new values from the request. It either gives me just the old session command object (without applying the changes) or a new Command Object with only the values from the POST request.
Here is a little code - doesn't work:
@SessionAttributes("contactCommand")
@Controller
public class ContactController {
@RequestMapping(value = "/editContact", method=RequestMethod.GET)
public String init(ModelMap model, Locale locale, HttpServletRequest request, HttpServletResponse response) throws GeneralException {
final ContactCommand cmd = new ContactCommand();
// populate with data from DB etc
model.addAttribute("contactCommand", cmd);
@RequestMapping(value="/editContact",method=RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody Map&String, ? extends Object& editContactInfo(@RequestBody @ModelAttribute("contactCommand") ContactCommand cmd, HttpServletRequest request, HttpServletResponse response) throws GeneralException {
// do business logic with command object here
Can anyone please tell me what is the "standard" or "easiest" way to use @RequestBody with JSON request data and make that bind to an existing / @ModelAttribute populated Command object so that the Command object fully constituted with both old and new data (in the same way it is easily achieved using a full POST http submit).
A related question is what is wrong with the code above? Can @SessionAttribute and @RequestBody with JSON content all be used together? If so, please explain how! Thank you so much for any input.
My work around is to let Spring create the new Command object and auto-populate with form data. Then make a separate call / retrieve manually from session the old command object, finally manually copy all those attributes that were not present in the form submission into the new command object. Now I have all the necessary data together in one command object to apply my SQL update with. There must be an easier way.... ;)
Found this SOF post today while further researching this problem:
It appears there is no known SPRING solution out of the box but a lot of demand to know the best way to handle it. In my case, yes, I am using nested domain objects so the workaround offered in the post is no good. Does anyone have any other ideas? To be clear, I wish to POST JSON format data to the Controller (not simply http form post data).
Ok, I've opened a Spring Source JIRA request for this one, perhaps it is a much needed improvement:
Or else, it is a case of leveraging the Jackson conversion capabilities in clever ways which sounds like a lot of plumbing.
解决方案 This isn't a complete answer, but I hope it will point you in the right direction.
Following is a class that we use to do deep binding from JSON to an existing object using Jackson. This is adapted from a bug report for Jackson here:
public class JsonBinder
private ObjectMapper objectM
public JsonBinder( ObjectMapper objectMapper )
this.objectMapper = checkNotNull( objectMapper );
public void bind( Object objToBindInto, InputStream jsonStream ) throws JsonProcessingException, IOException
JsonNode root = objectMapper.readTree( checkNotNull( jsonStream ) );
applyRecursively( checkNotNull( objToBindInto ), root );
private void applyRecursively( Object objToBindInto, JsonNode node ) throws JsonProcessingException, IOException
PropertyAccessor propAccessor =
for( Iterator&Entry&String, JsonNode&& i = node.fields(); i.hasNext(); )
Entry&String, JsonNode& fieldEntry = i.next();
JsonNode child = fieldEntry.getValue();
if( child.isArray() )
// We ignore arrays so they get instantiated fresh every time
// root.remove(fieldEntry.getKey());
if( child.isObject() )
if( propAccessor == null )
propAccessor = PropertyAccessorFactory.forDirectFieldAccess( objToBindInto );
Object o2 = propAccessor.getPropertyValue( fieldEntry.getKey() );
if( o2 != null )
// Only remove the JsonNode if the object already exists
// Otherwise it will be instantiated when the parent gets
// deserialized
i.remove();
applyRecursively( o2, child );
ObjectReader jsonReader = objectMapper.readerForUpdating( objToBindInto );
jsonReader.readValue( node );
We use this along with a an implementation of Spring's HandlerMethodArgumentResolver.
We don't use a lot of Spring's MVC framework. We are just building a JSON API backend using a lot of different parts of Spring. It is a pretty good amount of plumbing to get it all working, but now our controllers are very simple.
Unfortunately I can't show all of our code, it's pretty long anyways. I hope this solves at least part of the problem.
本文地址: &
有一个Java Spring MVC的Web应用程序,和我做一个jQuery的ajax post请求。我的控制器是设置接收和发送JSON数据。一切正常,JSON字符串是格式正确,控制器可以创建并填充Command对象和JSON的请求数据的内容来填充它。不过,我更新数据的联系对象,而我的JSP表单元素只包含了所有必需的DB更新数据的一个子集。在与我取得所有必要的数据从数据库表单JSP页面我最初的GET请求,填充联系Command对象,然后该命令对象绑定到模型。
如果我在做一个正常的POST提交表单提交,我相信只是说出我的命令对象作为@SessionAttribute,并引用在我的onsubmit()POST方法使用@ModelAttribute Command对象就足够了。春天将从我的会议中检索已填充命令对象,然后绑定(覆盖)已更改为POST请求的结果,这些值。这个更新命令对象可随后被用作一个DB更新的参数
不过,我使用Spring 3和利用@RequestBody paramater类型。我不能让春天到两个给我的会话对象并自动从请求绑定新值。它要么给我只是旧的会话命令对象(不应用更改),或一个新的命令对象,只有在POST请求的值。
下面是一个小code
- 不工作:
@SessionAttributes(“contactCommand”)
@Controller
公共类ContactController中{
@RequestMapping(值=“/ editContact”,方法= RequestMethod.GET)
公共字符串初始化(ModelMap模式,区域设置区域,HttpServletRequest的请求,HttpServletResponse的响应)抛出GeneralException {
最后ContactCommand CMD =新ContactCommand();
//从数据库等数据填充
model.addAttribute(“contactCommand”,CMD);
@RequestMapping(值=“/ editContact”,方法= RequestMethod.POST,消耗=“应用/ JSON”,产生=“应用/ JSON”)
公共@ResponseBody地图<字符串?扩展对象& editContactInfo(@RequestBody @ModelAttribute(“contactCommand”)ContactCommand CMD,HttpServletRequest的请求,HttpServletResponse的响应)抛出GeneralException {
//业务逻辑和命令对象在这里
谁能告诉我什么是“标准”或“最简单”的方式来使用@RequestBody使用JSON请求数据,并做出绑定到现有/ @ModelAttribute填充命令对象,以使Command对象与老完全组成和新的数据(以同样的方式很容易使用完整POST HTTP提交实现)。
一个相关的问题是,什么是错的code以上?可以@SessionAttribute和@RequestBody使用JSON内容都可以同时使用?如果是的话,请解释!非常感谢你对任何输入。
我的解决办法是让Spring创建新的命令对象,并自动填充表单数据。然后,让一个独立的呼叫/会话,从手工检索旧的命令对象,最后手动复制所有这些属性没有present的形式提交到新的命令对象。现在,我拥有所有必要的数据集中到一个命令对象申请我的SQL更新使用。必须有一个更简单的方法......;)
今天发现这个SOF岗位的同时,进一步研究这个问题:
这似乎没有任何已知的弹簧解决方案开箱即用,但大量的需求要知道处理它的最佳方式。就我而言,是的,我使用嵌套的域对象,以便在后提出的解决办法是不行的。没有人有任何其他的想法?需要明确的是,我想张贴JSON格式的数据控制器(不是简单的HTTP表单提交的数据)。
好吧,我已经开了春源JIRA要求为这一个,也许这是一个急需改进:
否则,它是利用在巧妙的方法杰克逊转换能力,这听起来像很多水管的情况。
解决方案 这是不是一个完整的答案,但我希望它会为你指明正确的方向。
以下是我们用来做深,从JSON结合使用杰克逊现有的对象的类。这是改编自一个bug报告,杰克逊在这里:
公共类JsonBinder
私人ObjectMapper objectM
公共JsonBinder(ObjectMapper objectMapper)
this.objectMapper = checkNotNull(objectMapper);
公共无效绑定(对象objToBindInto,InputStream的jsonStream)抛出JsonProcessingException,IOException异常
JsonNode根= objectMapper.readTree(checkNotNull(jsonStream));
applyRecursively(checkNotNull(objToBindInto),根);
私人无效applyRecursively(对象objToBindInto,JsonNode节点)抛出JsonProcessingException,IOException异常
PropertyAccessor接口propAccessor = NULL;
对(迭代器<进入<字符串,JsonNode>> I = node.fields(); i.hasNext();)
进入<字符串,JsonNode> fieldEntry = i.next();
JsonNode孩子= fieldEntry.getValue();
如果(child.isArray())
//我们忽略阵列,以便他们获得每次实例新鲜
// root.remove(fieldEntry.getKey());
如果(child.isObject())
如果(propAccessor == NULL)
propAccessor = PropertyAccessorFactory.forDirectFieldAccess(objToBindInto);
对象O2 = propAccessor.getPropertyValue(fieldEntry.getKey());
如果(O2!= NULL)
//只有当对象已经存在删除JsonNode
//否则会当父母得到被实例化
//反序列化
i.remove();
applyRecursively(O2,子女);
ObjectReader jsonReader = objectMapper.readerForUpdating(objToBindInto);
jsonReader.readValue(节点);
我们用这个伴随着春天的HandlerMethodArgumentResolver的一个实现。
我们不使用大量的Spring的MVC框架。我们只是建设使用了大量春天的不同部分的JSON API后端。这是管道的pretty的量好把一切的工作,但现在我们的控制器是很简单的。
不幸的是,我不能表现出我们所有的code,这是pretty的长期反正。我希望这至少解决了部分问题。
本文地址: &
扫一扫关注官方微信  最近准备在原有的SSM项目的基础上添加完善的日志分析,由于是APP的后台系统,之前在规划APP的时候,并没有在APP上做埋点的处理,而如果想要进行埋点处理的话,对于未能新升级的APP用户来说,就是去了意义,因为只要用户不升级,埋点就不能在他的APP中运行。所以,就考虑到了在后台的入口增加日志的监控。
  想法总是简单,但是在实际实现的过程中却还是遇到了问题。由于APP基本都采用公参的加密校验,然后采用POST请求传递JSON数据。对于一般的请求分析,比如每个时间段的访问量,或者每个方法每个某块的统计都简单,只要在拦截器中新增一个将数据扔到消息队列中,然后在消费端在进行日志的分析和处理即可。然后如果要针对每个用户在什么时间段,做了什么处理,问题就来了,因为这个时候就必须拿到post中的json参数。
  有些同学就说,这不是很简单么,直接request.getParameter()不就可以了吗?NO,post的json数据是通过流的方式传递的,并不可以直接读取。OK,那我们用request.getReader()拿到流然后转成字符串不就可以了么?那么问题来了,流是只能流一遍的,一旦读过了就不会再有了,具体的方法中就拿不到了。说到这里,其实访问根本就不会再进到方法体了,因为springmvc的DispatcherServlet就会抛出异常& getReader() has already been called for。。。。。。
  说了这么多,下面是重点啦,其实很简单,就是在过滤器处理request(如果没有过滤器,那就新增一个即可)
  实现方法:先将RequestBody保存为一个byte数组,然后通过Servlet自带的HttpServletRequestWrapper类覆盖getReader()和getInputStream()方法,使流从保存的byte数组读取。然后再Filter中将ServletRequest替换为ServletRequestWrapper。代码如下:
BodyReaderHttpServletRequestWrapper类包装ServletRequest,将流保存为byte[],然后将getReader()和getInputStream()方法的流的读取指向byte[]
import java.io.IOE
import javax.servlet.F
import javax.servlet.FilterC
import javax.servlet.FilterC
import javax.servlet.ServletE
import javax.servlet.ServletR
import javax.servlet.ServletR
import javax.servlet.http.HttpServletR
public class AuthFilter implements Filter{
public void destroy() {
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
ServletRequest requestWrapper = null;
if(request instanceof HttpServletRequest) {
requestWrapper = new BodyReaderHttpServletRequestWrapper((HttpServletRequest) request);
if(null == requestWrapper) {
chain.doFilter(request, response);
chain.doFilter(requestWrapper, response);
* 初始化函数时,需要获取排除在外的url
public void init(FilterConfig config) throws ServletException {
1 import java.io.BufferedR
2 import java.io.ByteArrayInputS
3 import java.io.IOE
4 import java.io.InputStreamR
6 import javax.servlet.ServletInputS
7 import javax.servlet.http.HttpServletR
8 import javax.servlet.http.HttpServletRequestW
<span style="color: # import jodd.JoddD
<span style="color: # import jodd.io.StreamU
<span style="color: #
<span style="color: # public class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper {
<span style="color: #
<span style="color: #
private final byte[]
<span style="color: #
<span style="color: #
public BodyReaderHttpServletRequestWrapper(HttpServletRequest request)throws IOException {
<span style="color: #
super(request);
<span style="color: #
body = StreamUtil.readBytes(request.getReader(), JoddDefault.encoding);
<span style="color: #
<span style="color: #
<span style="color: #
<span style="color: #
public BufferedReader getReader() throws IOException {
<span style="color: #
return new BufferedReader(new InputStreamReader(getInputStream()));
<span style="color: #
<span style="color: #
<span style="color: #
<span style="color: #
public ServletInputStream getInputStream() throws IOException {
<span style="color: #
final ByteArrayInputStream bais = new ByteArrayInputStream(body);
<span style="color: #
return new ServletInputStream() {
<span style="color: #
<span style="color: #
<span style="color: #
public int read() throws IOException {
<span style="color: #
return bais.read();
<span style="color: #
<span style="color: #
<span style="color: #
<span style="color: # }
阅读(...) 评论()安全检查中...
请打开浏览器的javascript,然后刷新浏览器
< 浏览器安全检查中...
还剩 5 秒&1401人阅读
@RequestBody
只能与@RequestHeader同用
不能与@RequestParam (实现迭代函数部分方法只调用一次,之后传递下去)
实现迭代函数部分方法只调用一次,之后传递下去,需要传递一些@controller前台没有的参数,又要保证前台(jsp)能调用这个方法,用required=false,@RequestBody传递list,@RequestHeader弥补无法同时
使用@RequestParam
@RequestBody
只能与@RequestHeader同用
不能与@RequestParam 同用 如果有
@RequestParam配合模型驱动使用
@RequestBody 配合@RequestHeader使用,用于传递流(图片,list等),流的优先级高于普通的属性(@RequestParam),流拿了之后马山就关闭reuqest,所以@RequestParam无法取到传过来的值
@RequestHeader就用来弥补用流的时候不能用@RequestParam 的情况
注意@RequestBody(required=false)属性
所有取值的本质request.getparamnter("");只是用了@之类的标签帮你拿出来而已
http://blog.csdn.net/kobejayandy/article/details/
.cn/s/blog_46debefc0101192j.html
/chenxizhang/archive//1675259.html
ajax中设置header的方式
beforeSend: function(xhr){
xhr.setRequestHeader('id', id);
xhr.setRequestHeader('leave', leave);
xhr.setRequestHeader('roleId', roleId);
xhr.setRequestHeader('pId', pId);
function appendTable() {
var roleId=$("input[name='roleId']").val();
var leave=$("input[name='leave']").val();
var pId=$("input[name='pId']").val();
var id=$("input[name='id']").val();
var dataParent = {
roleId: "1",
leave:"2",
type: "post",
url: "${pageContext.request.contextPath}/system/opmRole/Auths",
//data: dataParent,
// headers:"{\"id\": \"1\",\"leave\":\"2\",\"roleId\":\"3\",\"pId\":\"5\"}",
beforeSend: function(xhr){
xhr.setRequestHeader('id', id);
xhr.setRequestHeader('leave', leave);
xhr.setRequestHeader('roleId', roleId);
xhr.setRequestHeader('pId', pId);
xhr.setRequestHeader('fg', "1");
//dataType: 'json',
//contentType: "application/json",
success: function (data) {
if(data!=''&&data!=null){
var div1=$("#div1");
var table1=$("&table&&/table&");
var arr = eval(data);
for(j=0;j&arr.j++){
if(arr[j].leave=='1'){
var row =$("&tr&&/tr&");
var td =$("&td&&/td&");
td.append($(arr[j].str));
row.append(td);
table1.append(row);
var row2 ;
if(arr[j].leave=='2'){
row2 =$("&tr&&/tr&");
var td =$("&td&&/td&");
td.append(arr[j].str);
row2.append(td);
table1.append(row2);
}if(arr[j].leave=='3'){
var td =$("&td&&/td&");
td.append(arr[j].str);
table1.find("tr:last").append(td);
div1.html(table1);
alert("你输入的会员编号不存在!");
error:function(data){
alert("数据加载异常!");
@SuppressWarnings("rawtypes")
@RequestMapping(value="/system/opmRole/Auths")
@ResponseBody
public JSONArray treeRead(@RequestHeader(value="fg") String fg,@RequestHeader(value="id") String id,@RequestHeader(value="leave") String leave,@RequestHeader(value="roleId") String roleId,@RequestHeader(value="pId")
String pId,@RequestHeader(value="groupId",required=false)
String groupId1,@RequestBody(required=false) List&OpmRolelimit& o){
List&String& strl= new ArrayList&String&();
String str="";
JSONArray JsonArray = new JSONArray();
Map&String,Object& param = new HashMap&String,Object&();
param.put("pId", pId);
List&Map& map= opmMenufolderService.getfordMenuLimt(param);
if("1".equals(fg)&&id!=null&&!"".equals(id)){//迭代中只查一次,之后传入
//查询角色权限表
System.out.println("==========查询角色权限表=======");
OpmRolelimit oo =new OpmRolelimit();
oo.setRoleid(id);
o=opmRolelimitService.getRoleLimt(oo);
Map&String,Object& param1 = new HashMap&String,Object&();
String groupId=groupId1;
for(Map p: map){
param1.put("pId", p.get("ID"));
String l= (String) p.get("LEAVE");
if("1".equals(l)){
if("100000".equals(p.get("PARENTID")+"")){
groupId=(String)p.get("ID");
str+="&label style=\"float:left\"&&input type=\"checkbox\" class=\"checkboxCtrl\" value="+p.get("ID")+" group="+groupId+" selectType=\"invert\" /&"+p.get("NAME")+"&/label&"+"\n";
strl.add(str);
JSONObject Json = new JSONObject();
Json.put("ID", p.get("ID")+"");
Json.put("NAME", p.get("NAME")+"");
Json.put("groupId", groupId);
Json.put("parentId", p.get("PARENTID"));
Json.put("leave", l);
Json.put("str", "&label style=\"float:width:150\"&&input type=\"checkbox\" class=\"checkboxCtrl\" value="+p.get("ID")+"
onclick=\"checkedAllBox(this);\" group="+groupId+" //&"+p.get("NAME")+"&/label&"+"\n");
JsonArray.add(Json);
str+="&label&&input type=\"checkbox\" value="+p.get("ID")+" name="+groupId+"/&"+p.get("NAME")+"&/label&"+"\n";
strl.add(str);
JSONObject Json = new JSONObject();
Json.put("ID", p.get("ID")+"");
Json.put("NAME", p.get("NAME")+"");
Json.put("groupId",groupId);
Json.put("parentId", p.get("PARENTID"));
Json.put("leave", l);
Json.put("str","&label style=\"width:150\"&&&&"+p.get("NAME")+"&/label&"+"\n");
JsonArray.add(Json);
if("2".equals(l)){
if(Integer.valueOf(leave)&0){
if(Integer.valueOf(p.get("LEAVE1")+"") &=Integer.valueOf(leave)){
str+="&label&&input type=\"checkbox\" value="+p.get("ID")+"
name="+groupId+"/&"+p.get("NAME")+"&/label&"+"\n";
strl.add(str);
JSONObject Json = new JSONObject();
Json.put("ID", p.get("ID")+"");
Json.put("NAME", p.get("NAME")+"");
Json.put("groupId", groupId);
Json.put("parentId", p.get("PARENTID"));
Json.put("leave", l);
String bs ="&label style=\"width:150\"&&&&&&&&input type=\"checkbox\" value="+p.get("ID")+"
name='"+groupId+"'/&"+p.get("NAME")+"&/label&"+"\n";
if(o!=null){
for(OpmRolelimit k : o){
if( (p.get("ID")+"").equals(k.getMenuitemid())){
bs ="&label style=\"width:150\"&&&&&&&&input type=\"checkbox\" value="+p.get("ID")+" checked=\"checked\"
name='"+groupId+"'/&"+p.get("NAME")+"&/label&"+"\n";
Json.put("str",bs);
JsonArray.add(Json);
Map&String,Object& param2 = new HashMap&String,Object&();
param2.put("menuItemId", p.get("ID"));
param2.put("menuItemLimitId", null);
param2.put("roleId", roleId);
param2.put("displayOrder", Integer.valueOf(-1));
List&OpmRolelimit& rl= opmRolelimitService.getRoleLimitByTJ(param2);
if(rl!=null&&rl.size()&0&&Integer.valueOf(p.get("LEAVE1")+"") &=Integer.valueOf(leave)){
str+="&label&&input type=\"checkbox\" value="+p.get("ID")+" name="+groupId+"/&"+p.get("NAME")+"&/label&"+"\n";
strl.add(str);
JSONObject Json = new JSONObject();
Json.put("ID", p.get("ID")+"");
Json.put("NAME", p.get("NAME")+"");
Json.put("groupId", groupId);
Json.put("parentId", p.get("PARENTID"));
Json.put("leave", l);
Json.put("str","&label style=\"width:150\"&&&&&&&&input type=\"checkbox\" value="+p.get("ID")+" name='"+groupId+"'/&"+p.get("NAME")+"&/label&"+"\n");
String bs ="&label style=\"width:150\"&&&&&&&&input type=\"checkbox\" value="+p.get("ID")+"
name='"+groupId+"'/&"+p.get("NAME")+"&/label&"+"\n";
if(o!=null){
for(OpmRolelimit k : o){
if( (p.get("ID")+"").equals(k.getMenuitemid())){
bs ="&label style=\"width:150\"&&&&&&&&input type=\"checkbox\" value="+p.get("ID")+" checked=\"checked\"
name='"+groupId+"'/&"+p.get("NAME")+"&/label&"+"\n";
Json.put("str",bs);
JsonArray.add(Json);
if("3".equals(l)){
Map&String,Object& param2 = new HashMap&String,Object&();
param2.put("menuItemId", p.get("PARENTID"));
param2.put("menuItemLimitId", p.get("ID"));
param2.put("roleId", roleId);//当前登录用户角色Id
param2.put("displayOrder", null);
List&OpmRolelimit& rl2= opmRolelimitService.getRoleLimitByTJ(param2);
String tempg=groupId;
if(rl2!=null&&rl2.size()&0){
str+="&label&&input type=\"checkbox\"
value="+p.get("ID")+" name="+groupId+"/&"+p.get("NAME")+"&/label&"+"\n";
strl.add(str);
JSONObject Json = new JSONObject();
Json.put("ID", p.get("ID")+"");
Json.put("NAME", p.get("NAME")+"");
Json.put("groupId", groupId);
Json.put("parentId", p.get("PARENTID"));
Json.put("leave", l);
Json.put("str","&label style=\"width:150\"&&input type=\"checkbox\"
value="+p.get("ID")+" name='"+groupId+"'/&"+p.get("NAME")+"&/label&"+"\n");
String bs ="&label style=\"width:150\"&&input type=\"checkbox\"
value="+p.get("ID")+" name='"+groupId+"'/&"+p.get("NAME")+"&/label&"+"\n";
if(o!=null){//权限树的反显
for(OpmRolelimit k : o){
if( (p.get("ID")+"").equals(k.getMenuitemlimitid())){
bs ="&label style=\"width:150\"&&input type=\"checkbox\"
value="+p.get("ID")+" checked=\"checked\" name='"+groupId+"'/&"+p.get("NAME")+"&/label&"+"\n";
Json.put("str",bs);
JsonArray.add(Json);
//str+=treeRead(leave,roleId,p.get("ID")+"",groupId);
JsonArray.addAll(treeRead(fg,id,leave,roleId,p.get("ID")+"",groupId,o));
return JsonA
==========================================================
@RequestBody
该注解常用来处理Content-Type: 不是application/x-www-form-urlencoded编码的内容,例如application/json, application/xml等;
它是通过使用HandlerAdapter 配置的HttpMessageConverters来解析post data body,然后绑定到相应的bean上的。
因为配置有FormHttpMessageConverter,所以也可以用来处理 application/x-www-form-urlencoded的内容,处理完的结果放在一个MultiValueMap&String, String&里,这种情况在某些特殊需求下使用,详情查看FormHttpMessageC
示例代码:
[java] view plaincopy
@RequestMapping(value = "/something", method = RequestMethod.PUT)
public void handle(@RequestBody String body, Writer writer) throws IOException {
writer.write(body);
@RequestParam
A) 常用来处理简单类型的绑定,通过Request.getParameter() 获取的String可直接转换为简单类型的情况( String--& 简单类型的转换操作由ConversionService配置的转换器来完成);因为使用request.getParameter()方式获取参数,所以可以处理get 方式中queryString的值,也可以处理post方式中 body data的值;
B)用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容,提交方式GET、POST;
C) 该注解有两个属性: value、required; value用来指定要传入值的id名称,required用来指示参数是否必须绑定;
示例代码:
@RequestHeader("userId") Long userId, @RequestBody CaseCommitBean caseCommitBean, 可以放在一起使用
但是@RequestParam不能和@RequestBody一起使用不能同时使用,如果是流的形式与(比如json) 只能读取一次,到时候就会发生 stream close 异常 。。。 所以采用一中方式
表面是 error/defaulterror 的 view ,但是内容的错误时
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-charset=UTF-8' not supported
因为 用Get 获得数据 没有问题,现在用的是post 出入json
.一直有问题,
找了好久才发现
function adduser(){
var url=".."+"/userses";
type: "POST",
async: false,
url:url +"/add",
dataType:"html",
contentType: "application/json",
data:JSON.stringify({
loginName:
'loginName',
'password',
success:function(data){
jsonstr = eval_r(data);
通过进入spring web 的调试也大概知道内部的东西了, spring 真不愧是很多内容想法集合到一起的容器。呵呵
你也能做到,以前猜测 hibernate 内部用的弱引用,刚才调试看到 spring mvc用到的也是。
@RequestMapping(value = "/add", method = RequestMethod.POST
@ResponseBody
public Map&String,String& addUsers(
//HttpEntity& User& user,
@RequestBody User user2
//@RequestParam(value = "loginName", required = true)String loginName,
//@RequestParam(value = "password", required = true)String password,
//@RequestParam(value = "userId", required = true)String userId,
//@RequestParam(value = "email", required = true)String email
userservice.getUserById(user2.getUserId());
Map&String,String& result = new HashMap&String,String&();
result.put("result", "true");
注释上面中的几种吧 request 内容 映射到的对应的哦 变量中,不能同时使用,如果是流的形式与(比如json) 只能读取一次,到时候就会发生 stream close 异常 。。。 所以采用一中方式
&&相关文章推荐
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:91549次
排名:千里之外
原创:483篇
(window.slotbydup = window.slotbydup || []).push({
id: '4740887',
container: s,
size: '250,250',
display: 'inlay-fix'

我要回帖

更多关于 requestbody get 的文章

 

随机推荐