Servlet implementation Request filtering

Source: Internet
Author: User

Requirements: When users visit, we can enter the system through user login. There is a problem here: The user is not honest (not according to the usual card), first input http://xxxx:xx/xxxx/index[.xxxx], and so on, we developers know that our system is usually to record the user's status (session), Other pages will use the user information stored in the session. So that users visit the index page, it is not to report the programmer the most headaches nullpointexception, the user sees of course is page 500 error. So the user's impression and experience is not optimistic, customer first, we do not allow such a problem.

The above is an analysis of the problem, the following is to solve the problem.

Solve the problem:

Solution:

So, I naturally think of the servlet filter, through the user session to determine the implementation of request control.

Specific implementation:

1. Implement filter interface, code fragment:

HttpServletRequest HttpRequest = (httpservletrequest) request; HttpServletResponse HttpResponse = (httpservletresponse) response; HttpSession session = Httprequest.getsession (); if (Session.getattribute ("user") = null) {//SYSTEM.OUT.PRINTLN ("user session is empty"); Httpresponse.sendredirect (" Login.jsp "); Return else {filterchain.dofilter (request, response);}

2, configuration Web.xml, code fragment:

<filter> <filter-name>RequestFilter</filter-name> <filter-class>com.filter.requestfilter </filter-class> </filter> <filter-mapping> <filter-name>RequestFilter</filter-name> <url-pattern>/index.jsp</url-pattern> </filter-mapping>

Configuration complete, so that the user is not logged in the case, access to the home page, the system will automatically jump to the login pages to login after the visit.

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.