JavaWeb 使用Filter实现自动登录

思路

使用cookie存储账号、密码,使用Filter拦截,从cookie中取出账号、密码。若用户要注销|登出、不再想使用自动登录,将cookie的有效期设置为0即可。

浏览器可以查看Cookie,不能直接存储账号、密码的明文,使用Cookie存储账号、密码时需要加密,从Cookie中取出来时需要解密。

每次HTTP请求都使用Filter拦截,从Cookie中解密出账号、密码,每次都要解密,浪费时间。第一次从Cookie中解密出账号、密码后,可以将账号、密码放到session域中,会话期间直接从session中取,不必再解密。

登录页面

用户名:

密码:

登录

${requestScope.errorMsg}

EL表达式没有空指针异常,没有时返回空串。所以没有errorMsg时, ${requestScope.errorMsg} 也不会出错。

将登录页面设为项目初始页面

/login.jsp

处理登录表单的Servlet

1 @WebServlet("/loginServlet")

2 public class LoginServlet extends HttpServlet {

3 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

4 String user=request.getParameter("user");

5 String pwd=request.getParameter("pwd");

6

7 //连接数据库,检查是否正确

8 //......

9 if (true){

10 //放到session中

11 HttpSession session = request.getSession();

12 session.setAttribute("user",user);

13 session.setAttribute("pwd","pwd");

14

15 //将值加密后存储在Cookie中,此处略过加密

16 Cookie cookie=new Cookie("autoLogin",user+"-"+pwd);

17 //整个项目中可用

18 cookie.setPath(request.getContextPath());

19 //这个域名地址下的所有webApp都可用

20 //cookie.setPath("/");

21 cookie.setMaxAge(60*60*24*7);

22 response.addCookie(cookie);

23

24 //重定向到目标页面。request.getContextPath()获取的是当前web应用的根目录

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

26 //不能这样写,这样写表示域名下的index.jsp,不是域名/web应用/index.jsp。

27 //response.sendRedirect("/index.jsp");

28 }

29 else{

30 //转发到登录页面,附加错误信息

31 request.setAttribute("errorMsg","账户名或密码错误");

32 request.getRequestDispatcher("/login").forward(request,response);

33 }

34

35 }

36

37 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

38 doPost(request,response);

39 }

40 }

首页

hello,${sessionScope.user}

Filter实现自动登录

1 @WebFilter("/*")

2 public class HandlerFilter implements Filter {

3 public void destroy() {

4 }

5

6 public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

7 //统一全站编码

8 req.setCharacterEncoding("utf-8");

9 resp.setContentType("text/html;charset=utf-8");

10

11 //ServletRequest不能获取session、cookie,需要强转为HttpServletRequest

12 HttpServletRequest httpReq = (HttpServletRequest) req;

13

14 //检查session中有没有用户信息

15 HttpSession session = httpReq.getSession();

16 if (session.getAttribute("user")==null){

17 //如果session中没有,从Cookie中找autoLogin。可能是会话结束后再次访问,比如离开网站30min(session默认超时时间)后再次访问、关闭浏览器后重新打开再次访问。

18 Cookie[] cookies = httpReq.getCookies();

19 //需要先检测cookies是否为null,为null时会报空指针异常

20 if (cookies!=null){

21 for (Cookie cookie:cookies){

22 if (cookie.getName().equals("autoLogin")) {

23 //需要先解密,此处略过

24 //......

25 String[] userInfo=cookie.getValue().split("-");

26 session.setAttribute("user",userInfo[0]);

27 session.setAttribute("pwd",userInfo[1]);

28 }

29 }

30 }

31 }

32

33 chain.doFilter(req, resp);

34 }

35

36 public void init(FilterConfig config) throws ServletException {

37

38 }

39

40 }

ServletRequest不能获取session、cookie,需要强转为HttpServletRequest才可以。

处理注销 | 登出 | 不再使用自动登录 的Servlet

1 @WebServlet("/logoutServlet")

2 public class LogoutServlet extends HttpServlet {

3 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

4 //从session中移出用户信息

5 HttpSession session = request.getSession();

6 session.removeAttribute("user");

7 session.removeAttribute("pwd");

8

9 //删除Cookie,此处采用同名覆盖,也可以遍历获取,再将有效期设为0

10 Cookie cookie=new Cookie("autoLogin","");

11 cookie.setPath(request.getContextPath());

12 cookie.setMaxAge(0);

13 response.addCookie(cookie);

14 }

15

16 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

17 doPost(request,response);

18 }

19 }

获取当前WebApp的根目录:

String path1 = request.getContextPath(); //通过request对象来获取

