HttpServletRequest的getServletPath、getServletURI、getServletURL等区别

来源:互联网 发布:能在淘宝上买貂皮吗 编辑:程序博客网 时间:2024/06/15 09:23

现在项目做到加权限了,如何防止用户通过直接输入URL访问网页,去查资料,了解到在filter里用HttpServletRequest里的方法得到该请求的父URL-fatherURL,判断该fatherURL是否为空,如果为空就表示该请求是通过直接输入URL访问的。

代码:

public void doFilter(ServletRequest request, ServletResponse response,           FilterChain chain) throws IOException, ServletException {     //首先判断如果是在URL输入页面访问,直接非法     HttpServletRequest req=(HttpServletRequest)request;     HttpServletResponse resp=(HttpServletResponse)response;     String fatherUrl = fatherUrl = req.getHeader("REFERER");//取得上一级页面的RUL       if("".equals(fatherUrl ) || null == fatherUrl ) {             String url = req.getServletPath();             //第一次转发             if("//pages/login.jsp".equals(url )) {                     chain.doFilter(request, response);             } else {     //设置输出页面编码                     resp.setContentType("text/html;charset=gb2312");                      resp.getWriter().write("错误页面 ,无此页");                     return ;              }      } else{     //如果不是直接URL输入访问          if(null==req.getSession().getAttribute("inWebUser")) {                 resp.getWriter().write("非法访问");                 return;          } else {                 chain.doFilter(request, response);          }     }}


知道这个方法后,感觉HttpServletRequest太好用了,就去了JavaEE API文档,看到HttpServletRequest里有几个得到URL的方法,既然有好几个,说明它们之间肯定有不同之处,针对各种实际情况运用。下面就说说它们的区别:

getServletPath:得到相对项目的url,不带项目名称        如://sys/menu/gomain.htm

String path = ((HttpServletRequest)req).getServletPath();

getRequestURI:得到相对服务器的url,和上面有不同之处,getRequestURI带有项目root,以项目名称为开头,如:/cms//sys/menu/gomain.htm

String requestURI = ((HttpServletRequest)req).getServletURI();


getContextPath:得到部署的项目名(Context-root),不是URL,仅仅项目名字  如:/cms

String ContextPath = ((HttpServletRequest)req).getContextPath();


getRequestURL:得到绝对地址url如:http://localhost:8080/cms//sys/menu/gomain.htm

StringBuffer RequestURL = ((HttpServletRequest)req).getRequestURL();


getRealPath:得到应用程序部署在服务器上的绝对路径。如:D:\apache-tomcat-5.5.23\webapps\cms\

String realPath = this.fc.getServletContext().getRealPath("/");

               System.out.println("ServletPath:"+path+"\n"+"ContextPath:"+ContextPath+"\n"+"requestURI:"+requestURI+"\n"+"RequestURL:"+RequestURL+"\n"+"realPath:"+realPath);

结果如下:

ServletPath:/sys/menu/gomain.htm
ContextPath:/cms
requestURI:/cms//sys/menu/gomain.htm
RequestURL:http://localhost:8080/cms//sys/menu/gomain.htm
realPath:D:\apache-tomcat-5.5.23\webapps\cms\ 


速记:

  • getServletPath与getRequestURI相似,区别在于有无项目名称
  • getRequestURL是带有HTTP协议的URL,
  • getContextPath得到项目的名称
  • getRealPath得到在服务器上的绝对路径

原创粉丝点击