J2EE design pattern (2) Filter

zhaozj2021-02-16  55

J2EE design pattern (2) Filter

J Snow (zhuam) Email: zhaum@studyjava.com

In fact, too many definitions in J2EE are very annoying, design models are also abstract, today I will further describe the design mode in new FILTER in servlet2.3 in the Web Application application.

First, suppose we want to be a web application now (eg BBS).

The following functions are required:

1. Before the user posts, you should make an authentication to confirm that the user has been logged in.

2, followed by deleting posts, modifying posts, permission check.

3. Identity authentication when accessing a specific resource (web page, JSP page)

So how to do this, how should we do it, if you write the code for check permissions in each page, it is not a good idea, and the reusability of the program is reduced, and the design mode intercepting filter (intercept filtration) is in line with us. Requirements, and in servlet2.3, by using a filter (Filter) allows the Web Application Developer to capture the request before requesting the Web resource, modify the response after processing the request.

A Java class that performs a filter must implement a Javax.Servlet.Filter interface. This interface contains three methods:

INIT (FILTERCONFIG): This is the initialization method called by the container. It guarantees that the container is called before the first DOFILTER () call is called. It can get the Filter initialization parameters specified in the web.xml file (there is a web.xml file behind the article).

· DOFILTER (ServletRequest, servletResponse, filterchain): This is a method of completing the filter behavior. It is also a method of the previous filter. The introduced Filterchain object provides information about the subsequent filters to be called, and several filters have become a chain because of Filterchain.

· Destroy (): The container is called before the filter is destroyed, and all activities in DOFILTER () are called after the instance is terminated.

Two filters have been implemented in the open source LightningBoard BBS, as follows

1. The ControllerFilter acts here is the role of the Front Controller, which is the controller in the MVC mode, which is the entry point of the BBS.

Package lightningboard;

Import java.io.ioException;

Import javax.servlet.servletException;

Import javax.servlet.servletRequest;

Import javax.servlet.servletResponse;

Import javax.servlet.filter;

Import javax.servlet.filterconfig;

Import javax.servlet.filterchain;

Import javax.servlet.http.httpservletRequest;

Import javax.servlet.http.httpservletResponse;

Import Lightningboard.Act. *;

/ **

* Control all * .do.

* @Version 0.3.5

* @Author xiaobo liu

* /

Public class controllerfilter imports filter {

/ **

* Action dispatch

* EXAMPLE: HOMDE.DO WILL BE CREATE HOMEACTION AND CALL ITS EXCUTE () Method.

* /

Protected filterconfig filter;

Public void init (filterconfig config) {

THIS.FILTERCONFIG = Config;

}

Public void destroy () {

THIS.FILTERCONFIG = NULL;

}

Public Void Dofilter (ServletRequest Srequest, ServletResponse SRESPONSE, FILTERCHAIN ​​FILTERCHAIN)

THROWS IOException, servletexception {

HTTPSERVLETREQUEST REQUEST = (httpservletRequest) SREQUEST

HttpservletResponse response = (httpservletResponse) SRESPONSE

Long TimeStart = system.currenttimemillis ();

Configuration cfg = configuration.getinstance ();

String encoding = cfg.getValue ("sys.encoding");

Request.setCharacterencoding (Encoding);

String path = (string) Request.getRequesturi ();

String ActionString = path.substring (path.lastindexof ("/") 1, path.lastindexof ("."));

String forwardPage = NULL;

Try {

IF (ActionString.equals ("Forum"))

ForwardPage = New forumAction (). Excute (request (request, response);

Else IF (ActionString.equals ("Topic"))

ForwardPage = new topicArtAction (). Excute (Request, Response);

Else IF (ActionString.equals ("User"))

ForwardPage = new useraction (). Excute (request, response);

Else IF (ActionString.equals ("UserList")))

ForwardPage = new userlistAction (). Excute (request, response);

Else IF (ActionString.equals ("login")))

ForwardPage = new loginaction (). Excute (request, response);

Else IF (ActionString.equals ("Register"))

ForwardPage = new registerction (). Excute (request, response);

Else IF (ActionString.equals ("post"))

ForwardPage = new postAction (). Excute (request, response);

Else IF (ActionString.equals ("PostP"))

ForwardPage = new postPAction (). Excute (request, response);

Else IF (ActionString.equals ("Useredit"))

ForwardPage = new useditAction (). Excute (request, response);

Else IF (ActionString.equals ("Usereditp")))

ForwardPage = new useReditPAction (). Excute (request, response);

Else IF (ActionString.equals ("Logout")))

