【javaweb简单教程】2.JSP实现数据传递和保存(含四大作用域及简单示例)

2.JSP实现数据传递和保存

获取表单提交的数据

  • 请求对象:request
public String getParameter(String name)
  • 示例

    • HTML代码:

      <input type="text" name="userName" />
      
    • JSP代码:

      String userName
      		= request.getParameter("userName");
      

get与post区别

比较项Getpost
参数出现在URL中
长度限制
安全性
URL可传播

内置对象

  • JSP已经准备好的,可以直接使用的对象
    • 请求对象:request
    • 输出对象:out
    • 响应对象:response
    • 应用程序对象:application
    • 会话对象:session
    • 页面上下文对象:pageContext
    • 页面对象:page
    • 配置对象:config
    • 异常对象:exception

request对象常用方法

方法名称说明
String getParameter(String name)根据表单组件名称获取提交数据
String[ ] getParameterValues(String name)获取表单组件对应多个值时的请求数据
void setCharacterEncoding(String charset)指定每个请求的编码
RequestDispatcher getRequestDispatcher(String path)返回一个RequestDispatcher对象,该对象的forward( )方法用于转发请求

中文乱码

  • JSP中默认使用的字符编码方式:iso-8859-1,不支持中文
  • 常见的支持中文的编码方式
编码方式收录的字符
gb2312常用简体汉字
gbk简体和繁体汉字
utf-8所有国家需要的字符

jsp表头编码含义

需注意三者编码要一致

<%@ page language="java" contentType="text/html; charset=UTF-8"	//在jsp里面运行的java小脚本的编码
    pageEncoding="UTF-8"%>	//servlet读取的编码
<!DOCTYPE html>
<html>
<head>	
<meta charset="UTF-8">		//html的编码
<title>Insert title here</title>
</head>
<body>

</body>
</html>

解决中文乱码

  • 设置请求和响应的编码方式
    • request.setCharacterEncoding(“utf-8”);
    • response.setCharacterEncoding(“utf-8”);
    • <%@ page language=“java” contentType=“text/html; charset=utf-8”%>
  • get请求出现乱码
    • 治标的方法:new String( s.getBytes(“iso-8859-1”), “utf-8” );
    • 治本的方法:配置tomcat\conf\server.xml文件
      • URIEncoding=“UTF-8”
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8"/>

在请求中存取属性

  • 在请求中保存属性
    • public void setAttribute(String name,Object o)
    • request.setAttribute(“mess”, “注册失败”);
  • 在请求中获取属性
    • public Object getAttribute(String name)

注意:

  • 1、在使用属性值的时候要做非空判断,否则会出现空指针异常
  • 2、它的返回值类型是Object类型,需要做数据类型的转换

转发与重定向

  • 转发
    • RequestDispatcher对象
    • forward()方法
1、request.getRequestDispatcher("url").forward(request, response)
2<jsp:forward page="url" />
  • 重定向
    • 将用户请求重新定位到一个新的URL
response.sendRedirect("url")

转发与重定向的区别

比较项转发重定向
URL变化
重新发出请求不会
是否携带请求
目标URL要求仅本Web应用任意URL

注意:重定向是客户端行为,转发是服务器行为

总结

简单的登录小例子

示例代码

login.jsp

<%@ 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="dologin.jsp" method="post">
		账号:<input type="text" name="username"/><br/>
		密码:<input type="text" name="userpassword"/><br/>
		爱好:<br/>
		&emsp;&emsp;&emsp;唱<input type="checkbox" name="fun" value="1001"/>
		跳<input type="checkbox" name="fun" value="1002"/>
		Rap<input type="checkbox" name="fun" value="1003"/>
		篮球<input type="checkbox" name="fun" value="1004"/><br/>
		<input type="submit" value="提交"/>
	</form>
</body>
</html>

dologin.jsp

