需求:在使用servlet的时候,最后经常会转发或重定向到请求页面,每次都要写请求页面的地址。
思考:能不能通过请求对象,直接获取请求页面的地址呢?
通过request.getHeader("referer")返回的是http://客户机IP/项目名/中间文件夹/请求页面,同时request.getContextPath()返回/项目名。
那我直接在servlet模板中定义一个方法叫做backRequest(HttpServletRequest request),来实现转发或重定向功能。
转发:要得到referer头信息中"/项目名"以后的字符串,就以request.getContextPath()为分割符来得到数组,数组的最后一项即为所要得到的字符串,将它作为转发的路径。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
//转发至请求页面
public
void
backRequest(HttpServletRequest request,HttpServletResponse response)
throws
ServletException, IOException
{
//得到请求页面的完整地址http://客户机IP/项目名/中间文件夹/请求页面
String completedRequestURL = request.getHeader(
"referer"
);
//得到/项目名
String requestProName = request.getContextPath();
//分离转发需要的地址
String[] arr = completedRequestURL.split(requestProName);
//转发操作
request.getRequestDispatcher(arr[arr.length-
1
]).forward(request, response);
}
|
重定向:在referer头信息中,得到request.getContextPath()这个字符串的索引位置,取这个位置以后的字符串,即带项目名作为重定向的地址。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
//转发至请求页面
public
void
backRequest(HttpServletRequest request,HttpServletResponse response)
throws
ServletException, IOException
{
//得到请求页面的完整地址http://客户机IP/项目名/中间文件夹/请求页面
String completedRequestURL = request.getHeader(
"referer"
);
//得到/项目名
String requestProName = request.getContextPath();
//得到项目名字符串的索引位置
int
startIndex = completedRequestURL.indexOf(requestProName);
//得到带项目名称的路径,用来重定向到请求页面。
String hopeUrl = completedRequestURL.substring(startIndex);
//重定向
response.sendRedirect(hopeUrl);
}
|
本文转自屠夫章哥 51CTO博客,原文链接:http://blog.51cto.com/4259297/1673090
,如需转载请自行联系原作者