Filter filter implements permission control

Source: Internet
Author: User
Tags flush

in the operation of the user is often to check whether to authenticate, then if you want to verify, there must be a large number of code to constantly determine whether the session exists. This kind of code can actually be written directly in the filter.

Login page: login.jsp

<script type= "Text/javascript" >//Check whether to enter a user name or not to submit function check () {var username = Document.getelement
	   Byid ("username"). Value; if (username==null| | ""
		   ==username) {alert ("Please enter user name");
	   return false;
   return true; } </script> <body> <center> <form action= "Loginservlet" method= "POST" onsubmit= "R
	                Eturn check () "> <table> <caption> User Login </caption> <tr>
	             <td> username </td><td><input type= "text" id= "username" name= "username"/></td> </tr> <tr> <td> Password </td><td><input type= "text" name= "Password"/></td> </tr> <tr> <td align= "right" Colspa N= "2" ><input type= "submit" value= "Login" ></td> </tr> </table> </ Form> </center> </body> 

Rights control users In fact, there is only one portal, that is, first login, log in after the information stored in the session, if there is no content in the session, you can not access other pages or other operations.

Click the login button to enter Loginservlet to save the information.

Loginservlet.java

Package com.org;
Import java.io.IOException;

Import Java.io.PrintWriter;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

Import javax.servlet.http.HttpSession; public class Loginservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse resp
		Onse) throws Servletexception, IOException {response.setcontenttype ("TEXT/HTML;CHARSET=GBK");
		Request.setcharacterencoding ("GBK");
		
		PrintWriter out = Response.getwriter ();
		String username = request.getparameter ("username");
		HttpSession session = Request.getsession ();  Session.setattribute ("username", username);    User login to join in session response.sendredirect ("jsp/success.jsp");
		
		Login successfully jumped into success.jsp//test System.out.println ("Username:" +username);
		Out.flush ();
	Out.close ();
public void DoPost (HttpServletRequest request, httpservletresponse response)			Throws Servletexception, IOException {this.doget (request, response);
 }

}

Filter Interceptor: Myfilter.java

Package com.org;
Import java.io.IOException;
Import Java.io.PrintWriter;

Import java.io.UnsupportedEncodingException;
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 Myfilter implements Filter {public void Destroy () {} public void Dofilter (ServletRequest servletreques T, Servletresponse Servletresponse, Filterchain filterchain) throws IOException, servletexception {HttpServletRe
		Quest req = (httpservletrequest) servletrequest;
		
		HttpSession session = Req.getsession ();
		
		String username = (string) session.getattribute ("username"); if (username!= null&&username!= "") {//If there is a session now, the request continues to pass Filterchain.dofilter (ServletRequest, SERVL EtresponSE);
		else {//jump to the prompt landing page servletrequest.getrequestdispatcher ("/error.jsp"). Forward (ServletRequest, servletresponse);
 } public void init (Filterconfig filterconfig) throws servletexception {}}

Filter extracts the data from the session to see if it is logged in, and executes the Filterchain.dofilter () method request to continue the downward pass if there is content in the session. Otherwise, return to the login page.

To test for a class that will fail its session

Invalidateservlet.java

package com.org;
Import java.io.IOException;

Import Java.io.PrintWriter;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

Import javax.servlet.http.HttpSession;  public class Invalidateservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse
		Response) throws Servletexception, IOException {response.setcontenttype ("TEXT/HTML;CHARSET=GBK");
		Request.setcharacterencoding ("GBK");
		PrintWriter out = Response.getwriter (); HttpSession session =request.getsession ();                      Get the Session object Session.invalidate ();
		Log off session to invalidate//then jump to login page request.getrequestdispatcher ("/login.jsp"). Forward (request, response);
		Out.flush ();
	Out.close (); 

		
	public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { }

}

If you access a different page when you are not logged on, jump to the error.jsp page

<body>
		<center>
			

Login Success Page success.jsp

<body>
		<center>
			Welcome <%=session.getattribute ("username")%> visit
			<br>
			< A href= "Invalidateservlet" > Exit </a>
		</center>
	</body>

Also, it's a good idea to have several test pages

Test1.jsp test2.jsp inside a few display content can

Configuring Web.xml to implement interception

<filter> <filter-name>myfilter</filter-name> <filter-class>com.org.myfilter</ filter-class> </filter> <filter-mapping> <filter-name>myfilter</filter-name> < url-pattern>/jsp/*</url-pattern> </filter-mapping> <servlet> <servlet-name> Loginservlet</servlet-name> <servlet-class>com.org.LoginServlet</servlet-class> </servlet > <servlet> <servlet-name>InvalidateServlet</servlet-name> &LT;SERVLET-CLASS&GT;COM.ORG.INV alidateservlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>loginservlet </servlet-name> <url-pattern>/loginServlet</url-pattern> </servlet-mapping> < Servlet-mapping> <servlet-name>InvalidateServlet</servlet-name> <url-pattern>/ invalidateservlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcoMe-file>index.jsp</welcome-file> </welcome-file-list> 

Except login.jsp in the Webroot directory the rest of the JSP pages under the JSP folder

You can test with the following methods

logon access without first entering login.jsp http://localhost:8080/filter/jsp/test1.jsp prompts you not to sign in.

Then login to enter a user name, and then access test1.jsp can enter or close the browser to reopen, or can enter

Until you log out of the success.jsp page.





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.