<%@ 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>
	<% 
	//解决post乱码设置
	request.setCharacterEncoding("utf-8");
	
	String uname = request.getParameter("username");
	String upwd = request.getParameter("userpassword");
	String[] fun = request.getParameterValues("fun");
	/* for (int i = 0; i < fun.length; i++) {
		out.print(fun[i]+"\t");
	} */
	
	request.setAttribute("uname", uname);
	request.setAttribute("upwd", upwd);
	request.setAttribute("fun", fun);
	//response重定向  不携带参数
	//response.sendRedirect("index.jsp");
	
	//request转发  携带参数
 	request.getRequestDispatcher("index.jsp").forward(request, response); 
	%>
</body>
</html>

index.jsp

<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ 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 uname = (String)request.getAttribute("uname");
		String upwd = (String)request.getAttribute("upwd");
		String[] fun = (String[])request.getAttribute("fun");
		out.print(uname + "成功登录,密码是:" + upwd + "爱好是:");
		for (int i = 0; i < fun.length; i++) {
			switch (fun[i]) {
			case "1001":
				out.print("唱" + "\t");
				break;
			case "1002":
				out.print("跳" + "\t");
				break;
			case "1003":
				out.print("Rap" + "\t");
				break;
			case "1004":
				out.print("篮球" + "\t");
				break;
			}
		}
	%>
	
	
	<%-- <%!	
	//写方法需要用<%!...的形式
		public void show() {}
	%>
	<%
	//简单的逻辑拼接写法
		List<String> list = new ArrayList<>();
		list.add("张三");
		list.add("李四");
		list.add("王五");

		for (int i = 0; i < list.size(); i++) {
	%>
			<ul>
				<li><%=list.get(i)%></li>
			</ul>	
	<%
		}
	%> --%>
</body>
</html>

使用session保存用户名

  • 使用会话对象session实现
    • 一个会话就是浏览器与服务器之间的一次通话
    • 会话可以在多次请求中保存和使用数据
public void setAttribute(String name, Object value);
//用法:
session.setAttribute("userName", "张三丰"); 

public Object getAttribute(String name);
//用法:
String userName=(String)session.getAttribute("userName");

会话的清除和过期

session的数据是在服务器端的,服务器保存的会话数据量会越来越大,从而导致性能问题

  • 若没有清理机制,会导致性能问题或服务器崩溃
    • 程序主动清除session数据
    • 服务器主动清除长时间没有再次发出请求的session
  • 程序主动清除session数据
    • 设置会话失效:session.invalidate();
    • 移除会话的一个属性
public void removeAttribute(String name); 
//用法:
session.removeAttribute("userName");
  • 服务器主动清除长时间没有再次发出请求的session

    • 设置会话过期时间

      • 方法一
      public void setMaxInactiveInterval(int interval); 	//单位:秒
      
      • 方法二
      <session-config>
             <session-timeout>30</session-timeout>
      </session-config>	//单位:分钟
      

使用cookie自动填写用户名

  • cookie以文件方式保存数据
    • 添加数据
      • public void addCookie(Cookie cookie)
    • 获取数据
      • public Cookie[] getCookies()
    • 设置有效期
      • public void setMaxAge(int expiry)
    • 用户可以禁用cookie

用法

//cookie的使用
//如果有中文
username = URLEncoder.encode(username,"utf-8");
Cookie cookie = new Cookie("username",username);
//设置路径,这个路径即该工程下都可以访问该cookie 如果不设置路径,那么只有设置该cookie路径及其子路径可以访问
cookie.setPath("/");
//设置cookie生命周期
cookie.setMaxAge(60*60);
response.addCookie(cookie);


//获取cookie
Cookie[] cookies = request.getCookies();
    if(cookies!=null && cookies.length!=0){
        for(int i=0;i<cookies.length;i++){
            System.out.println(cookies[i].getName());
            if(cookies[i].getName().equals("username")){
                username = cookies[i].getValue();
                username = URLDecoder.decode(username,"utf-8");
            }
        }
    }

简单示例

login.jsp:在登录页面进行接收Cookie的操作

