Java web 过滤器 Filter 验证登录界面

doFilter()方法中定义的是ServletRequest类型的对象,那么要想取得session,则必须进行向下转型,将ServletRequest变为HttpServletRequest接口对象,才能通过getSession()方法取得session对象。

验证 用户名: zhangsan 密码: lisi
在这里插入图片描述

过滤器采用注解的方式,只过滤文件夹test里的文件

loginfilter.java

package com.Filter;

import java.io.IOException;
import java.io.PrintWriter;

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.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@WebFilter (filterName= "loginfilter" ,urlPatterns= "/test/*" )
public class loginfilter implements Filter{
    public void init(FilterConfig config) throws ServletException{

    }
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException,ServletException{
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        HttpSession session = req.getSession();

        
        
        //用来判断是否是从登录页登录。
        //若直接判断是否有session,在重新登录时因为此时session还在,如果密码错误也会登录成功。
        String userName = request.getParameter("username");
        String password = request.getParameter("password");
      
        if(userName!=null && !userName.trim().equals("") && password!=null && !password.trim().equals("") ){              //可以取到表单的信息,说明正在登录页验证登录
            if("zhangsan".equals(userName)&&"lisi".equals(password) )
            {//验证通过
            	 session.setAttribute("name", userName);
                chain.doFilter(request, response); //请求转发给过滤器链上的下一个对象
            }
            else{   //用户名或密码错误   (或其他去主页的链接 )
            	response.getWriter().write("wrong username or password. ");
            
            	response.getWriter().write("relogin after 2 seconds ");
            	res.setHeader("refresh", "2;url="+req.getContextPath()+"/login.jsp");   
             //request.getRequestDispatcher("/login.jsp").forward(request, response);
            }
        }
        else if(session.getAttribute("name")!=null){//不是从登录页进去的,但曾经登录过
            chain.doFilter(request, response);
        }
        else {//(曾经)没有登录过
        	response.getWriter().write("never login,relogin after 3 seconds");
        	res.setHeader("refresh", "3;url="+req.getContextPath()+"/login.jsp"); 
            //request.getRequestDispatcher("/login.jsp").forward(request, response);
        }       
    }
    public void destroy() {
        // TODO Auto-generated method stub      
    }
}

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
  <head>
           <title>登录</title>   	
  </head>
 
  
  <body>
 
 <form action="test/index.jsp" method="post">
 <table>
 <tr>
<td>用户名:</td>
<td  > <input type="text" name="username"></td>
</tr>  
<tr>
<td>密码:</td>
<td  > <input type="password" name="password"></td>

</tr>  
</table>  
 <input type="submit" name="submit" id="submit" value="登录"/>                 
  </form>
  
  
    <% 
        //读取session值
        String val= (String)session.getAttribute("name");
        //如果session不存在
        if(val==null){
            val ="不存在";
        }
        out.print("当前\""+val+"\"用户可自动登录");
     %>
    
<a href="test/index.jsp">主页</a>
<a href="TestPaper.jsp">去测试页</a>   
    
  </body>
</html>


TestPaper.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
  <head>
           <title>登录</title>   	
  </head>
 
  
  <body>
 
 <form action="test/index.jsp" method="post">
 <table>
 <tr>
<td>用户名:</td>
<td  > <input type="text" name="username"></td>
</tr>  
<tr>
<td>密码:</td>
<td  > <input type="password" name="password"></td>

</tr>  
</table>  
 <input type="submit" name="submit" id="submit" value="登录"/>                 
  </form>
  
  
    <% 
        //读取session值
        String val= (String)session.getAttribute("name");
        //如果session不存在
        if(val==null){
            val ="不存在";
        }
        out.print("当前\""+val+"\"用户可自动登录");
     %>
    
<a href="test/index.jsp">主页</a>
<a href="TestPaper.jsp">去测试页</a>   
    
  </body>
</html>


index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>主页</title>
</head>
<body>
   <%
    String user=(String)session.getAttribute("name");
     %>
     <%
     if(user==null||"".equals(user)){
     %>
     	欢迎!
     	<a href="http://localhost:8080/Cookie_/login.jsp">登陆界面</a><br>
     <%
     	}else{	
      %>
      	欢迎回来 <%=user %>
      	<a href="logout.jsp">注销</a>
      	<a href="http://localhost:8080/Cookie_/login.jsp">登陆界面</a><br>
      <%
      	}

     %>
     
     
</body>
</html>

logout.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title></title>
</head>
<body>

<% 
session.removeAttribute("user");
session.invalidate(); 
%> 


<h1>注销成功</h1>
<a href="login.jsp">relogin</a>
</body>
</html>

运行login.jsp
成功登录后
测试页可直接去主页

在这里插入图片描述
另例
未登录无法到主页,跳转到登录页
过滤器Loginfilter.java 限定index.jsp一个页面

package com.imooc.jdbc;

import java.io.IOException;
import java.io.PrintWriter;

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.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@WebFilter (filterName= "loginfilter" ,urlPatterns= "/index.jsp" )