ForwardPage = new logoutAction (). Excute (request, response);

Else // Default: home

ForwardPage = new homeAction (). EXCUTE (Request, Response);

} catch (ActionException EX) {

Debug.out (ex);

Request.setttribute ("ActionMessage", New ActionMessage ("System_ERROR"));

ForwardPage = "/ ActionMessage.jsp";

}

// forward page

IF (forwardpage! = null) {

String Processtime = "" (System.currentTimeMillis () - TimeStart);

Request.setttribute ("Processtime", ProceSstime;

FilterConfig.getServletContext (). getRequestDispatcher (ForwardPage) .forward (request, response);

}

}

}

2, this filter is the role of IntercePting Filter (intercepting filtration).

Package lightningboard.filter;

Import java.io.ioException;

Import javax.servlet.servletException;

Import javax.servlet.servletRequest;

Import javax.servlet.servletResponse;

Import javax.servlet.filter;

Import javax.servlet.filterconfig;

Import javax.servlet.filterchain;

Import javax.servlet.http.httpservletRequest;

Import javax.servlet.http.httpservletResponse;

Import javax.servlet.http.httpsession;

Public Class SessionauthorizationFilter Implements Filter {

Protected filterconfig filter;

Public void init (filterconfig config) {

THIS.FILTERCONFIG = Config;

}

Public void destroy () {

THIS.FILTERCONFIG = NULL;

}

Private Boolean Pass (ServletRequest Request, ServletResponse Response)

THROWS IOEXCEPTION, ServletException {Boolean Result = FALSE

String Objectname = this.filterconfig.getinitParameter ("object_name");

HTTPSERVLETREQUEST REQ = (httpservletRequest) Request;

HttpSession session = req.getsession (false);

IF (session! = null) {

Object object = session.gettribute (ObjectName);

IF (Object! = NULL)

Result = TRUE;

}

Return Result;

}

Public Void Dofilter (ServletRequest Request, ServletResponse Response, Filterchain Filterchain)

THROWS IOException, servletexception {

IF (Passed (Request, Response))

Filterchain.dofilter (Request, Response);

Else {

HTTPSERVLETRESPONSE RES = (HTTPSERVLETRESPONSE) Response;

String ErrorPage = this.filterconfig.getinitParameter ("Error_Page");

Res. extendedRedirect (ErrorPage);

}

}

}

The container parses the filter configuration information through the configuration descriptor web.xml file in the web application. There are two new tags related to the filter:

with

.

The tag is a filter definition, it must have one

with

Child elements.

The child element gives a name related to the filter instance.

Specifies the implementation class loaded by the container. You can freely contain one

The child element provides an initialization parameter for a filter instance.

The tag represents a filter mapping, specifying the subset of the URL that the filter is generated.

The Web.xml file in the Lightningboard project is as follows:

Controllerfilter

Lightningboard.Controllerfilter

SessionauthorizationFilter

Lightningboard.filter.SessionAuthorizationFilter

Error_Page

Login.jsp

Object_name

Loginbean

SessionauthorizationFilter

/Post.do

SessionauthorizationFilter

/Postp.do

SessionauthorizationFilter

/POST.JSP

SessionauthorizationFilter

/useredit.do

SessionauthorizationFilter

/USEREDITP.DO

SessionauthorizationFilter

/useredit.jsp

SessionauthorizationFilter

/userlist.do

Controllerfilter

* .do

INDEX.HTML

Since I have limited level, please refer to it, thank you! ! !

转载请注明原文地址:https://www.9cbs.com/read-20374.html

New Post(0)