Java代码登录拦截器例子
通常我们在点击某个按钮的时候,对某个对象进行操作,是需要登陆才能做的,这时候就需要一个拦截器对某个方法进行拦截,
比如你在一个图书管理中心中你要借书,这时候你就会被要求出示借书证,管理员才能借书给你。而拦截器就具有这样的功能
:游客点击借书按钮-->后台拦截器拦截该方法-->判断你是否登陆-->已经登陆-->允许操作-->没登陆-->请登陆-->允许操作
代码如下:
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代码登录拦截器例子的更多相关文章
- Java结合SpringBoot拦截器实现简单的登录认证模块
Java结合SpringBoot拦截器实现简单的登录认证模块 之前在做项目时需要实现一个简单的登录认证的功能,就寻思着使用Spring Boot的拦截器来实现,在此记录一下我的整个实现过程,源码见文章 ...
- Java三大器之拦截器(Interceptor)的实现原理及代码示例
1,拦截器的概念 java里的拦截器是动态拦截Action调用的对象,它提供了一种机制可以使开发者在一个Action执行的前后执行一段代码,也可以在一个Action执行前阻止其执行,同时也提供了 ...
- 大型运输行业实战_day05_1_登录+注销+表单重复提交+登录拦截器
1.登录 登录实现如下步骤: 1.在首页中添加登录按钮 html代码如下: <%@ page contentType="text/html;charset=UTF-8" la ...
- 用户登录拦截器查询到登录用户后如何将用户信息传递到后面的Controller
taotao创建订单代码中之前忘了加入用户信息,那么加上呢? 分析:用户创建订单的时候,我们会强制要求用户先登录,也就是说,创建订单的Controller执行时,一定是用户已经登录了的,而用户只要登录 ...
- Spring mvc登录拦截器
自己实现的第一个Spring mvc登录拦截器 题目要求:拒绝未登录用户进入系统,只要发现用户未登录,则将用户请求转发到/login.do要求用户登录 实现步骤: 1.在spring的配置文件中添加登 ...
- sessionStorage记录返回前端的数据,用于解决登录拦截器刷新页面的问题
1.问题出现的场景与解决 实现一个登录拦截器,重写doFilter方法,判断用户的登录状态,在用户长时间未操作或者异地登录时前端进行提示,完整代码如下 public class LoginValida ...
- struts2自定义登录拦截器
版权声明:本文为博主原创文章,未经博主允许不得转载. (1)配置web.xml,让xml加载struts2框架 <?xml version="1.0" encoding=&q ...
- Struts2 在登录拦截器中对ajax请求的处理
前言: 由于ajax请求不像http请求,可以直接进行页面跳转,你返回的所有东西,ajax都只会识别为一个字符串. 之前尝试的方法是在拦截器中返回一个标识给ajax,然后再在每一个ajax请求成功之后 ...
- 【java web】拦截器inteceptor
一.简介 java里的拦截器提供的是非系统级别的拦截,也就是说,就覆盖面来说,拦截器不如过滤器强大,但是更有针对性. Java中的拦截器是基于Java反射机制实现的,更准确的划分,应该是基于JDK实现 ...
随机推荐
- 51nod 1135 原根 就是原根...
%%% dalao Orz ,筛素数到sqrt(n),分解ϕ(p),依次枚举判断就好了 #include<cstdio> #include<cstring> #include& ...
- CentOS 7下单机部署RabbltMQ环境的操作记录
一. RabbitMQ简单介绍 在日常工作环境中,你是否遇到过两个(多个)系统间需要通过定时任务来同步某些数据?你是否在为异构系统的不同进程间相互调用.通讯的问题而苦恼.挣扎?如果是,那么恭喜你,消息 ...
- Windows上安装配置SSH教程(1)——知识点汇总
1.是什么SSH? 维基百科:https://zh.wikipedia.org/wiki/Secure_Shell 其他博客:http://www.ruanyifeng.com/blog/2011/1 ...
- Postman----presets与环境变量的联合使用
一.环境 在开发不同阶段,可能存在不同的环境(对我碰到的就是服务器地址/api版本/header信息等不一样),比如 debug环境和release环境,每次切换环境测试的时候都得重新配置url信息, ...
- python 之 初识模块
什么是模块 什么是模块 一个.py文件 就是一个模块 我们使用import加载的模块分为4个通用类别 1.py文件 2.包好一组模块的包(带__init__.py文件的文件夹) 3.内置模块 4.已被 ...
- PyQt5嵌入matplotlib动画
# -*- coding: utf-8 -*- import sys from PyQt5 import QtWidgets import numpy as np from matplotlib.ba ...
- Docker最全教程之使用 Visual Studio Code玩转Docker(二十)
前言 VS Code是一个年轻的编辑器,但是确实是非常犀利.通过本篇,老司机带你使用VS Code玩转Docker——相信阅读本篇之后,无论是初学者还是老手,都可以非常方便的玩转Docker了!所谓是 ...
- DSAPI显示PNG异形窗体
使用DSAPI实现PNG异形窗体,注意,该窗体为层样式窗体,以PNG或32位带透明通道的图像合成到屏幕,此方法不会触发窗体的重绘,故原窗体(包括其子控件)均不会显示,如果需要更新画面,需要重新用代码等 ...
- 在ArcMap中发布FeatureLayer(要素图层)
FeatureLayer(要素图层)是ArcGIS Server发布的一种很重要的地图服务,发布后使用提供的url地址就可以在代码中调用并在地图上显示.编辑这个FeatureLayer.在HTML页面 ...
- 好代码是管出来的——使用Jenkins搭建CI服务器
Jenkins是一个开源的跨平台的CI工具,它可以部署在Windows.Linux等平台上,并且Jenkins提供了非常丰富的插件来帮助完成编译.测试.部署等工作. 本文将介绍在Windows平台上使 ...