Web应用中request获取path,URI,URL

Web应用中有各种获取path或URI,URL的方法,假设网页访问地址:

http://localhost:8080/tradeload/TestServlet

Web应用context: /tradeload 

各路径鉴定如下:

Java代码  
  1. request.getContextPath()= /tradeload   
  2. request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()= http://localhost:8080   
  3. request.getRequestURL() = http://localhost:8080/tradeload/TestServlet   
  4. request.getRequestURI() = /tradeload/TestServlet   
  5. request.getPathInfo() = null   
  6. request.getServletPath() = /TestServlet   
  7. getServletContext().getRealPath('/') = C:\server\glassfish\domains\domain1\applications\j2ee-modules\tradeload\   

其中的servletpath就是web.xml中配置的url-pattern。

-------------------------------------------------------------------------------

假定你的web application 名称为news,你在浏览器中输入请求路径: 
http://localhost:8080/news/main/list.jsp 

则执行下面向行代码后打印出如下结果:
1、System.out.println(request.getContextPath()); 
打印结果:/news 
2、System.out.println(request.getServletPath()); 
打印结果:/main/list.jsp 
3、System.out.println(request.getRequestURI()); 
打印结果:/news/main/list.jsp 
4、System.out.println(request.getRealPath("/"));  
打印结果:F:\Tomcat 6.0\webapps\news\test
-------------------------------------------------------------------------------------------------------

String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

out.println("basePath:"+basePath);
out.println("<br/>");
out.println("getContextPath:"+request.getContextPath());
out.println("<br/>");
out.println("getServletPath:"+request.getServletPath());
out.println("<br/>");
out.println("getRequestURI:"+request.getRequestURI());
out.println("<br/>");
out.println("getRequestURL:"+request.getRequestURL());
out.println("<br/>");
out.println("getRealPath:"+request.getRealPath("/"));
out.println("<br/>");
out.println("getServletContext().getRealPath:"+getServletContext().getRealPath("/"));
out.println("<br/>");
out.println("getQueryString:"+request.getQueryString());

 

显示结果:

basePath:http://localhost:8080/test/

getContextPath:/test
getServletPath:/test.jsp
getRequestURI:/test/test.jsp
getRequestURL:http://localhost:8080/test/test.jsp
getRealPath:D:\Tomcat 6.0\webapps\test\
getServletContext().getRealPath:D:\Tomcat 6.0\webapps\test\
getQueryString:p=fuck

在一些应用中,未登录用户请求了必须登录的资源时,提示用户登录,此时要记住用户访问的当前页面的URL,当他登录成功后根据记住的URL跳回用户最后访问的页面:

String lastAccessUrl = request.getRequestURL() + "?" + request.getQueryString();






  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值