其中包含两个jsp文件,分别为login.jsp和index.jsp
代码如下:
login.jsp
<%@ 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>登录界面</title> </head> <body> <form action="index.jsp" method="post"> 用户名:<input type="text" name="name"/> <input type="submit" value="提交"/> </form> </body> </html>
index.jsp
<%@ 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>欢迎您</title> </head> <body> <% string name = request.getparameter("name"); if(name != null && !name.trim().equals("")){ cookie cookie = new cookie("name",name); cookie.setmaxage(30); //设置cookie有效期为30s response.addcookie(cookie); }else{ cookie[] cookies = request.getcookies(); if(cookies != null && cookies.length > 0){ for(cookie cookie:cookies){ string cookiename = cookie.getname(); if("name".equals(cookiename)){ string val = cookie.getvalue(); name = val; } } } } if(name != null && !name.trim().equals("")){ out.print("hello: " + name); }else{//否则重定向到登录界面 response.sendredirect("login.jsp"); } %> </body> </html>
以上所述是小编给大家介绍的javaweb使用cookie模拟实现自动登录功能,希望对大家有所帮助
如对本文有疑问, 点击进行留言回复!!
荐 深入理解Java中的BigInteger和 BigDecimal,再也不怕面试了
tomact正常启动,但是在日志文件报错java.lang.NoClassDefFoundError: java/util/logging/Logger
servlet整合quartz:servlet中使用quartz,服务器启动时加载任务
荐 Java——集合中的Map接口通过HashMap类实现一些常用的方法
SpringBoot整合mybatis访问时报错Invalid bound statement (not found)
网友评论