验证用户是否已经登录与实现自动登录 (50)

验证用户是否已经登录

package cn.hongxin.filter;

import java.io.IOException;

import javax.servlet.Filter;

import javax.servlet.FilterChain;

import javax.servlet.FilterConfig;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

public class LoginFilter implements Filter{

public void init(FilterConfig filterConfig) throws ServletException {

}

public void doFilter(ServletRequest request, ServletResponse response,

FilterChain chain) throws IOException, ServletException {

//将request强转成htt...

HttpServletRequest req = (HttpServletRequest) request;

//获取session

HttpSession ss = req.getSession();

//从session中获取user

if(ss.getAttribute("user")==null){

System.err.println("你还没有登录");

req.getSession().setAttribute("msg", "请你先登录");

//重定向到登录

HttpServletResponse resp = (HttpServletResponse) response;

resp.sendRedirect(req.getContextPath()+"/index.jsp");[W2]

}else{

//放行

chain.doFilter(request, response);

}

}

public void destroy() {

}

}

配置到web.xml中且对jsps/*进行过虑:

<filter>

<filter-name>login</filter-name>

<filter-class>cn.itcast.filter.LoginFilter</filter-class>

</filter>

<filter-mapping>

<filter-name>login</filter-name>

<url-pattern>/jsps/*</url-pattern>

<url-pattern>/views/*</url-pattern>

</filter-mapping>


实现自动登录

自动登录,是为了帮助用户多次使用这个网页时,不用再次输入用户名和密码就可以登录。

是指用户将用户的登录信息,人,保存到本地的文件中Cookie中。

Name,value – 声明时 new Cookie(key,value);

Path        - 默认值,即为当前保存cookie的这个serlvet所在的路径。

如果Cookie在这样的路径:http://loclhost:8080/project/abc/AServlet

则Cookie的路径为: http://loclhost/project/abc

则说明:

所在在http://loclhost/project/abc目录下的servlet才可以读取这个cookie的值。

如果:

保存Cookie类:http://loclhost:8080/project/a/b/AServlet

则Cookie的默认path为;

http://loclhost/project/a/b

第一步:开发一个登录页面

<c:choose>

<c:when test="${empty sessionScope.name}">

<form name="x" method="post" action="<c:url value=‘/LoginServlet‘/>">

Name:<input type="text" name="name"/><br/>

auto:

<input type="radio" name="auto" value="-1">不自动登录

<br/>

<input type="radio" name="auto" value="1">1天<br/>

<input type="radio" name="auto" value="7">1周<br/>

<input type="submit"/>

</form>

</c:when>

<c:otherwise>

你已经登录了:${name}<br/>

<a href="<c:url value=‘/LoginServlet‘/>">退出</a>

</c:otherwise>

</c:choose>

第二步:成功保存cookie

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

//接收用户姓名

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

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

//将用户信息放到session

request.getSession().setAttribute("name",name);

//判断auto是否是-1

if(!auto.equals("-1")){

int day = Integer.parseInt(auto);//1|7

int seconds = 60*60*24*day;

//声明cookie

Cookie c = new Cookie("autoLogin",name);

c.setMaxAge(seconds);

c.setPath(request.getContextPath());

//保存cookie

response.addCookie(c);

}

}

第三步:要求访问本网点中任何一个页面都应该实现自动登录

写一个过虑器,对所有url=/*进行过虑。在doFilter中读取所有cookie。是否存在名称为autoLogin的名称cookie。

永远都放行。

public void doFilter(ServletRequest request, ServletResponse response,

FilterChain chain) throws IOException, ServletException {

//在这儿读取cookie

HttpServletRequest req = (HttpServletRequest) request;

//获取所的有cookie

Cookie[] cs = req.getCookies();

if(cs!=null){

for(Cookie c:cs){

if(c.getName().equals("autoLogin")){//如果存在自动登录的cookie

String value = c.getValue();//用户名称

//登录成功是指

req.getSession().setAttribute("name", value);

break;

}

}

}

//不管是否自动登录成

chain.doFilter(request, response);

}

第四涉:配置到web.xml中对所有url=/*

<filter>

<filter-name>auto</filter-name>

<filter-class>cn.itcast.filter.AutoFilter</filter-class>

</filter>

<filter-mapping>

<filter-name>auto</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

第五步:开发退出

System.err.println("用户退出");

//删除整个session

request.getSession().invalidate();

Cookie c = new Cookie("autoLogin", "ddd");

c.setMaxAge(0);

c.setPath(request.getContextPath());

response.addCookie(c);

//     request.getSession().removeAttribute("name");

response.sendRedirect(request.getContextPath()+"/index.jsp");

第六步:优化代码

由于用户在做手工登录时,也会进入AutoFiilter的doFilter方法,且读取所有Cookie遍历一次。而这次遍历对用户来说是多余。

所以应该将LoginServet这个url在doFiler中不过过虑。

且对退出也不能自动登录。

时间: 2024-08-26 19:36:58

验证用户是否已经登录与实现自动登录 (50)的相关文章

JavaEE之--------利用过滤器实现用户自动登录,安全登录,取消自动登录黑用户禁止登录

在我们生活中,对于账户的自动登录已经很常见了,所以利用过滤器实现这个功能 主要介绍用户的自动登录和取消自动登录,以及实现一天自动登录或者n天实现自动登录,当用户ip被加入到黑名单之后,直接利用过滤器返回一个警告页面. 过滤器的功能很是强大,我们只需要在写好的前台后servlet之后进行添加就可以实现这个功能 Ps:这个仅仅只是一个演示而已,里面的访问数据库的部分,自己随意模拟了下,主要是突出实现自动登录的功能. 前台代码: 前台代码是成功与否都在这个页面显示.用到的技术:jstl标签的应用,se

php登录页面cookie自动登录及验证

<?php //cookie实现自动登录 error_reporting(0);// 关闭错误报告(浏览页面出现notice可用此法消除) $user = $_POST['username'];$pwd = $_POST['password'];if ($user!=''&&$pwd!=''){if($_POST['remmber']==1){ header("Location:http://localhost/homework/login.php"); //转到

如何设置phpMyAdmin自动登录和取消自动登录

如何设置phpMyAdmin自动登录? 首先在根目录找到config.sample.inc.php复制一份文件名改为config.inc.php(如果已经存在 config.inc.php 文件,则直接修改该文件即可). 打开config.inc.php 找到 $cfg['Servers'][$i]['auth_type'],将 $cfg['Servers'][$i]['auth_type'] = 'cookie'; 改成 $cfg['Servers'][$i]['auth_type'] = '

phpmyadmin设置自动登录和取消自动登录

1首先在phpmyadmin安装目录下找到config.sample.inc.php复制一份文件名改为config.inc.php 2打开config.inc.php 找到 $cfg['Servers'][$i]['auth_type'],将其改为 [html] view plain copy $cfg['Servers'][$i]['auth_type'] = 'config'; 3在下面添加一些代码,phpmyadmin的用户名和密码 [html] view plain copy $cfg[

线程阻塞问题-功能:环信登录失败后自动登录5次

项目中集成了环信,点击联系客服时需要调取环信的接口,现在有个要求,如果调取环信的登录接口失败了,就要重新登录,但是这个操作不能影响主线程的操作,登录次数达到一定的数量后停止登录.首先:环信的登录时同步的,需要我们开启一个线程,不然当环信登录失败时会很容易造成界面卡死的情况.+ (void)loginWithSuccessBlock:(void(^)())success FailureBlock:(void(^)())failure{   // 自己封装的一个公共类 // 开启一个线程防止登录失败

登录模块(自动登录)

render里面要直接跳到某个页面要用return <Redirect to="/" />   不用this.props.history.replace('/');  因为render里面必定return this.props.history.replace用在点击回调事件里面 1.admin.js里面 <script> render() { //读取保存的user ,如果不存在直接跳转到登录页面 const user = JSON.parse(localSto

JavaWeb-过滤器Filter学习(三)实现用户的自动登录与IP黑名单过滤

实现用户的自动登录: 解决方案: 设置一个全站拦截的过虑器. 在此过虑器中,读取用户带过来的Cookie信息,然后从中读取用户的用户名和密码,自动帮助用户登录. 即可实现自动登录功能. 用Filter验证用户是否已经登录过.已经登录过了,我们就根据他选择的自动登录来选择让他在多久内能自动登录. IP黑名单过滤就很简单了,只要在Filter过滤器防范一下就OK. 在init方法中,我们先把黑名单的IP加载进Set<String> set集合, Set集合有如下特点: Java.util.Hash

cookie技术实现自动登录+验证用户名输入是否正确

login页面 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+requ

尝试用户自动登录

//尝试用户自动登录 /// <summary> /// 尝试自动登录 或填充密码 /// </summary> /// <param name="context"></param> /// <returns>自动登录后的状态:成功,填充密码,失败继续</returns> public static ConstStringHelper.AutoLoginResult TryAutoLoginOrMemoryPwd(