Java Code login Blocker example

Source: Internet
Author: User
Tags stub

Usually when we click on a button, the operation of an object, we need to login to do, this time we need an interceptor to intercept a method,

For example, you are in a library management center you want to borrow books, this time you will be asked to show a library card, the administrator can borrow books to you. And interceptors have this function.

: Visitors click on the Library button--and the background blocker intercepts the method--to determine if you are logged-in and logged-on---No login----Allow operation

The code is as follows:

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 Voi D Destroy () {//TODO auto-generated method stub}public void DoFilter (ServletRequest request, Servletresponse Response,fil Terchain chain) throws IOException, servletexception {//Get HttpSession object, determine whether to login httpservletrequest req = ( HttpServletRequest) Request; HttpServletResponse res = (httpservletresponse) response; HttpSession session = Req.getsession (); if (Session.getattribute ("model") ==null) {//illegal access, no login, Jump to landing page Session.setattribute ("error", "illegal access");//Save the place where the customer wants to goAddress, the login succeeds then jumps directly, instead of to the homepage string gourl = Req.getservletpath ();//(Get to addresses do not include parameters)//Determine whether the parameter is empty, not NULL to get the parameter if (req.getquerystring () !=null) {gourl+= "?") +req.getquerystring ();} Session.setattribute ("Gourl", Gourl); Res.sendredirect (Req.getcontextpath () + "/user/userlogin.jsp");} else{//If there is a next filter, jump to the next filter otherwise target page chain.dofilter (request, Response);}}

Xml

<filter>
<!--interceptors configured in Web. XML, start--><filter-name>userfilter</filter-name><filter-class> together when the container is started Com.utis.filter.userfiter</filter-class></filter><filter-mapping><filter-name> Userfilter</filter-name><url-pattern>/book/*</url-pattern></filter-mapping>

Usercontrller.java

/** * User Login function * @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", "User or password Error!"); return new Modelandview ("User/userlogin");}}

userlogin.jsp

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 + "/";%&GT;&L t;! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >

Initializing data

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;/** * The main function of this class is to load the index home page method, query data, display home * @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;//Loads the spring container (config file) through the Spring Web tool class and calls a class to do something context =webapplicationcontextutils.getwebapplicationcontext (Event.getservletcontext ());//1, get Bookservicebookservice = ( Bookservice) Context.getbean ("Bookservice"); goodstimertask = (Goodstimertask) context.getbean ("GoodsTimerTask");// 2, check all books Event.getservletcontext (). SetATtribute ("Booklist", Bookservice.findbook ());//Will application built-in objects, The data object that is passed into the Goodstimertask query Goodstimertask.setapplication (Event.getservletcontext ());//Set the time task, load the product information of the home page every time, This thread must set the daemon thread to stop the new Timer (TRUE) when the main thread stops. Schedule (Goodstimertask, 0,1000*60);}}

Xml

<!--Initialize Home information (query) listener--><listener><listener-class>com.booksys.listener.initdatalistener</ Listener-class></listener>

Timestamp: Used to automatically invoke the Query method, update the first page data display

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 {// Incoming application built-in object private ServletContext application;public void Setapplication (ServletContext application) { this.application = Application;} Gets the business logic class @resourceprivate Bookservice bookservice=null; @Overridepublic void Run () {System.out.println (" Goodstimertask.run () ");//first page load book data information list<book> Booklist = Bookservice.findbook ();//Store the list collection data in the app's built-in objects, Application.setattribute ("Booklist", Booklist) at the Inde front desk through a circular query;}}

Java Code login Blocker example

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.