jsp使用session、Cookie登录状态验证

一,session登录状态验证

1.登录界面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!--登录界面  -->
<form action="logonServlet.do" method="post">
	<div>
		账户名:<input type='text' name="oname"/>
	</div>
	<div>
		密码:<input type="password" name="opwd"/>
	</div>
	<button>登录</button>
</form>
</body>
</html>

2.登录servlet程序

servlet自己需要配置web.xml哦 

package com.jmh.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.jmh.dao.Tb_LogonDao;
import com.jmh.entity.Tb_Logon;

/**
 * 登录
 *
 */
public class LogonServlet extends HttpServlet{
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	this.doGet(req, resp);
	}
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	//设置编码
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
	//获取out、session对象
		PrintWriter out = resp.getWriter();
		HttpSession session = req.getSession();
	//处理业务逻辑代码
		//获取传入过来的值
		String oname = req.getParameter("oname");
		String opwd = req.getParameter("opwd");
		//实例化实体类
		Tb_Logon lo=new Tb_Logon(oname, opwd);
		//实例化方法类
		Tb_LogonDao tbl=new Tb_LogonDao();
		try {
			boolean logon = tbl.Logon(lo);
			if(logon) {//登录成功
				//登录状态:登录成功后把用户名传入给session作用域
				session.setAttribute("oname", oname);
				req.getRequestDispatcher("登录成功后要跳转的页面").forward(req, resp);
			}else {//登录失败
				out.print("<script>alert('登录失败!');location.href='登录失败后要跳转的页面'</script>");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}

3.session判断登录状态

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!--判断登录状态  -->
	<%
	String str=(String)session.getAttribute("oname");
	if(null==str){//没有登录
		out.print("<script>alert('请先登录!');location.href='自动跳转到登录界面';</script>");
	}
	%>
</body>
</html>

4.跳转指定页面session判断登录状态(登录过就可以访问/反之)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!--判断登录状态  引入判断登录session状态页面-->
<%@ include file="sessionLogon.jsp" %>
<!-- 主页 -->
<h1>登录成功!</h1>
</body>
</html>

二,Cookie登录状态验证

1.登录界面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!--登录界面  -->
<form action="logonServlet.do" method="post">
	<div>
		账户名:<input type='text' name="oname"/>
	</div>
	<div>
		密码:<input type="password" name="opwd"/>
	</div>
	<button>登录</button>
</form>
</body>
</html>

2.登录servlet程序

 servlet自己需要配置web.xml哦 

package com.jmh.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.jmh.dao.Tb_LogonDao;
import com.jmh.entity.Tb_Logon;

/**
 * 登录
 *
 */
public class LogonServlet extends HttpServlet{
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	this.doGet(req, resp);
	}
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	//设置编码
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
	//获取out、session对象
		PrintWriter out = resp.getWriter();
		HttpSession session = req.getSession();
	//处理业务逻辑代码
		//获取传入过来的值
		String oname = req.getParameter("oname");
		String opwd = req.getParameter("opwd");
		//实例化实体类
		Tb_Logon lo=new Tb_Logon(oname, opwd);
		//实例化方法类
		Tb_LogonDao tbl=new Tb_LogonDao();
		try {
			boolean logon = tbl.Logon(lo);
			if(logon) {//登录成功
				//使用Cookie
				Cookie ck=new Cookie("oname", oname);
				resp.addCookie(ck);//将Cookie对象输出客户端
				resp.sendRedirect("登录成功后跳转指定的页面");
			}else {//登录失败
				out.print("<script>alert('登录失败!');location.href='登录成功后跳转指定的页面'</script>");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}

3.Cookie判断登录状态

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!--Cookie登录判断验证  -->
<%	
	boolean f=false;
	//获取所有Cookie
	Cookie[] ck= request.getCookies();
	//遍历Cookie
	for(Cookie c : ck){
		//非空判断
		if(null!=c){
			if(c.getName().equals("oname")){
				f=true;//已经登录
				break;
			}
		}
	}
	if(f==false){
		out.print("<script>alert('请先登录!');location.href='没有登录就自动跳转到登录界面';</script>");
	}
%>
</body>
</html>

4.跳转指定页面Cookie判断登录状态(登录过就可以访问/反之)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!--判断登录状态  引入判断登录Cookie状态页面-->
<%@ include file="cookieLogon.jsp" %> 
<!-- 主页 -->
<h1>登录成功!</h1>
</body>
</html>

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JavaWeb中,Session是一种保存在服务器端的数据对象,用于保存用户会话信息。可以通过Session实现用户登录功能,具体步骤如下: 1. 用户输入用户名和密码,提交表单到服务器端。 2. 服务器端接收到表单数据后,验证用户名和密码是否正确。 3. 如果用户名和密码正确,则在服务器端创建一个Session对象,并将用户信息保存到Session中,如用户ID、用户名等。 4. 将Session ID返回给客户端浏览器,通常是通过cookie方式保存Session ID。 5. 用户进行其他操作时,浏览器会将保存的Session ID发送给服务器端,服务器端可以通过Session ID获取到对应的Session对象,从而获取到用户信息。 6. 当用户退出登录时,服务器端可以通过invalidate方法将Session对象销毁,从而清除用户信息。 在实现用户登录时,需要注意以下几点: 1. 用户密码不能明文存储,应该加密存储或使用哈希函数存储。 2. Session ID应该设置为随机字符串,以避免被猜测。 3. Session对象中保存的用户信息应该尽量少,以减少网络流量和服务器内存占用。 4. 应该设置Session过期时间,以避免Session长时间存在导致安全风险和服务器资源浪费。 示例代码如下: ```java // 用户登录验证 if (checkUser(username, password)) { // 登录成功,创建Session对象 HttpSession session = request.getSession(true); // 设置Session过期时间为30分钟 session.setMaxInactiveInterval(30 * 60); // 将用户信息保存到Sessionsession.setAttribute("userId", userId); session.setAttribute("username", username); // 将Session ID保存到cookieCookie cookie = new Cookie("JSESSIONID", session.getId()); cookie.setMaxAge(30 * 60); response.addCookie(cookie); // 跳转到主页 response.sendRedirect("index.jsp"); } else { // 登录失败 response.sendRedirect("login.jsp?error=1"); } ``` 在上面的示例代码中,如果用户登录成功,则创建一个Session对象,并将用户ID和用户名保存到Session中,同时将Session ID保存到cookie中。如果用户登录失败,则重定向到登录页面,并在URL中添加error参数,以提示用户登录失败。在JSP页面中,可以通过EL表达式和Session对象获取用户信息,如下所示: ```jsp <%-- 获取Session中的用户信息 --%> <% String userId = (String) session.getAttribute("userId"); String username = (String) session.getAttribute("username"); %> <%-- 显示用户信息 --%> <p>欢迎您,<c:out value="${username}" /></p> ``` 在上面的示例代码中,使用JSP页面中的EL表达式和<c:out>标签,从Session中获取用户信息,并将其显示在页面上。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值