通常我们在点击某个按钮的时候,对某个对象进行操作,是需要登陆才能做的,这时候就需要一个拦截器对某个方法进行拦截,

比如你在一个图书管理中心中你要借书,这时候你就会被要求出示借书证,管理员才能借书给你。而拦截器就具有这样的功能

:游客点击借书按钮-->后台拦截器拦截该方法-->判断你是否登陆-->已经登陆-->允许操作-->没登陆-->请登陆-->允许操作

代码如下:

UserFiler.java

package com.utis.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 UserFiter implements Filter{ public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub } public void destroy() {
// TODO Auto-generated method stub } public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
//获取HttpSession对象,判断是否登陆
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
HttpSession session = req.getSession(); if(session.getAttribute("model")==null){
//非法访问,没有登陆,跳转到登陆页面
session.setAttribute("error", "非法访问");
// 保存客户想要去的地址, 登录成功后则直接跳转,而不是到首页
String goURL = req.getServletPath();//(获取到地址不包括参数)
//判断参数是否为空,不null就获取参数
if(req.getQueryString()!=null){
goURL+="?"+req.getQueryString();
}
session.setAttribute("goURL", goURL);
res.sendRedirect(req.getContextPath() + "/user/userLogin.jsp");
}else{
// 如果有下一个过滤器则跳转到下一个过滤器否则目标页面
chain.doFilter(request, response);
}
} }

web.xml

	<filter>
          <!-- 配置在web.xml的拦截器,在容器启动的时候一起启动 -->
<filter-name>userFilter</filter-name>
<filter-class>com.utis.filter.UserFiter</filter-class>
</filter>
<filter-mapping>
<filter-name>userFilter</filter-name>
<url-pattern>/book/*</url-pattern>
</filter-mapping>

UserContrller.java

	/**
* 用户登陆功能
* @return
*/
@RequestMapping(value="login",method=RequestMethod.POST)
public ModelAndView userLogin(@Valid User user,HttpServletRequest request,HttpServletResponse response){
Map<String, Object> maplist = new HashMap<String, Object>();
HttpSession session = request.getSession();
User model = userService.findUser(user);
if(model != null && !model.equals("")){
session.setAttribute("model", model);
maplist.put("model", model);
return new ModelAndView("index","maplist",maplist); }else{
request.setAttribute("message", "用户或密码错误!");
return new ModelAndView("user/userLogin");
}
}

userLogin.jsp

<html>
<head>
<title>登陆页面</title>
</head> <body>
<center>
<h1>登陆页面</h1>
<table>
<form action="login" method="post">
用户名:<input type="text" class="username" name="username"/><br/>
密  码:<input type="password" class="password" name="password"/><br/>
<input type="submit" value="登陆"><br/>
</form>
${message}
</table>
</center>
</body>
</html>

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>首页</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head> <body> <CENTER>
<h1>图书首页</h1>
<c:choose>
<c:when test="${empty sessionScope.model}">
<a href="<%=basePath%>user/userLogin.jsp">登陆</a>
<a href="<%=basePath%>user/userRegister.jsp">注册</a>
</c:when>
<c:otherwise>
欢迎使用图书管理系统:${sessionScope.model.username }
</c:otherwise>
</c:choose> <c:if test="${booklist ne '' && booklist != null}">
<!-- 作为隐藏的传递参数 -->
<table border="1"
style="border-collapse: collapse; border-color: blue;">
<!-- 表头 -->
<tr>
<th>
书名
</th>
<th>
出版社
</th>
<th>
是否可借
</th>
<th>
数量
</th>
<th>
操作
</th>
</tr>
<!-- 显示数据列表 -->
<c:forEach items="${booklist}" var="book">
<tr>
<td>
${book.bookname }
</td>
<td>
${book.chubanshe }
</td>
<td>
${book.state }
</td>
<td>
${book.number }
</td>
<td>
<a
href="book/borrowBook?bookid=${book.bookid }&userid=${sessionScope.model.userid }">借书</a>
</td>
</tr>
</c:forEach> <!-- 其他操作 -->
<tr>
<td colspan="7">
<a href="#">添加</a>
</td>
</tr>
</table>
</c:if>
</CENTER>
</body>
</html>