<%@page import="java.net.URLDecoder"%>
<%@ 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 uname = "";
		String upwd = "";
		//用request获取cookie
		Cookie[] cookies = request.getCookies();
		if (cookies != null && cookies.length != 0) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals("username")) {
					//获得cookie值
					uname = cookie.getValue();
					//如果其值存在中文,就将其解码
					uname = URLDecoder.decode(uname,"utf-8");
				}
				if (cookie.getName().equals("upwd")) {
					//获得cookie值
					upwd = cookie.getValue();
				}

			}
		}
	%>

	<form action="dologin.jsp" method="post">
	
	<!-- 用value设置cookie默认值 -->
		账号:<input type="text" name="username" value="<%=uname%>"/><br/>	
		密码:<input type="text" name="userpassword" value="<%=upwd%>"/><br/>
        
        
		爱好:<br/>
		&emsp;&emsp;&emsp;唱<input type="checkbox" name="fun" value="1001"/>
		跳<input type="checkbox" name="fun" value="1002"/>
		Rap<input type="checkbox" name="fun" value="1003"/>
		篮球<input type="checkbox" name="fun" value="1004"/><br/>
		<input type="submit" value="提交"/>
	</form>
</body>
</html>

dologin.jsp:在处理登录页面进行添加Cookie的设置

<%@page import="java.net.URLEncoder"%>
<%@ 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>
	<% 
	//解决post乱码设置
	request.setCharacterEncoding("utf-8");
	
	String uname = request.getParameter("username");
	String upwd = request.getParameter("userpassword");
	String[] fun = request.getParameterValues("fun");
	/* for (int i = 0; i < fun.length; i++) {
		out.print(fun[i]+"\t");
	} */
	
	
		
	if (uname.equals("张三") && upwd.equals("111")) {
		//设置Cookie
		//如果Cookie中值存在中文,就将其编码设置成utf-8(也可能因为设置了反而乱码,看具体情况)
		String username = URLEncoder.encode(uname, "utf-8");
		Cookie cookie = new Cookie("username",username);
		//设置路径为根目录(方便使用)
		cookie.setPath("/");
		//设置cookie生命周期
		cookie.setMaxAge(20);	//s
		//添加cookie(response)
		response.addCookie(cookie);
		
		Cookie cookie1 = new Cookie("upwd",upwd);
		//设置路径为根目录(方便使用)
		cookie1.setPath("/");
		//设置cookie生命周期
		cookie1.setMaxAge(20);	//s
		//添加cookie(response)
		response.addCookie(cookie1);
		
		

		
		request.setAttribute("uname", uname);
		request.setAttribute("upwd", upwd);
		request.setAttribute("fun", fun);
		//response重定向  不携带参数
		//response.sendRedirect("index.jsp");
		
		
		
		//request转发  携带参数
	 	request.getRequestDispatcher("index.jsp").forward(request, response); 
	} else {
		response.sendRedirect("login.jsp");
	}
	
	%>
</body>
</html>

index.jsp:从dologin.jsp跳转后显示结果

<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ 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 uname = (String)request.getAttribute("uname");
		String upwd = (String)request.getAttribute("upwd");
		String[] fun = (String[])request.getAttribute("fun");
		out.print(uname + "成功登录,密码是:" + upwd + "爱好是:");
		for (int i = 0; i < fun.length; i++) {
			switch (fun[i]) {
			case "1001":
				out.print("唱" + "\t");
				break;
			case "1002":
				out.print("跳" + "\t");
				break;
			case "1003":
				out.print("Rap" + "\t");
				break;
			case "1004":
				out.print("篮球" + "\t");
				break;
			}
		}
	%>
	
	
	<%-- <%!	
	//写方法需要用<%!...的形式
		public void show() {}
	%>
	<%
	//简单的逻辑拼接写法
		List<String> list = new ArrayList<>();
		list.add("张三");
		list.add("李四");
		list.add("王五");

		for (int i = 0; i < list.size(); i++) {
	%>
			<ul>
				<li><%=list.get(i)%></li>
			</ul>	
	<%
		}
	%> --%>
</body>
</html>

