雪洗中关村

导航

【java、js】获取URL请求路径信息

 

 

 

有时候,我们需要对请求路径做处理,例如url重定向,或者为url追加参数,我们可以使用js在前端对请求路径做处理, 也可以使用java在后端对请求路径做处理。

  • java获取请求路径信息

  • 开发javaweb项目时,  需要web容器,  例如tomcat是一个常用的javaweb容器, 该容器会为我们的servlet(假如没有使用mvc框架, 如struts2、springmvc)提供一个HttpServletRequest对象, 通过访问该对象, 我们可以获取到请求路径信息, 示例如下:
//测试的请求url, get方法  
//"http://localhost:8080/struts2/user/login.action?userid=1000"  
   
//获取请求方法  
request.getMethod();        //返回"GET"  
   
//获取请求协议  
request.getScheme();        //返回"http"  
   
//获取请求域名(IP地址);  
request.getServerName();    //返回"localhost"  
   
//获取请求端口号  
request.getServerPort();    //返回"8080"  
   
//获取请求URL, 不包括请求参数  
request.getRequestURL();    //返回"http://localhost:8080/struts2/user/login.action"  
   
//获取请求URI, 也不包括请求参数, 相当于contextPath + servletPath  
request.getRequestURI();    //返回"/struts2/user/login.action"  
   
//获取请求参数, 不带问号"?"  
request.getQueryString();   //返回"userid=1000"   
   
//获取请求协议  
request.getProtocol();      //返回"HTTP/1.1"  
   
//获取Web应用程序路径  
request.getContextPath();   //返回"/struts2"  
   
//获取请求资源路径  
request.getServletPath();   //返回"/user/login.action"

 

root形式获取:

ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            String sessionId = RequestContextHolder.getRequestAttributes().getSessionId();//获取Session
            HttpServletRequest request = attributes.getRequest();  //获取HttpServletRequest
            String key = sessionId + "-" + request.getServletPath();//获取ServletPath

 

 

  • js获取请求路径信息

  • js有个全局变量location,操作这个对象就等于操作浏览器的地址栏,下面我们观察一下location对象可以获取到什么url信息

 

//测试的请求url, get方法  
//"http://localhost:8080/struts2/user/login.action?userid=1000#topic1"  
   
//获取请求协议  
location.protocol;    //返回"http:"  
   
//获取请求服务器域名(IP地址),   
location.hostname;    //返回"localhost"  
   
//获取请求服务器端口号  
location.port;        //返回"8080"  
   
//获取请求服务器的域名(IP地址)和端口号  
location.host;        //返回"localhost:8080"  
   
//获取请求资源名  
location.pathname;    //返回"/struts2/user/login.action"  
   
//获取锚点  
location.hash;        //返回"#topic1"  
   
//获取请求参数  
location.search;      //返回?userid=1000", 注意: 如果请求地址只有"?"后面却没有请求参数, 则返回空字符串  
   
//返回整个url地址, 包含以上所有信息  
location.href;        //返回"http://localhost:8080/struts2/user/login.action#topic1?userid=1000#topic1"  

 

 

原文参考:https://www.iteye.com/blog/lizhuquan0769-2230749

 

posted on 2020-05-15 16:02  雪洗中关村  阅读(1936)  评论(0编辑  收藏  举报