一直对getRequestURI()与getRequestURL()理解不透彻,因此今天通过查找资料,现将些许收获分享一下:
[非原创]代码搬运工..(*^__^*)
1.request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/"
http://www.baidu.com:8080/web/index.html
2.request.getContextPath() 返回 "/web"
3.request.getRequestURI() 返回 /myContext/requestdemo.jsp, 返回的是String
4.request.getRequestURL() 返回 http://localhost:8080/myContext/requestdemo.jsp, 返回的StringBuffer
http://www.baidu.com:8080/web/index.html?username=abc&password=123
1.注册注解@MarkRequest:
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented @Mapping public @interface MarkRequest{ String value() default "returnURI"; String scope() default "session" String[] excludes() default {}; }
2.根据有无@MarkRequest注解来判断是否应当向request或session域中保存请求的uri:
//根据有无@MarkRequest注解来判断是否应当向request或session域中保存请求的uri public void postHandle(HttpServletRequest request,HttpServletResponse response,Object handler,ModelAndView modelAndView){ if(handler instanceof HandlerMethod)}{ HandlerMethod hm=(HandlerMethod)handler; MarkRequest markRequest=hm.getMethodAnnotation(MarkRequest.class); if(markRequest!=null){ String name=markRequest.value(); String scope=markRequest.scope(); String[] excludes= markRequest.excludes(); //不需要保存的uri请求参数 markRequestInfo(request,scope,name,excludes); } } }
/** * 向request域或session域中保存请求的uri */ public void markRequestInfo(HttpServletRequest request,String scope,String name,String[] excludes){ List excludeParamList=Arrays.asList(excludes); String uri=getRequestInfo(request,false,excludeParamList); if("request".equals(scope)){ request.setAttribute(name,uri); }else if("session".equals(scope)){ request.getSession().setAttribute(name,uri); } }
public String getRequestInfo(HttpServletRequest request,boolean trimContextPath,List excludeParamList){ String uri=request.getRequestURI(); //是否去掉应用名 if(trimContextPath){ String contextPath = request.getContextPath(); if(uri.startsWith(contextPath)){ uri = uri.substring(contextPath.length()); } } //往uri中添加请求参数 Map<String, String[]> paramMap=(Map<String, String[]) request.getParameterMap(); uri = uri + "?"; if(!paramMap.isEmpty()){ for(Map.Entry<String,String[]> entry : paramMap.entrySet()){ String key = entry.getKey(); if(!excludeParamList.contains(key)){ String[] values= entry.getValue(); for(int i=0; i< values.length; i++){ //url中的请求参数,应当使用URIEncoder把普通字符串转换成application/x-www-form-urlencoded字符串 uri += (key + "=" + URIEncoder.encode(values[i],"utf-8") + "&"); } } } } //去掉去掉uri中的最后一个‘&‘字符 return uri.substring(0,uri.length()-1); }
时间: 2024-10-20 01:47:04