response对象常用方法

版权声明:本文为博主原创文章,转载请标注,谢谢 https://blog.csdn.net/qq_43462019/article/details/86611869
  1. request负责封装客户端请求,response封装的是服务器的响应
  2. 重定向采用response.sendRedirect(url)实现,重定向行为发生于浏览器,地址栏地址改变
  3. 转发采用request.getRequestDispatcher(url).forward(request, response)实现,转发行为发生于服务器,地址栏地址不改变
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="controller.jsp" method="post">
		<table>
			<tr>
				<td>用户名</td>
				<td><input type="text" name="userName"></td>
			</tr>
			<tr>
				<td>密码</td>
				<td><input type="password" name="Password"></td>
			</tr>
			<tr>
				<td><input type="submit" value="提交"></td>
			</tr>
		</table>
	</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		String userName = request.getParameter("userName");
		String passWord = request.getParameter("Password");
		if(userName.equals("sa") && passWord.equals("123")){
			//1.通过响应告诉浏览器该请求这样一个地址
			//2.浏览器访问指定url 302代表告诉浏览器该重定向一个URL了
			response.sendRedirect("welcome.jsp?userName="+userName);

            //方法2:转发采用
			RequestDispatcher rd =request.getRequestDispatcher("welcome.jsp");
			rd.forward(request, response);
		}else{
			out.print("用户名或密码不正确!!!");
		}
	%>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<%
	//浏览器发起了两次请求 导致第一次请求 失败
	//1.当第一次请求失败的时候,把数据进行保存 使用数据作为参数来发起第二次请求
	//2.只发出一次请求 完成页面跳转
%>
<body>
	您好<%=request.getParameter("userName") %>!欢迎访问!!!
</body>
</html>

运行效果: 

            

利用链接形式传参:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<a href="result.jsp?color=黄色">黄色</a>
	<a href="result.jsp?color=白色">白色</a>
	<a href="result.jsp?color=红色">红色</a>
	<a href="result.jsp?color=黑色">黑色</a>
	<a href="result.jsp?color=蓝色">蓝色</a>
	<a href="result.jsp?color=紫色">紫色</a>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	您所选择的是<%=request.getParameter("color") %>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_43462019/article/details/86611869
今日推荐