public class LoginFilter implements Filter {
	public void init(FilterConfig config) throws ServletException{

    }
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
			throws ServletException, IOException {
    	HttpServletRequest request = (HttpServletRequest)servletRequest;
		HttpServletResponse response = (HttpServletResponse)servletResponse;
		HttpSession session = request.getSession();
     
        
		if(session == null || session.getAttribute("name") == null){
			response.sendRedirect("http://localhost:8080/Ser/login.jsp");
		}
		else {
			 chain.doFilter(request, response); 
		}
   
       
    }
	
	public void destroy() {
        // TODO Auto-generated method stub      
    }
       
}

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>主页</title>

<style>
body{
    margin:0px;padding:100px;
    text-align:center;
    
}
</style>
</head>
<body>


   <%
    String userna=(String)session.getAttribute("name");
   %>
   <% 
     if(userna==null||"".equals(userna)){
     %>
    
      <table align="center">
      <tr align="center">
      <td >    欢迎!
      <td ><a href="login.jsp">登录</a>
      </td>
      </tr>
     	    	
     <%
     	}else{	
      %>
      <table align="center">
      <tr align="center">
      <td >	欢迎回来 <%=userna %></td>
      	<td ><a href="logout.jsp">注销</a></td>
      	<td ><a href="login.jsp">登录页</a></td>
      <% 
        } 
      %>
  
    
    
     <table align="center">
     <tr align="center">
     <td ><a href="searchServlet?us=<%=userna%>">查询用户信息</a></td>
     </tr>
     </table>
   
</body>
</html>

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
 <title>登录</title>
 
    </head>
   
<meta charset="UTF-8">
<title>登录</title>

 <script type="text/javascript" language = "javascript">
 
     function reloadCode(){
         var time = new Date().getTime();
         document.getElementById("imag").src="authImg?d="+time;
     }
     
     function check(){
    	    //验用户名
    	  
    	    	var username = document.getElementById("user").value;
    	        var pwd = document.getElementById("pwd").value;
    	        
    	  
    	     
    	    
    	     
    	    	if(username == ""){
    				alert("用户名不能为空");
    				return ;
    				}
    	    	if(pwd == ""){
    				alert("密码不能为空");
    				return ;
    				} 	 	    
    	  
    	    
    	    	
    			
    			document.getElementById("sub").submit();//方法进行到这里将form的action提交
    	    
       } 
     
 </script>
<body>
<form id="sub" action="loginServlet" method="post">
<table align="center">


<tr >
<td>用户名:</td>
<td align="left"> <input type="text" placeholder="输入用户名" name="user" id="user"></td>
</tr>


<tr >
<td>密码:</td>
<td align="left"> <input type="password" placeholder="输入密码" name="pwd" id="pwd"></td>
</tr>

<tr >
<td>验证码:</td>
<td align="left"><input type="text" placeholder="输入验证码" name="text" id="text" size="10"/> 
<img  src="authImg" id="imag" onclick="reloadCode()"/>
</td>
</tr>

<tr table align="center">
<td ><input type="button" value="提交" onclick="check()"/>  </td>
<td ><input type="reset"  value="重置"/>  </td>
<td ><input type="button" value="注册" onclick="window.location.href='register.jsp'"/></td>
</tr>

</table>
</form>





<center>
 <% 
        //读取session值
        String val= (String)session.getAttribute("name");
        //如果session不存在
        if(val==null){
            val ="不存在";
        }
        
        out.print("当前\""+val+"\"用户已登录");
        
     
     %>

<table align="center">
<tr>
<td><input type = "button" value = "主页" onclick="window.location.href='index.jsp'"/></td>
</tr>
 </center>
 </table>
</form>


</body>
</html>


Loginservlet 调用mysql数据库 具体内容如此

package com.imooc.jdbc;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;


import com.imooc.jdbc.UserDao;

@WebServlet(name="loginServlet",urlPatterns={"/loginServlet"})   //注解名和post的标签名相同

public class LoginServlet extends HttpServlet{
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("UTF-8");	 
		PrintWriter out = response.getWriter();
        response.setContentType("text/html);charset=UTF-8");

        String imageText = request.getParameter("text");
        String text = (String) request.getSession().getAttribute("image");      
        String user = request.getParameter("user");
        String pwd = request.getParameter("pwd"); 
       
        
        UserVO u=new UserVO();
        u.setUsername(user);
        u.setPassword(pwd);
        
		boolean r=new UserDao().selectByNameAPwd(u);//调用dao层
		
		
		
		
		//页面跳转
		if (!text.equalsIgnoreCase(imageText)){
        	response.getWriter().write("验证码错误,1秒后重新登录");
    		response.setHeader("refresh", "1;url="+request.getContextPath()+"/login.jsp");
        }
		else if(r){
			
			
            //把用户数据保存在session域对象中		
        		request.getSession().setAttribute( "user" , user);
        		
        		 HttpSession session = request.getSession(true);  
        	        session.setAttribute("name", user);
        	        
        		out.println("登陆成功,2秒后到主页");                       
        		response.setHeader("refresh", "1;url="+request.getContextPath()+"/index.jsp"); 
		
	       
			
		}else{
			response.getWriter().write("登陆失败,2秒后重新登录");
    		response.setHeader("refresh", "2;url="+request.getContextPath()+"/login.jsp");   
	       
		}
		
       
    }
 
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值