String path2 = getServletContext().getContextPath(); //通过ServletContext对象来获取

这2种方式获取的都是相对路径。

获取当前WebApp中的某个资源在服务器上的绝对路径:

String path3 = getServletContext().getRealPath("/index.jsp"); //通过ServletContext对象来获取

就是把当前项目的根目录(绝对路径)、参数中的路径拼接在一起。

java拦截到登陆界面,JavaWeb 使用Filter实现自动登录相关推荐

  1. Java实现QQ登陆界面的搭建

    仿QQ登陆界面 界面显示 界面布局 响应事件 仿QQ登陆界面实现 1.界面显示 界面显示的两种方法 创建JFrame对象 import java.awt.Color; import javax.swi ...

  2. java版本qq登陆界面_java实现QQ登陆界面

    以下是效果截图: 素材: 以下是源代码: import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.Mous ...

  3. java实现QQ登陆界面

    以下是效果截图:   素材:          以下是源代码: import java.awt.*; import java.awt.event.MouseEvent; import java.awt ...

  4. Filter 过滤器 自动登录

                                                        Filter 过滤器 : 其实就是对客户端发出来的请求进行过滤. 浏览器发出, 然后服务器派se ...

  5. JavaWeb使用过滤器实现自动登录功能

    登录前: 登录后: 思维导图: 总结一下: 1.第一次访问主页:经过过滤器,此时无cookie,无session,则会进入登陆页面,执行完登陆,会把用户信息写入cookie发送到客户端,同时写入ses ...

  6. Matlab模拟登陆网页,转:使用matlab自动登录网站(人人网、新浪微博)代码

    使用matlab自动登录网站(人人网.新浪微博)代码 标题听上去很怪哈...其实意思就是用matlab自动填表单--自动填写账号,密码,然后模拟点击登录. 希望能够起到抛砖引玉的作用,登录其他邮箱什么 ...

  7. 使用Filter过滤器自动登录功能

    实现思路 1.首先判断是否勾选了自动登录按钮(LoginServlet文件中进行判断) 2.在LoginServlet 创建一个cookie 将用户的登录账号与密码保存到其中 ,存到客户端 3.返回到 ...

  8. java 天猫模拟登陆_基于servlet+filter+反射模拟实现天猫首页的后端

    前言:为了深入web原理,本项目没有使用框架,主要描述了从请求到页面展现的思路,详情请见文末的具体项目 一.为什么要用filter?直接servlet实现不就行了 因为天猫这样的项目需要很多servl ...

  9. Java Swing用户登陆界面

    import javax.swing.*;import java.awt.*; //导入必要的包public class Home extends JFrame{private JPanel jPan ...

最新文章

  1. 一个公众号可以绑定几个小程序_如何实现微信小程序和公众号的绑定
  2. ORB-SLAM(八)ORBmatcher 特征匹配
  3. 数据中心网络性能:新应用下的新需求
  4. Mysql迁移到Oracle方法
  5. Tomcat 是怎么处理js file access request的
  6. 准确率、召回率、F1、mAP、ROC、AUC
  7. java项目短信群发接口_JAVA实现第三方短信发送过程详解
  8. SpringBoot查看和修改依赖的版本
  9. 无需付费,教你IDEA社区版中使用Tomcat
  10. 查阅 arXiv 论文新神器,一行代码比较版本差别,Github 新开源!
  11. 2016 - 2- 2 非正式协议与正式协议
  12. Echarts双纵轴分隔线合并解决方案
  13. java view template_Java设计模式之模板方法模式(Template Method)
  14. python 运行pyc_Pyc文件编译和运行
  15. How to extend a readonly property ?????
  16. 使用dbstart 和dbshut 脚本来自动化启动和关闭数据库
  17. 程序逻辑的处理方式尽量不要写在SQL文中
  18. matlab2019使用仿真,simulink视频教程仿真建模matlab2019高级
  19. Centos7安装jdk1.8
  20. 【芯片学习】X86 CPU 发展历史与分析——1971~2020——明白Intel架构的变迁

热门文章

  1. linux C++安装并编译boost库
  2. 解锁oracle数据库的 scott用户,亲身测试。success
  3. Linux下运行.cpp文件
  4. FALCON组装参数学习
  5. linux cuda 异常退出,cudaErrorCudartUnloading问题排查及建议方案
  6. c语言多线程的作用是什么意思,多线程-如何在普通C语言中启动线程?
  7. 四十二、文件的物理结构(下)
  8. 【ES6】ES6编程规范 编程风格
  9. APUE(第九章)进程关系
  10. php自动加载和实现方法,php 自动加载方法