如果您想了解request.getParameter()request.getAttribute()的知识,那么本篇文章将是您的不二之选。同时我们将深入剖析的各个方面,并给出实际的案例分析,希望能帮助
如果您想了解request.getParameter() request.getAttribute()的知识,那么本篇文章将是您的不二之选。同时我们将深入剖析<% String path = request.getContextPath(); String basePath = request.getScheme()+"://&quo...、@PathVariable,@RequestParam, @RequestBody,@ModelAttribute,@RequestHeader,@CookieValue的区别、@RequestParam、@RequestBody和@ModelAttribute区别、getContextPath、getServletPath、getRequestURI、getRealPath、getRequestURL、getPathInfo (); 的区别的各个方面,并给出实际的案例分析,希望能帮助到您!
本文目录一览:- request.getParameter() request.getAttribute()
- <% String path = request.getContextPath(); String basePath = request.getScheme()+"://&quo...
- @PathVariable,@RequestParam, @RequestBody,@ModelAttribute,@RequestHeader,@CookieValue的区别
- @RequestParam、@RequestBody和@ModelAttribute区别
- getContextPath、getServletPath、getRequestURI、getRealPath、getRequestURL、getPathInfo (); 的区别
request.getParameter() request.getAttribute()
(1)request.getParameter()取得是通过容器的实现来取得通过类似post,get等方式传入的数据,request.setAttribute()和getAttribute()只是在web容器内部流转,仅仅是请求处理阶段。
(2)request.getParameter()方法传递的数据,会从Web客户的传到Web服务器端,代表HTTP请求数据。request.getParameter()方法返回String类型的数据。
public AuthUser getAuthUser() {
// 请求域中获取
HttpServletRequest request = SessionUtil.getRequest();
AuthUser rau = (AuthUser) request.getAttribute(Const.AUTH_USER_IN_REQUEST);
if (rau != null) {
return rau;
}
Integer userId = SessionCore.UserId.value();
if (userId == null) {
logger.info("session user is null");
return null;
}
AuthUser authUser = getAuthUser(userId);
if (authUser != null) {
request.setAttribute(Const.AUTH_USER_IN_REQUEST, authUser);
}
return authUser;
}
request.getAttribute() 适用于服务端一次请求到处调用的需求。
<% String path = request.getContextPath(); String basePath = request.getScheme()+"://&quo...
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
这个语句是用来拼接当前网页的相对路径的。
<base herf="...">从来表明当前页面的相对路径所使用的根路径,也就是项目名称
比如,页面内部有一个连接,完整的路径应该是 http://localhost:8085/Info_System/user/user_info.jsp
其中http://server/是服务器的基本路径,Info_System是当前应用程序的名字,那么,我的根路径应该是那么http://localhost:80/Info_System/。
用这个base,服务器就可以动态的将指定路径和页面的相对路径拼装起来,形成完整的路径。
1.request.getSchema();可以返回当前页面所使用的协议,就是"http"
2.request.getServerName();返回当前页面所在服务器的名字,就是上面例子中的"localhost"
3.request.getServerPort();返回当前页面所在服务器的端口号,就是上面例子中的"8085"
4.request.getContextPath();返回当前页面所在的应用的名字,就是上面例子中的"Info_System"
当前页面路径是:http://localhost:80/Info_System/uploadAttachs/attachs_list.jsp
根据上面的介绍,那么我在当前页面中有跳转为: <li><a href="<%=basePath%>user/user_info.jsp"></a></li>就应该这样写。
原文:https://blog.csdn.net/haocm66/article/details/52998785
版权声明:本文为博主原创文章,转载请附上博文链接!
@PathVariable,@RequestParam, @RequestBody,@ModelAttribute,@RequestHeader,@CookieValue的区别
@RequestMapping(value="/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)
public String processSubmit(@ModelAttribute Pet pet) {
}
请求路径上有个id的变量值,可以通过@PathVariable来获取 @RequestMapping(value = "/page/{id}", method = RequestMethod.GET)
@RequestParam用来获得静态的URL请求入参 spring注解时action里用到。
简介:
handler method 参数绑定常用的注解,我们根据他们处理的Request的不同内容部分分为四类:(主要讲解常用类型)
A、处理requet uri 部分(这里指uri template中variable,不含queryString部分)的注解: @PathVariable;
B、处理request header部分的注解: @RequestHeader, @CookieValue;
C、处理request body部分的注解:@RequestParam, @RequestBody;
D、处理attribute类型是注解: @SessionAttributes, @ModelAttribute;
1、 @PathVariable
当使用@RequestMapping URI template 样式映射时, 即 someUrl/{paramId}, 这时的paramId可通过 @Pathvariable注解绑定它传过来的值到方法的参数上。
示例代码:
@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController {
@RequestMapping("/pets/{petId}")
public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
// implementation omitted
}
}
上面代码把URI template 中变量 ownerId的值和petId的值,绑定到方法的参数上。若方法参数名称和需要绑定的uri template中变量名称不一致,需要在@PathVariable("name")指定uri template中的名称。
2、 @RequestHeader、@CookieValue
@RequestHeader 注解,可以把Request请求header部分的值绑定到方法的参数上。
示例代码:
这是一个Request 的header部分:
- Host localhost:8080
- Accept text/html,application/xhtml+xml,application/xml;q=0.9
- Accept-Language fr,en-gb;q=0.7,en;q=0.3
- Accept-Encoding gzip,deflate
- Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
- Keep-Alive 300
@RequestMapping("/displayHeaderInfo.do") public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding, @RequestHeader("Keep-Alive") long keepAlive) { }
上面的代码,把request header部分的 Accept-Encoding的值,绑定到参数encoding上了, Keep-Alive header的值绑定到参数keepAlive上。
@CookieValue 可以把Request header中关于cookie的值绑定到方法的参数上。
例如有如下Cookie值:
- JSESSIONID=415A4AC178C59DACE0B2C9CA727CDD84
参数绑定的代码:
@RequestMapping("/displayHeaderInfo.do")
public void displayHeaderInfo(@CookieValue("JSESSIONID") String cookie) {
}
即把JSESSIONID的值绑定到参数cookie上。
3、@RequestParam, @RequestBody
@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用来指示参数是否必须绑定;
示例代码:
@Controller
@RequestMapping("/pets")
@SessionAttributes("pet")
public class EditPetForm {
@RequestMapping(method = RequestMethod.GET)
public String setupForm(@RequestParam("petId") int petId, ModelMap model) {
Pet pet = this.clinic.loadPet(petId);
model.addAttribute("pet", pet);
return "petForm";
}
@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>里,这种情况在某些特殊需求下使用,详情查看FormHttpMessageConverter api;
示例代码:
<span>@RequestMapping(value = "/something", method = RequestMethod.PUT)
public void handle(@RequestBody String body, Writer writer) throws IOException {
writer.write(body);
} </span>
4、@SessionAttributes, @ModelAttribute
@SessionAttributes:
该注解用来绑定HttpSession中的attribute对象的值,便于在方法中的参数里使用。
该注解有value、types两个属性,可以通过名字和类型指定要使用的attribute 对象;
示例代码:
@Controller
@RequestMapping("/editPet.do")
@SessionAttributes("pet")
public class EditPetForm {
// ...
}
@ModelAttribute
该注解有两个用法,一个是用于方法上,一个是用于参数上;
用于方法上时: 通常用来在处理@RequestMapping之前,为请求绑定需要从后台查询的model;
用于参数上时: 用来通过名称对应,把相应名称的值绑定到注解的参数bean上;要绑定的值来源于:
A) @SessionAttributes 启用的attribute 对象上;
B) @ModelAttribute 用于方法上时指定的model对象;
C) 上述两种情况都没有时,new一个需要绑定的bean对象,然后把request中按名称对应的方式把值绑定到bean中。
用到方法上@ModelAttribute的示例代码:
// Add one attribute
// The return value of the method is added to the model under the name "account"
// You can customize the name via @ModelAttribute("myAccount")
@ModelAttribute
public Account addAccount(@RequestParam String number) {
return accountManager.findAccount(number);
}
用在参数上的@ModelAttribute示例代码:
@RequestMapping(value="/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)
public String processSubmit(@ModelAttribute Pet pet) {
}
首先查询 @SessionAttributes有无绑定的Pet对象,若没有则查询@ModelAttribute方法层面上是否绑定了Pet对象,若没有则将URI template中的值按对应的名称绑定到Pet对象的各属性上。
@RequestParam、@RequestBody和@ModelAttribute区别
<div id="cnblogs_post_body"><p>一、@RequestParam<br>GET和POST请求传的参数会自动转换赋值到@RequestParam 所注解的变量上<br>1. @RequestParam(org.springframework.web.bind.annotation.RequestParam)用于将指定的请求参数赋值给方法中的形参。<br>例:<br>(1) get请求:</p> <p>url请求:<a href="http://localhost:8080/WxProgram/findAllBookByTag?tagId=1&pageIndex=3" target="_blank">http://localhost:8080/WxProgram/findAllBookByTag?tagId=1&pageIndex=3</a></p> <p>userTest.jsp</p> <div> <pre><form action="/WxProgram/json/requestParamTest" method="get"><span> requestParam Test</span><br><span> 用户名:</span><input type="text" <span>name="username"</span>><br><span> 用户昵称:</span><input type="text" <span>name="usernick"</span>><br> <input type="submit" value="提交"> </form></pre> </div> <p>UserController.java</p> <div><div><span><a href="javascript:void(0);" onclick="copyCnblogsCode(this)" title="复制代码"><img src="//common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></span></div> <pre> @RequestMapping(value="/requestParamTest", method =<span> RequestMethod.GET) </span><span>public</span> String requestParamTest(<span>@RequestParam(value="username") String userName, @RequestParam(value="usernick"</span><span><span>) String userNick</span>){ System.out.println(</span>"requestParam Test"<span>); System.out.println(</span>"username: " +<span> userName); System.out.println(</span>"usernick: " +<span> userNick); </span><span>return</span> "hello"<span>; }</span></pre> <div><span><a href="javascript:void(0);" onclick="copyCnblogsCode(this)" title="复制代码"><img src="//common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></span></div></div> <p>上述代码会将请求中的username参数的值赋给username变量。</p> <p>等价于:</p> <div><div><span><a href="javascript:void(0);" onclick="copyCnblogsCode(this)" title="复制代码"><img src="//common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></span></div> <pre> @RequestMapping(value="/requestParamTest", method =<span> RequestMethod.GET) </span><span>public</span><span> String requestParamTest(String username, <span>HttpServletRequest request</span>){ System.out.println(</span>"requestParam Test"<span>); System.out.println(</span>"username: " +<span> username); String usernick </span>= <span>request.getParameter("usernick"</span><span><span>);</span> System.out.println(</span>"usernick: " +<span> usernick); </span><span>return</span> "hello"<span>; }</span></pre> <div><span><a href="javascript:void(0);" onclick="copyCnblogsCode(this)" title="复制代码"><img src="//common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></span></div></div> <p>也可以不使用@RequestParam,直接接收,此时要求controller方法中的参数名称要跟form中name名称一致</p> <div><div><span><a href="javascript:void(0);" onclick="copyCnblogsCode(this)" title="复制代码"><img src="//common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></span></div> <pre> @RequestMapping(value="/requestParamTest", method =<span> RequestMethod.GET) </span><span>public</span><span> String requestParamTest(<span>String username, String usernick</span>){ System.out.println(</span>"requestParam Test"<span>); System.out.println(</span>"username: " +<span> username); System.out.println(</span>"usernick: " +<span> usernick); </span><span>return</span> "hello"<span>; }</span></pre> <div><span><a href="javascript:void(0);" onclick="copyCnblogsCode(this)" title="复制代码"><img src="//common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></span></div></div> <p>总结:</p> <p>接收请求参数的方式:</p> <div> <pre>@RequestParam(value="username") String userName, @RequestParam(value="usernick") String userNick <span>//</span><span>value中的参数名称要跟name中参数名称一致</span> String username, String usernick<span>//</span><span> 此时要参数名称一致</span> HttpServletRequest request <span>//</span><span>request.getParameter("usernick")</span></pre> </div> <p>(2) post请求:<br>跟get请求格式一样,只是把方法中的get换成post</p> <p>@RequestParam<br>用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容。提交方式为get或post。(Http协议中,如果不指定Content-Type,则默认传递的参数就是application/x-www-form-urlencoded类型)</p> <p>RequestParam实质是将Request.getParameter() 中的Key-Value参数Map利用Spring的转化机制ConversionService配置,转化成参数接收对象或字段。</p> <p>get方式中query String的值,和post方式中body data的值都会被Servlet接受到并转化到Request.getParameter()参数集中,所以@RequestParam可以获取的到。</p> <p>二. @RequestBody</p> <p>@RequestBody注解可以接收<span>json格式的数据</span>,并将其转换成对应的数据类型。</p> <p>1. @RequestBody接收一个对象<br>url请求:<a href="http://localhost:8080/WxProgram/findBookByName" target="_blank">http://localhost:8080/WxProgram/findBookByName</a></p> <div><div><span><a href="javascript:void(0);" onclick="copyCnblogsCode(this)" title="复制代码"><img src="//common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></span></div> <pre>@RequestMapping(value="/findBookByName", method = RequestMethod.<span>POST</span><span>) @ResponseBody </span><span>public</span><span> DbBook findBookByName(<span>@RequestBody DbBook book</span>){ System.out.println(</span>"book: " +<span> book.toString()); System.out.println(</span>"book name: " +<span> book.getTitle()); String bookName </span>=<span> book.getTitle(); DbBook book </span>=<span> wxService.findBookByName(bookName); </span><span>return</span><span> book; }</span></pre> <div><span><a href="javascript:void(0);" onclick="copyCnblogsCode(this)" title="复制代码"><img src="//common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></span></div></div> <p>2. @RequestBody接收不同的字符串</p> <p>(1)前台界面,这里以小程序为例</p> <div><div><span><a href="javascript:void(0);" onclick="copyCnblogsCode(this)" title="复制代码"><img src="//common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></span></div> <pre><span>wx.request({ url: host.host </span>+ `/WxProgram/<span>deleteBookById`, method: </span>''POST''<span>, data: { <span> nick</span>: </span><span>this</span><span>.data.userInfo.nickName, <span>bookIds</span>: bookIds }, success: (res) </span>=><span> { console.log(res); </span><span>this</span><span>.getCollectionListFn(); }, fail: (err) </span>=><span> { console.log(err); } })</span></pre> <div><span><a href="javascript:void(0);" onclick="copyCnblogsCode(this)" title="复制代码"><img src="//common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></span></div></div> <p>(2)controller</p> <div><div><span><a href="javascript:void(0);" onclick="copyCnblogsCode(this)" title="复制代码"><img src="//common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></span></div> <pre>@RequestMapping(value="/deleteBookById",method=<span>RequestMethod.POST) @ResponseBody </span><span>public</span> <span>void</span> deleteBookById(<span>@RequestBody Map<String, String></span><span><span> map</span>){ String bookIds </span>= <span>map.get("bookIds"</span><span><span>)</span>; String nick </span>= <span>map.get("nick"</span><span><span>)</span>; String[] idArray </span>= bookIds.split(","<span>); Integer userId </span>=<span> wxService.findIdByNick(nick); </span><span>for</span><span>(String id : idArray){ Integer bookid </span>=<span> Integer.parseInt(id); System.out.println(</span>"bookid: " +<span> bookid); wxService.removeBookById(bookid, userId); } }</span></pre> <div><span><a href="javascript:void(0);" onclick="copyCnblogsCode(this)" title="复制代码"><img src="//common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></span></div></div> <p>@RequestBody<br>处理HttpEntity传递过来的数据,一般用来处理非Content-Type: application/x-www-form-urlencoded编码格式的数据。</p> <p>GET请求中,因为没有HttpEntity,所以@RequestBody并不适用。<br>POST请求中,通过HttpEntity传递的参数,必须要在请求头中声明数据的类型Content-Type,SpringMVC通过使用HandlerAdapter 配置的HttpMessageConverters来解析HttpEntity中的数据,然后绑定到相应的bean上。</p> <p>@RequestBody用于post请求,不能用于get请求</p> <p>这里涉及到使用@RequestBody接收不同的对象<br>1. 创建一个新的entity,将两个entity都进去。这是最简单的,但是不够“优雅”。<br>2. 用Map<String, Object>接受request body,自己反序列化到各个entity中。<br>3. 类似方法2,不过更为generic,实现自己的HandlerMethodArgumentResolver。参考<a href="https://sdqali.in/blog/2016/01/29/using-custom-arguments-in-spring-mvc-controllers/" target="_blank">这里 </a></p> <p>三、@ModelAttribute</p> <p>@ModelAttribute注解类型将参数绑定到Model对象</p> <p>1. userTest.jsp</p> <div><div><span><a href="javascript:void(0);" onclick="copyCnblogsCode(this)" title="复制代码"><img src="//common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></span></div> <pre><form action="/WxProgram/json/modelAttributeTest" method="post"><span> modelAttribute Test</span><br><span> 用户id:</span><input type="text" name="userId"><br><span> 用户名:</span><input type="text" name="userName"><br><span> 用户密码:</span><input type="password" name="userPwd"><br> <input type="submit" value="提交"><br> </form></pre> <div><span><a href="javascript:void(0);" onclick="copyCnblogsCode(this)" title="复制代码"><img src="//common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></span></div></div> <p>name的属性值要跟User的属性相对应。</p> <p>2. UserController.java</p> <div><div><span><a href="javascript:void(0);" onclick="copyCnblogsCode(this)" title="复制代码"><img src="//common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></span></div> <pre>@RequestMapping(value="/modelAttributeTest", method =<span> RequestMethod.POST) </span><span>public</span><span> String modelAttributeTest(<span>@ModelAttribute User user</span>){ System.out.println(</span>"modelAttribute Test"<span>); System.out.println(</span>"userid: " +<span> user.getUserId()); System.out.println(</span>"username: " +<span> user.getUserName()); System.out.println(</span>"userpwd: " +<span> user.getUserPwd()); </span><span>return</span> "hello"<span>; }</span></pre> <div><span><a href="javascript:void(0);" onclick="copyCnblogsCode(this)" title="复制代码"><img src="//common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></span></div></div> <p>3. User.java</p> <div><div><span><a href="javascript:void(0);" onclick="copyCnblogsCode(this)" title="复制代码"><img src="//common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></span></div> <pre><span>public</span> <span>class</span><span> User { </span><span>private</span><span> Integer userId; </span><span>private</span><span> String userName; </span><span>private</span><span> String userPwd;
</span><span>public</span><span> User(){
</span><span>super</span><span>();
}
</span><span>//</span><span>setter and getter </span>
}</pre>
<div><span><a href="javascript:void(0);" onclick="copyCnblogsCode(this)" title="复制代码"><img src="//common.cnblogs.com/images/copycode.gif" alt="复制代码"></a></span></div></div> <p> </p> <p>当前台界面使用GET或POST方式提交数据时,数据编码格式由请求头的ContentType指定。分为以下几种情况:<br>1. application/x-www-form-urlencoded,这种情况的数据@RequestParam、@ModelAttribute可以处理,@RequestBody也可以处理。<br>2. multipart/form-data,@RequestBody不能处理这种格式的数据。(form表单里面有文件上传时,必须要指定enctype属性值为multipart/form-data,意思是以二进制流的形式传输文件。)<br>3. application/json、application/xml等格式的数据,必须使用@RequestBody来处理。</p> <p>参考:</p> <p><a href="https://blog.csdn.net/xinluke/article/details/52710706" target="_blank">@RequestBody和@RequestParam区别 </a></p> <p><a href="https://segmentfault.com/q/1010000009017635" target="_blank">https://segmentfault.com/q/1010000009017635</a></p></div>
getContextPath、getServletPath、getRequestURI、getRealPath、getRequestURL、getPathInfo (); 的区别
<%
out.println("getContextPath: "+request.getContextPath()+"<br/>");
out.println("getServletPath: "+request.getServletPath()+"<br/>");
out.println("getRealPath: "+request.getRealPath("/")+"<br/>");
out.println("getRequestURL: "+request.getRequestURL()+"<br/>");
out.println("getRequestURI: "+request.getRequestURI()+"<br/>");
%>
出来的输出效果为:
getContextPath: /ckswzl
getServletPath: /admin/login.jsp
getRealPath: D:\document\EclipseWorkSpace2\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\ckswzl\
getRequestURL: http://localhost:8080/ckswzl/admin/login.jsp
getRequestURI: /ckswzl/admin/login.jsp
getContextPath 是返回的项目上下文的名字(其实也就是项目名);
getServletPath 是返回的是项目名到当前 jsp 文件的路径(意思就是在这个项目首页到文件的路径)
getRequestURI 是返回的是项目名到整个文件的请求路径
getRealPath 是返回的文件所在的绝对路劲。相对于当前计算机的真实路径
getRequestURL 是返回的整个 URL 的路径请求(意思就是返回的浏览器地址栏的整个地址)
request.getPathInfo(); 这个方法返回请求的实际 URL 相对于请求的 serlvet 的 url 的路径。
如果我们的 servlet-mapping 如下配置:
<servlet-mapping>
<servlet-name>jetbrick-template</servlet-name>
<url-pattern>/template/*</url-pattern>
</servlet-mapping>
那么访问: /context/templates/index.jetx
request.getServletPath() == "/templates"
request.getPathInfo() == "/index.jetx"
今天关于request.getParameter() request.getAttribute()的介绍到此结束,谢谢您的阅读,有关<% String path = request.getContextPath(); String basePath = request.getScheme()+"://&quo...、@PathVariable,@RequestParam, @RequestBody,@ModelAttribute,@RequestHeader,@CookieValue的区别、@RequestParam、@RequestBody和@ModelAttribute区别、getContextPath、getServletPath、getRequestURI、getRealPath、getRequestURL、getPathInfo (); 的区别等更多相关知识的信息可以在本站进行查询。
本文标签: