HttpServletRequest 取得请求的完整URL

 

新建两个jsp文件,index1.jsp,index2.jsp

 

index1.jsp

<html>
<body>
<%
//forward至index2.jsp,传递参数username和sex
request.getRequestDispatcher("index2.jsp?username=lisi&sex=1").forward(request,response);
%>
</body>
</html>

 

index2.jsp

<%@ page language="java" contentType="text/html; charset=gbk" pageEncoding="gbk"%>
<%@page import="java.util.*"%>

<%@page import="java.util.Map.Entry"%><html>
<body>
<h3>request.getRequestURL、request.getQueryString()</h3>
<%
String uri = request.getRequestURI();
out.print("request.getRequestURI()="+uri);
out.print("<hr>");
StringBuffer url = request.getRequestURL();
out.print("request.getRequestURL()="+url);
out.print("<hr>");
String queryString = request.getQueryString();
out.print("request.getQueryString()="+queryString);
out.print("<hr>");
out.print("请求的完整URL="+url+"?"+queryString);
out.print("<hr>");
%>

<h3>request.getAttributeNames</h3>

<%
Enumeration<String> enums = request.getAttributeNames();
while(enums.hasMoreElements()){
	String key = enums.nextElement();
	out.print("key="+key+",value="+request.getAttribute(key));
	out.print("<hr>");
}
if(request.getAttribute("javax.servlet.forward.request_uri") != null){
	String uri2 = String.valueOf(request.getAttribute("javax.servlet.forward.request_uri"));
	String queryString2 = String.valueOf(request.getAttribute("javax.servlet.forward.query_string"));
	String url2 = url.toString().replace(uri,uri2);
	out.print("请求的完整URL2="+url2+"?"+queryString2);
	out.print("<hr>");
}
%>

<h3>request.getParameter</h3>
<%
Enumeration<String> enums2 = request.getParameterNames();
while(enums2.hasMoreElements()){
	String key = enums2.nextElement();
	out.print("key="+key+",value="+request.getParameter(key));
	out.print("<hr>");
}

%>
</body>
</html>

 

在浏览器地址栏直接访问:

http://localhost:8080/web/index2.jsp?username=zhangsan&password=123456

打印结果:

HttpServletRequest 取得请求的完整URL_第1张图片
 

在浏览器地址栏访问:

http://localhost:8080/web/index1.jsp?username=zhangsan&password=123456

打印结果如下:


HttpServletRequest 取得请求的完整URL_第2张图片
 

 

你可能感兴趣的:(HttpServletRequest 取得请求的完整URL)