初始化数据

IniDataListener.java

package com.booksys.listener;

import java.util.Timer;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener; import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils; import com.booksys.service.BookService;
import com.utis.util.GoodsTimerTask;
/**
* 该类的主要作用是用于加载index首页的方法,查询数据,显示首页
* @author chunyu
*
*/
public class InitDataListener implements ServletContextListener{ private BookService bookService;
private GoodsTimerTask goodsTimerTask; public void contextDestroyed(ServletContextEvent sce) { } public void contextInitialized(ServletContextEvent event) {
ApplicationContext context = null;
//通过spring的web工具类来加载spring容器(配置文件),并且调用某个类来做某事
context=WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
//1、获取bookservice
bookService = (BookService) context.getBean("bookService");
goodsTimerTask = (GoodsTimerTask) context.getBean("goodsTimerTask");
//2、查询所有图书
event.getServletContext().setAttribute("booklist", bookService.findBook());
//将Application内置对象,传入到goodsTimerTask查询的数据对象中
goodsTimerTask.setApplication(event.getServletContext());
// 设置时间任务,每隔一段时间加载首页的商品信息, 此线程必须设置守护线程, 主线程停止的时候此线程也要停止
new Timer(true).schedule(goodsTimerTask, 0,1000*60); } }

web.xml

	<!-- 初始化首页信息(查询)监听器 -->
<listener>
<listener-class>
com.booksys.listener.InitDataListener
</listener-class>
</listener>

时间戳:用于自动调用查询方法,更新首页数据显示

GoodsTimerTask.java

package com.utis.util;

import java.util.List;
import java.util.TimerTask; import javax.annotation.Resource;
import javax.servlet.ServletContext; import org.springframework.stereotype.Component; import com.booksys.domain.Book;
import com.booksys.service.BookService; @Component("goodsTimerTask")
public class GoodsTimerTask extends TimerTask { //传入Application内置对象
private ServletContext application; public void setApplication(ServletContext application) {
this.application = application;
} //获取业务逻辑类
@Resource
private BookService bookService=null; @Override
public void run() {
System.out.println("GoodsTimerTask.run()");
//首页加载图书数据信息
List<Book> booklist = bookService.findBook();
//将list集合数据存储到app内置对象中,在inde前台通过循环查询出来
application.setAttribute("booklist", booklist);
}
}

Java代码登录拦截器例子的更多相关文章

  1. Java结合SpringBoot拦截器实现简单的登录认证模块

    Java结合SpringBoot拦截器实现简单的登录认证模块 之前在做项目时需要实现一个简单的登录认证的功能,就寻思着使用Spring Boot的拦截器来实现,在此记录一下我的整个实现过程,源码见文章 ...

  2. Java三大器之拦截器(Interceptor)的实现原理及代码示例

    1,拦截器的概念    java里的拦截器是动态拦截Action调用的对象,它提供了一种机制可以使开发者在一个Action执行的前后执行一段代码,也可以在一个Action执行前阻止其执行,同时也提供了 ...

  3. 大型运输行业实战_day05_1_登录+注销+表单重复提交+登录拦截器

    1.登录 登录实现如下步骤: 1.在首页中添加登录按钮 html代码如下: <%@ page contentType="text/html;charset=UTF-8" la ...

  4. 用户登录拦截器查询到登录用户后如何将用户信息传递到后面的Controller

    taotao创建订单代码中之前忘了加入用户信息,那么加上呢? 分析:用户创建订单的时候,我们会强制要求用户先登录,也就是说,创建订单的Controller执行时,一定是用户已经登录了的,而用户只要登录 ...

  5. Spring mvc登录拦截器

    自己实现的第一个Spring mvc登录拦截器 题目要求:拒绝未登录用户进入系统,只要发现用户未登录,则将用户请求转发到/login.do要求用户登录 实现步骤: 1.在spring的配置文件中添加登 ...

  6. sessionStorage记录返回前端的数据,用于解决登录拦截器刷新页面的问题

    1.问题出现的场景与解决 实现一个登录拦截器,重写doFilter方法,判断用户的登录状态,在用户长时间未操作或者异地登录时前端进行提示,完整代码如下 public class LoginValida ...

  7. struts2自定义登录拦截器

    版权声明:本文为博主原创文章,未经博主允许不得转载. (1)配置web.xml,让xml加载struts2框架 <?xml version="1.0" encoding=&q ...

  8. Struts2 在登录拦截器中对ajax请求的处理

    前言: 由于ajax请求不像http请求,可以直接进行页面跳转,你返回的所有东西,ajax都只会识别为一个字符串. 之前尝试的方法是在拦截器中返回一个标识给ajax,然后再在每一个ajax请求成功之后 ...

  9. 【java web】拦截器inteceptor

    一.简介 java里的拦截器提供的是非系统级别的拦截,也就是说,就覆盖面来说,拦截器不如过滤器强大,但是更有针对性. Java中的拦截器是基于Java反射机制实现的,更准确的划分,应该是基于JDK实现 ...

