SQL防止重复提交和Filter

/class User

package com.neuedu.bean;

import java.io.Serializable;

public class User implements Serializable{
    private static final long serialVersionUID = 1L;
private  int password;
   private  String name;

    public User() {
        super();

    }
    public User(int password, String name) {
        super();
        this.password = password;
        this.name = name;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getPassword() {
        return password;
    }
    public void setPassword(int password) {
        this.password = password;
    }
    @Override
    public String toString() {
        return "password=" + password + ", name=" + name;
    }

}

/class LoginDao

package com.neusoft.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.neuedu.bean.User;
import com.neusoft.utils.JDBCUtil;

public class LoginDao {
     public User getUser(String name,String password){
         User user=null;
         PreparedStatement ps=null;
         ResultSet rs =null;
         Connection conn=JDBCUtil.getConnection();
         String sql="select * from t_user where password= ? and name =?";
         try {
              ps = conn.prepareStatement(sql);
              ps.setString(1, password);
              ps.setString(2, name);
              rs = ps.executeQuery();
            while (rs.next()) {
                String username = rs.getString("name");
                int password2 = rs.getInt("password");
                user=new User(password2,username);
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            JDBCUtil.close(ps, rs, conn);
        }
        return user;

     }
     public void Add(String name,String password,String email){

         PreparedStatement ps=null;
         Connection conn=JDBCUtil.getConnection();
         String sql="insert into t_user values(?,?,?,?)";
         try {
              ps = conn.prepareStatement(sql);
              ps.setString(1, null);
              ps.setString(2, name);
              ps.setString(3, password);
              ps.setString(4, email);
               ps.executeUpdate();
            System.out.println(ps.toString());
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {            

            if (ps !=null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (conn !=null) {
                 try {
                    conn.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
     }
     public void Update(String name,String password,String email){

         PreparedStatement ps=null;
         Connection conn=JDBCUtil.getConnection();
         String sql="update t_user set name=?,pasword=?,mail=? where id=?";
         try {
              ps = conn.prepareStatement(sql);
              ps.setString(1, null);
              ps.setString(2, name);
              ps.setString(3, password);
              ps.setString(4, email);
               ps.executeUpdate();
            System.out.println(ps.toString());
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {            

            if (ps !=null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (conn !=null) {
                 try {
                    conn.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
     }
}

/class AFilter

package com.neusoft.servlet;

import java.io.IOException;
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;

@WebFilter( "/LoginServlet" )
public class AFilter implements Filter {

    public void destroy() {
        // TODO Auto-generated method stub
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("AFilter此路是我开,此树是我栽!");
        String name = request.getParameter("username");
        if (name.equals("qwe")) {
            chain.doFilter(request, response);
            System.out.println("AFilter要想从此过,留下买路财!");
        }else {
            request.getRequestDispatcher("/Login.jsp").forward(request, response);//转发
        }

    }

    public void init(FilterConfig fConfig) throws ServletException {
        // TODO Auto-generated method stub
    }

}

/class BFilter

package com.neusoft.servlet;

import java.io.IOException;
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;

@WebFilter("/LoginServlet")
public class BFilter implements Filter {

    public void destroy() {
        // TODO Auto-generated method stub
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("BFilter此路是我开,此树是我栽!");
        String psd = request.getParameter("pwd");
        if (psd.equals("123")) {
            chain.doFilter(request, response);
            System.out.println("BFilter要想从此过,留下买路财!");
        }else {
            request.getRequestDispatcher("/Login.jsp").forward(request, response);//转发
        }

    }

    public void init(FilterConfig fConfig) throws ServletException {
        // TODO Auto-generated method stub
    }

}

/class LoginServlet

package com.neusoft.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.neuedu.bean.User;
import com.neusoft.dao.LoginDao;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String reqUUID = request.getParameter("uuid");
        HttpSession session = request.getSession();
        String sessUUID =(String)session.getAttribute("uuid");
        session.removeAttribute("uuid");//防止重复提交
        try {
            Thread.sleep(1000*3);//休眠3秒

        String name = request.getParameter("username");
        String psd = request.getParameter("pwd");
        System.out.println(name);
        User user=new LoginDao().getUser(name, psd);
        if (user !=null&&reqUUID.equals(sessUUID)) {
//            List<User>List=new ArrayList<User>();
//            List.add(user);
            request.setAttribute("user", user);
            System.out.println(user);
//            response.sendRedirect(request.getContextPath()+"/login-success.jsp");//重定向
            request.getRequestDispatcher("/login-success.jsp").forward(request, response);//转发
        }else {
            request.setAttribute("errorMsg", "不要重复提交!");
            request.getRequestDispatcher("/Login.jsp").forward(request, response);//转发
        }
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        doGet(request, response);
    }

}

/class OUTServlet

package com.neusoft.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.JOptionPane;

@WebServlet("/OUTServlet")
public class OUTServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        session.invalidate();//清除会话,也就是清除参数
        JOptionPane.showMessageDialog(null,"您已退出,请重新登录");
        response.sendRedirect(request.getContextPath()+"/Login.jsp");//重定向
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doGet(request, response);
    }

}

/class JDBCUtil

package com.neusoft.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCUtil {
    private static String driver="com.mysql.jdbc.Driver";
    private static String url="jdbc:mysql://localhost:3306/demo";
    private static String username="root";
    private static String password="123456";
    static{

        try {
            Class.forName(driver);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    public static Connection getConnection(){
            try {
                return DriverManager.getConnection(url, username, password);
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                return null;
            }
        }

    public static void close(Statement st,ResultSet rs,Connection conn){
        if (conn !=null) {
             try {
                conn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (rs !=null) {
            try {
                rs.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (st !=null) {
            try {
                st.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

/Login.jsp

<%@page import="java.util.UUID"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
   <%
     String uuid=UUID.randomUUID().toString();
     session.setAttribute("uuid", uuid);
   %>
   ${errorMsg}
   <form action="${pageContext.request.contextPath}/LoginServlet" method="post">
            <input type="hidden" name="uuid" value="<%=uuid%>"/>
                   用户名:<input type="text" name="username"/>
                   密码:<input type="password" name="pwd"/>
       <input type="submit" value="提交"/>
   </form>
   <a href="Regist.html">去注册</a>
</body>
</html>

  

<%@page import= "com.neuedu.bean.User"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
   <table border="1" align="center" width="50%">
      <tr>
         <th>姓名 </th>
         <th>密码 </th>
         <th colspan="2"> </th>
      </tr>
      <%-- <%
      List<User>stuList=new ArrayList<User>();
      stuList=(List<User>)request.getAttribute("stuList");
      for(int i=0;i<stuList.size();i++){
    	  User user=stuList.get(i);
    	  %> --%>
	        <tr>
	         <td><%-- <%=user.getName() %> --%>${user.name}</td>
	         <td><%-- <%=user.getPassword() %> --%>${user.password}</td>
	         <td><a href="#">修改</a></td>
	         <td><a href="#">删除</a></td>
	        </tr>
    	<%--   <%
         }
      %> --%>

   </table>
   <form action="${pageContext.request.contextPath}/OUTServlet" >
      <input type="submit"value="退出"/>
   </form>
</body>
</html>

  写之前导包

时间: 2024-10-07 15:07:46

SQL防止重复提交和Filter的相关文章

JAVA–利用Filter和session防止页面重复提交

JAVA–利用Filter和session防止页面重复提交解决思路:1 用户访问表单页面,先经过过滤器,过滤器设置一个随机id作为token令牌, 并将该token放入表单隐藏域中.2 表单响应到浏览器,用户填充数据后提交请求;3 请求经过过滤器,过滤器获取表单中的令牌进行验证,如果和之前生成的令牌一致,则将请求放行,并且清空令牌;4 如果用户重复提交表单,请求经过过滤器,过滤器进行验证.因为第一次放行后令牌已经清空失效,令牌不一致,不放行.跳转到提醒界面. 需用知识:1 过滤器基础知识2 se

7、struts2 案例( 模型驱动、 防止表单重复提交--拦截器 、数据回显 、值栈 、 OGNL表达式综合运用)

struts2 案例 技术点: 模型驱动 防止表单重复提交–拦截器 数据回显 值栈 OGNL表达式 通配符.路径匹配原则.常量 数据处理的集中方式 请求数据自动封装以及类型转换 1.导包 c3p0-0.9.1.2.jar commons-dbutils-1.6.jar commons-fileupload-1.2.2.jar commons-io-2.0.1.jar commons-lang3-3.1.jar freemarker-2.3.19.jar javassist-3.11.0.GA.j

struts2 模拟令牌机制防止表单重复提交

web.xml: <?xml version="1.0" encoding="UTF-8"?><web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http:

在JSP中动态生成随机验证码,登录时后台校验验证码,以及如何避免同一个验证码被重复提交爆破密码

只需几步就可以生成动态随机的验证码,最终效果如下图: 一 前台显示页面login.jsp 其中验证码显示的是一张图片,链接指向的是生成验证码的servlet,同时点击图片后触发changeImg()这个js函数,使其动态生成一个新的验证码,这个函数中的参数t=Math.random()并不会参与验证码的生成,它的作用仅仅只是表示每次提交的并不是同一个请求,需要单独处理,完整的login.jsp代码如下: <%@ page language="java" contentType=&

struts2 自带的 token防止表单重复提交拦截器

在struts2中,我们可以利用struts2自带的token拦截器轻松实现防止表单重复提交功能! 1. 在相应的action配置中增加:  <interceptor-ref name="token"></interceptor-ref> <result name="invalid.token">/error.jsp</result> 2. 增加error.jsp文件,代码如下:  <h1>禁止重复提交&l

Jquery 防止Ajax重复提交权威解决方案

在jquery开发中,我们常常遇到ajax重复提交问题,那如何解决ajax的重复提交呢?本文就将重点和大家分享这部分内容,一起来看看吧,希望可以帮助大家更好的学习ajax. ``` /* * jquery ajax请求过滤,防止ajax请求重复发送,对ajax发送错误时进行统一处理 / $(function(){ var pendingRequests = {}; // 所有ajax请求的通用前置filter $.ajaxPrefilter(function( options, original

struts2.3.16中表单重复提交出现空指针异常

异常代码形式: 严重: Exception occurred during processing request: nulljava.lang.NullPointerException    at com.opensymphony.xwork2.util.LocalizedTextUtil.findText(LocalizedTextUtil.java:630)    at com.opensymphony.xwork2.util.LocalizedTextUtil.findText(Local

Spring MVC服务器端防止重复提交

实现机制是使用token,简单说下: (a)进入下单页,会生成一个token,同时存在两个地方:session(或redis也可以)和页面 (b)提交时,服务器接收到页面的token后,会和session中的token比较,相同则允许提交,同时删除session中的token; (c)如果重复提交,则session中已经没有token(已被步骤b删除),那么校验不通过,则不会真正提交. 拦截器代码:下载 Java代码 package com.chanjet.gov.filter; import 

ASP.NET MVC 通过ActionFilterAttribute来实现防止重复提交

实现思想:每个页面打开的时候会在页面的隐藏控件自动生成一个值并将这个值赋值session,当提交方法的时候会在过滤器的时候进行获取session和页面传值过来的隐藏控件的值进行比较,如果值相同的话,重写session值.否则的话给出提示. ActionFilter: using System;using System.Web;using System.Web.Mvc;using EwayFramework.Utils.Token; namespace EwayFramework.BaseCont