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.