随机推荐

  1. 用C++向一个txt文档中写数据

    bool CMaked::WriteFileMake(CString filePath, const char *isChange) { ofstream file; //filePath为该txt文 ...

  2. BZOJ_1009_[HNOI2008]GT考试_KMP+矩阵乘法

    BZOJ_1009_[HNOI2008]GT考试_KMP+矩阵乘法 Description 阿申准备报名参加GT考试,准考证号为N位数X1X2....Xn(0<=Xi<=9),他不希望准考 ...

  3. BZOJ_1552_[Cerc2007]robotic sort_splay

    BZOJ_1552_[Cerc2007]robotic sort_splay 题意: 分析: splay维护区间操作 可以先把编号排序,给每个编号分配一个固定的点,映射过去 查找编号的排名时先找到这个 ...

  4. 查看Linux下系统资源占用常用命令(top、free、uptime)

    本文介绍下,在linux中查看系统资源占用的三个命令:top.free.uptime,通过实例学习下它们的用法,有需要的朋友参考下 一,top命令 1.作用top命令用来显示执行中的程序进程,使用权限 ...

  5. MySQL(七)DQL之分组查询

    一.语法 select 分组函数,分组后的字段from 表[where 筛选条件]group by 分组的字段[having 分组后的筛选][order by 排序列表] 二.特点 分组前筛选:whe ...

  6. Bug的严重等级和优先级别与分类

    一. Bug的严重等级定义: 1. Blocker 即系统无法执行.崩溃或严重资源不足.应用模块无法启动或异常退出.无法测试.造成系统不稳定. 严重花屏 内存泄漏 用户数据丢失或破坏 系统崩溃/死机/ ...

  7. 你真的了解ASP.NET Core 部署模型吗?

    ----------------------------   以下内容针对 ASP.NET Core2.1,2.2出现IIS进程内寄宿 暂不展开讨论-------------------------- ...

  8. Javascript的内存泄漏分析

    作为程序员(更高大尚的称谓:研软件研发)的我们,无论是用Javascript,还是.net, java语言,肯定都遇到过内存泄漏的问题.只不过他们都有GC机制来帮助程序员完成内存回收的事情,如果你是C ...

  9. 基于Unity的AR开发初探:第一个AR应用程序

    记得2014年曾经写过一个Unity3D的游戏开发初探系列,收获了很多好评和鼓励,不过自那之后再也没有用过Unity,因为没有相关的需求让我能用到.目前公司有一个App开发的需求,想要融合一下AR到A ...

  10. Nuget(BagGet)使用教程

    Nuget(BagGet)使用教程 1. 服务器安装ASP.NET Core 网上有很多教程,不多讲,链接给你:https://www.cnblogs.com/Agui520/p/8331499.ht ...