application实现计数器

  • 分析
    • 每个用户都需要使用访问次数
    • application可在整个项目中共享使用数据
    • 使用application实现计数器
    • 每次访问该页面,计数器加1
  • 解决方法
    • public void setAttribute(String name, Object object)
    • public Object getAttribute(String name)

示例代码

<html>
<head>
<meta charset="UTF-8">
<title>计数器(刷新增加)</title>
</head>
<body>
	<% 
		int i = 1;	//设置初始值
		if (application.getAttribute("num") != null) {	//如果存入的值不为空,获取到值了
			//i则等于上次存入的值(i+1)
			i = Integer.parseInt(application.getAttribute("num").toString());
		}
		//在页面输出增加后的结果
		out.print(i);
		//将此次获取到的值+1
		i++;
		//将本次获得且增加后的值再次存入,在页面刷新后上面的application.getAttribute可以重新获取到
		application.setAttribute("num", i);
	%>
</body>
</html>

四大作用域

介绍

  • pageContext、request、session、application
    • 相同点
      • 都可以存储属性
    • 不同点
      • pageContext中存储的数据仅在当前页面中可用
      • request中存储的数据仅在一个请求中可用
      • session中存储的数据在一个会话的有效期内可用
      • application中存储的数据在整个Web项目中可用

示例代码

A.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>我是A页面</title>
</head>
<body>
	<h2 style="color:orange">我是A页面</h2>
	<%
	/*
	四大作用域
		pageContext		当前页面
		request			本次请求
		session			当前会话
		application		整个项目(当前服务器开关)
	*/
	
	
	//pageContext		当前页面
	String uname = "张三";
	pageContext.setAttribute("uname", uname);
	
	//request			本次请求
	request.setAttribute("uname", uname);
	
	//session			当前会话
	session.setAttribute("uname", uname);
	
	//application		整个项目(当前服务器开关)
	application.setAttribute("uname", uname);
	
	//转发
	request.getRequestDispatcher("B.jsp").forward(request, response);
	%>
</body>
</html>

B.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>我是B页面</title>
</head>
<body>
	<h2 style="color:orange">我是B页面</h2>
	<% 
		out.print("我是pageContext,我的值为:" + pageContext.getAttribute("uname"));	//因pageContext作用域只在当前页面,所以A.jsp的值无法被B.jsp获取到
	%><br/>
	<%
		out.print("我是request,我的值为:" + request.getAttribute("uname"));	
	%><br/>
	<%
		out.print("我是session,我的值为:" + session.getAttribute("uname"));
	%><br/>
	<%
		out.print("我是application,我的值为:" + application.getAttribute("uname"));
	%>
</body>
</html>

C.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>我是C页面</title>
</head>
<body>
	<h2 style="color:orange">我是C页面</h2>
	<% 
		out.print("我是pageContext,我的值为:" + pageContext.getAttribute("uname"));	//因pageContext作用域只在当前页面,所以A.jsp的值无法被B.jsp获取到
	%><br/>
	<%
		out.print("我是request,我的值为:" + request.getAttribute("uname"));	
	%><br/>
	<%
		out.print("我是session,我的值为:" + session.getAttribute("uname"));	//因session作用域在当前浏览器,所以关闭当前浏览器页面后才无法获取值(不过当前开多少个浏览器窗口都可以获取到),不过也可以手动设置session会话失效时间
		//session设置失效时间,5秒后自动清除session,这时session的id也会改变
		 session.setMaxInactiveInterval(5); 	//单位:秒
	%>
	&emsp;&emsp;&emsp;&emsp;
	<%
		out.print("session的id为:" + session.getId());
	%>
	<br/>
	<%
		out.print("我是application,我的值为:" + application.getAttribute("uname"));	//因application作用域只在当前服务器,所以需停止服务器之后才无法获取值
	%>
</body>
</html>

D.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>我是D页面</title>
</head>
<body>
	<h2 style="color:orange">我是D页面</h2>
	清除session	<!-- 只删除值,不删除session的id -->
	<%
	//清除session
	//session.removeAttribute("uname");
	//清除所有session
	session.invalidate();
	%>
</body>
</html>
  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Tuerlechat,

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值