项目需求:所有jsp页必须通过Action转发,不能直接在地址栏链接jsp或
我的应用如下:
1.LoginFilter
Java代码
publicclassLoginFilterimplementsFilter {
publicvoiddoFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throwsIOException, ServletException {
HttpServletRequest hRequest = (HttpServletRequest)request;
HttpServletResponse hResponse = (HttpServletResponse)response;
String uri = hRequest.getRequestURI();
System.out.println("uri======"+uri);
TBussinessInfo info = (TBussinessInfo) hRequest.getSession().getAttribute("user");
if("/b2cPlatform/jsp/phone/login/login.jsp".equals(uri) ||"/b2cPlatform/".equals(uri)
|| "/b2cPlatform/jsp/phone/login/trunToLogin.jsp".equals(uri) )
{
chain.doFilter(request, response);
}
else
{
hResponse.sendRedirect(hRequest.getContextPath());//不允许直接访问jsp页,除非login.jsp等页
}
}
publicvoiddestroy() {}
publicvoidinit(FilterConfig arg0)throwsServletException {}
}
2.web.xml
Xml代码
LoginFilter
com.hanpeng.b2c.phone.priv.LoginFilter
LoginFilter
*.jsp
二、网上其他资料
是解决相对路径的问题,可返回站点的根路径。
request.getContextPath()得到的是项目的名字,如果项目为根目录,则得到一个"",即空的字条串,
如果项目为dzjc, / 将得到dzjc/,服务器端的路径则会自动加上,
应该就是指当前路径下的这个xxx.jsp页面,有时候也可以在head里设置html:base
来解决路径的问题,不过用的最多的还是request.getContextPath。
用EL来表示相同功能的EL为:${pageContext.request.getContextPath()}
request.getScheme();
返回的协议名称,默认是http
request.getServerName()
返回的是你浏览器中显示的主机名
getServerPort()
获取服务器端口号
如果想得到工程文件的实际物理路径,可通过:,这样页面就会输出:d:/web
现在request.getRealPath("") 这个方法已经不推荐使用了
可以使用
ServletContext.getRealPath(java.lang.String) instead. request.getSession().getServletContext().getRealPath() 得到工程文件的实际物理路径,也就是绝对地址
简便用法:
String path=request.getContextPath();//path = /oa
request.setAttribute("path", path);
在页面中应用(EL) ${path}/images/xx.jpg(绝对定位:oa/images/xx.jpg)
可以解决复杂的相对路径定位失败的问题。