JSP application Servlet filter for authentication, servlet Filter
1. Description of Servlet Filters
(1) intercept the customer's HttpServletRequest before HttpServletRequest arrives at the Servlet.
Check HttpServletRequest as needed. You can also modify the HttpServletRequest header and data.
(2) intercept HttpServletResponse before HttpServletResponse arrives at the client.
Check HttpServletResponse as needed. You can modify the HttpServletResponse header and data.
2. Apply the Servlet filter for authentication
Login1.htm and longin1.jsp in the root directory of the website are used for user logon. Files in the chap08 directory can only be accessed after user logon.
(1) Compile the Servlet Filter
@ WebFilter ("/FilterStation ")
Public class FilterStation extends HttpServlet implements Filter {
Private FilterConfig filterConfig;
Public FilterStation (){
Super ();
}
Public void destroy (){
}
Public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpSession session = (HttpServletRequest) request). getSession ();
Response. setCharacterEncoding ("gb2312 ");
If (session. getAttribute ("me") = null ){
PrintWriter out = response. getWriter ();
Out. print ("<script> alert ('log on! '); Location. href =' ../login1.htm' </script> ");
}
Else {
// Pass the request along the filter chain
Chain. doFilter (request, response );
}
}
Public void init (FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
This. filterConfig = fConfig;
}
}
(2) Configure web. xml
<Filter>
<Filter-name> filterstation </filter-name>
<Filter-class> zhou. FilterStation </filter-class>
</Filter>
<Filter-mapping>
<Filter-name> filterstation </filter-name>
<Url-pattern>/chap08/* </url-pattern>
</Filter-mapping>
(3366login1.htm code
<Html>
<Head>
<Title> User Logon </title>
</Head>
<Body>
<Form method = "POST" action = "login1.jsp">
<P> user name: <input type = "text" name = "user" size = "18"> </p>
<P> password: <input type = "text" name = "pass" size = "20"> </p>
<P> <input type = "submit" value = "submit" name = "OK">
<Input type = "reset" value = "reset" name = "cancel"> </p>
</Form>
</Body>
</Html>
(4) login1.jsp code
<% @ Page contentType = "text/html; charset = GB2312" %>
<Html>
<Head> <title> Session application demonstration </title> <%
If (request. getParameter ("user ")! = Null & request. getParameter ("pass ")! = Null)
{
String strName = request. getParameter ("user ");
String strPass = request. getParameter ("pass ");
If (strName. equals ("admin") & strPass. equals ("admin "))
{
Session. setAttribute ("login", "OK ");
Session. setAttribute ("me", strName );
Response. sendRedirect ("chap08/welcome. jsp ");
}
Else
{
Out. print ("<script> alert('user name or Password error 'your region location.href}'login1.htm' </script> ");
}
}
%>
</Html>