中易网

spring mvc restful请求对象request不通过controller如何得到

答案:2  悬赏:30  
解决时间 2021-02-16 17:19
spring mvc restful请求对象request不通过controller如何得到
最佳答案
p=415 在controller类中,获得request 或是 session 对象,在网上查了下,没看到比较清晰的示例,贴段代码在下面: package net.ly.controllers; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletReques...
全部回答
spring mvc本身对restful支持非常好。它的@requestmapping、@requestparam、@pathvariable、@responsebody注解很好的支持了rest。18.2 creating restful services 1. @requestmapping spring uses the @requestmapping method annotation to define the uri template for the request. 类似于struts的action-mapping。 可以指定post或者get。 2. @pathvariable the @pathvariable method parameter annotation is used to indicate that a method parameter should be bound to the value of a uri template variable. 用于抽取url中的信息作为参数。(注意,不包括请求字符串,那是@requestparam做的事情。) @requestmapping("/owners/{ownerid}", method=requestmethod.get) public string findowner(@pathvariable string ownerid, model model) { // ... } 如果变量名与pathvariable名不一致,那么需要指定: @requestmapping("/owners/{ownerid}", method=requestmethod.get) public string findowner(@pathvariable("ownerid") string theowner, model model) { // implementation omitted } tip method parameters that are decorated with the @pathvariable annotation can be of any simple type such as int, long, date... spring automatically converts to the appropriate type and throws a typemismatchexception if the type is not correct. 3. @requestparam 官方文档居然没有对这个注解进行说明,估计是遗漏了(真不应该啊)。这个注解跟@pathvariable功能差不多,只是参数值的来源不一样而已。它的取值来源是请求参数(querystring或者post表单字段)。 对了,因为它的来源可以是post字段,所以它支持更丰富和复杂的类型信息。比如文件对象: @requestmapping("/imageupload") public string processimageupload(@requestparam("name") string name, @requestparam("description") string description, @requestparam("image") multipartfile image) throws ioexception { this.imagedatabase.storeimage(name, image.getinputstream(), (int) image.getsize(), description); return "redirect:imagelist"; } 还可以设置defaultvalue: @requestmapping("/imageupload") public string processimageupload(@requestparam(value="name", defaultvalue="arganzheng") string name, @requestparam("description") string description, @requestparam("image") multipartfile image) throws ioexception { this.imagedatabase.storeimage(name, image.getinputstream(), (int) image.getsize(), description); return "redirect:imagelist"; } 4. @requestbody和@responsebody 这两个注解其实用到了spring的一个非常灵活的设计——httpmessageconverter 18.3.2 http message conversion 与@requestparam不同,@requestbody和@responsebody是针对整个http请求或者返回消息的。前者只是针对http请求消息中的一个 name=value 键值对(名称很贴切)。 htppmessageconverter负责将http请求消息(http request message)转化为对象,或者将对象转化为http响应体(http response body)。 public interface httpmessageconverter { // indicate whether the given class is supported by this converter. boolean supports(class clazz); // return the list of mediatype objects supported by this converter. list getsupportedmediatypes(); // read an object of the given type form the given input message, and returns it. t read(class clazz, httpinputmessage inputmessage) throws ioexception, httpmessagenotreadableexception; // write an given object to the given output message. void write(t t, httpoutputmessage outputmessage) throws ioexception, httpmessagenotwritableexception; } spring mvc对httpmessageconverter有多种默认实现,基本上不需要自己再自定义httpmessageconverter stringhttpmessageconverter - converts strings formhttpmessageconverter - converts form data to/from a multivaluemap bytearraymessageconverter - converts byte arrays sourcehttpmessageconverter - convert to/from a javax.xml.transform.source rsschannelhttpmessageconverter - convert to/from rss feeds mappingjacksonhttpmessageconverter - convert to/from json using jackson's objectmapper etc... 然而对于restful应用,用的最多的当然是mappingjacksonhttpmessageconverter。 但是mappingjacksonhttpmessageconverter不是默认的httpmessageconverter: public class annotationmethodhandleradapter extends webcontentgenerator implements handleradapter, ordered, beanfactoryaware { ... public annotationmethodhandleradapter() { // no restriction of http methods by default super(false); // see spr-7316 stringhttpmessageconverter stringhttpmessageconverter = new stringhttpmessageconverter(); stringhttpmessageconverter.setwriteacceptcharset(false); this.messageconverters = new httpmessageconverter[]{new bytearrayhttpmessageconverter(), stringhttpmessageconverter, new sourcehttpmessageconverter(), new xmlawareformhttpmessageconverter()}; } } 如上:默认的httpmessageconverter是bytearrayhttpmessageconverter、stringhttpmessageconverter、sourcehttpmessageconverter和xmlawareformhttpmessageconverter转换器。所以需要配置一下: text/plain;charset=gbk 配置好了之后,就可以享受@requestbody和@responsebody对jons转换的便利之处了: @requestmapping(value = "api", method = requestmethod.post) @responsebody public boolean addapi(@requestbody api api, @requestparam(value = "afterapiid", required = false) integer afterapiid) { integer id = apimetadataservice.addapi(api); return id > 0; } @requestmapping(value = "api/{apiid}", method = requestmethod.get) @responsebody public api getapi(@pathvariable("apiid") int apiid) { return apimetadataservice.getapi(apiid, version.primary); } 一般情况下我们是不需要自定义httpmessageconverter,不过对于restful应用,有时候我们需要返回jsonp数据: package me.arganzheng.study.springmvc.util; import java.io.ioexception; import java.io.printstream; import org.codehaus.jackson.map.objectmapper; import org.codehaus.jackson.map.annotate.jsonserialize.inclusion; import org.springframework.http.httpoutputmessage; import org.springframework.http.converter.httpmessagenotwritableexception; import org.springframework.http.converter.json.mappingjacksonhttpmessageconverter; import org.springframework.web.context.request.requestattributes; import org.springframework.web.context.request.requestcontextholder; import org.springframework.web.context.request.servletrequestattributes; public class mappingjsonphttpmessageconverter extends mappingjacksonhttpmessageconverter { public mappingjsonphttpmessageconverter() { objectmapper objectmapper = new objectmapper(); objectmapper.setserializationconfig(objectmapper.getserializationconfig().withserializationinclusion(inclusion.non_null)); setobjectmapper(objectmapper); } @override protected void writeinternal(object o, httpoutputmessage outputmessage) throws ioexception, httpmessagenotwritableexception { string jsonpcallback = null; requestattributes reqattrs = requestcontextholder.currentrequestattributes(); if(reqattrs instanceof servletrequestattributes){ jsonpcallback = ((servletrequestattributes)reqattrs).getrequest().getparameter("jsonpcallback"); } if(jsonpcallback != null){ new printstream(outputmessage.getbody()).print(jsonpcallback + "("); } super.writeinternal(o, outputmessage); if(jsonpcallback != null){ new printstream(outputmessage.getbody()).println(");"); } } }
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
我朋友饭了销毁会计凭证罪,行贿罪,咋骗罪,
7天营养加油站翠明草本营养咨询中心在什么地
2007年10月小英把1200元压岁钱存入银行,存期
在易学算命中12月初5的子时出生的人应该算初
西三合村怎么去啊,有知道地址的么
excel 表格一个单元格输入大段文字显示不出来
附近哪里有修洗衣机的
海利不锈钢管·板(流泗镇中心卫生院东北)在哪
升安大街/广善大街(路口)地址有知道的么?有
用保妇康栓三个疗程,期间可以同房吗?
重庆小面之梦小面(崧厦店)地址在哪,我要去那
苹果4s,联通卡3gnet网络怎么设置。
我在北京昌平有一电动车想托运回老家河南项城
疯兔盒子是用散装进口零食做成的盒子。想模仿
哈尔滨银行ATM(学府支行)地址在哪,我要去那
推荐资讯
武城县人民法院老城人民法庭我想知道这个在什
中石化人民东路加油站(人民东路与黄山路交叉
Windows7什么时候停产?听说OEM厂商Win7停产
男朋友睡觉为什么喜欢夹着我腿睡觉
五菱提车员工作是真的假的。有在五菱工作的朋
win7家庭版 想把系统升级到service pack 1,
我是1984年9月23日(阴历)早晨5点多出生的,
万千美容美体地址在什么地方,想过去办事
盆栽植物浇水你真的会吗
对面阳台镜子对着我家卧室,求破解
NBA2KOnline哪个球队好
现在流行什么样的面膜呢
手机登qq时,显示手机磁盘不足,清理后重新登
刺客的套装怎么选啊?