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);
	}
}

 

posted @ 2014-10-15 16:40  吴小雨  阅读(7237)  评论(0编辑  收藏  举报