getContextPath、getServletPath、getRequestURI的区别

假定你的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 

结合到Spring MVC项目来说一下:

1.jsp:           

 <li><a class="add" rel="add-category" href="${ctx}/admin/category/create.do?parentId=${param.q_eq_parentId}" target="navTab" title="添加目录"><span>添加</span></a></li>

2.如何找到${ctx}/admin/category/create.do地址?

首先,找ctx代表什么。假如:pageContext.setAttribute("ctx", application.getContextPath());从上面的解说可以知道System.out.println(request.getContextPath())得出的是/news。故完整路径为:/news/admin/category/create.do。至于参数则根据实际研究。

可看到上路径为.do结尾。Spring MVC与Struts从原理上很相似(都是基于MVC架构),都有一个控制页面请求的Servlet,处理完后跳转页面。spring会自动扫描找到该路径对应的controller,如下图所示:

 

当前对应的路径为CategoryController类下的showCreate方法

 

 

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

 

输出:

path:/E_WuLiu
basePath:http://localhost:8080/E_WuLiu/

getContextPath():得到当前应用的根目录

getScheme():它返回当前请求所使用的协议。 一般的应用返回 "http",对于ssl则返回"https"

getServerName():获取服务器名字,如果是在本地的话就是localhost

getServerPort():获得服务器的端口号

 

 

另外:jsp中获取客户端的浏览器和操作系统信息

string agent = request.getheader("user-agent");
stringtokenizer st = new stringtokenizer(agent,";");
st.nexttoken();
//得到用户的浏览器名
string userbrowser = st.nexttoken();
//得到用户的操作系统名
string useros = st.nexttoken();

 

取得本机的信息也可以这样:

 

操作系统信息
system.getproperty("os.name"); //win2003竟然是win xp?
system.getproperty("os.version");
system.getproperty("os.arch");


浏览器:
request.getheader("user-agent")

 

其他
request.getheader(“user-agent”)返回客户端浏览器的版本号、类型

getheader(string name):获得http协议定义的传送文件头信息,

request. getmethod():获得客户端向服务器端传送数据的方法有get、post、put等类型

request. getrequesturi():获得发出请求字符串的客户端地址

request. getservletpath():获得客户端所请求的脚本文件的文件路径

request. getservername():获得服务器的名字

request.getserverport():获得服务器的端口号

request.getremoteaddr():获得客户端的ip地址

request.getremotehost():获得客户端电脑的名字,若失败,则返回客户端电脑的ip地址

request.getprotocol():

request.getheadernames():返回所有request header的名字,结果集是一个enumeration(枚举)类的实例

request.getheaders(string name):返回指定名字的request header的所有值,结果集是一个enumeration(枚举)类的实例

posted @ 2016-11-23 11:45  新宇泽起  阅读(13582)  评论(0编辑  收藏  举报