当前位置: 代码迷 >> Java Web开发 >> struts2 往数据库存入数据出现重复存入,该怎么处理
  详细解决方案

struts2 往数据库存入数据出现重复存入,该怎么处理

热度:1457   发布时间:2013-02-25 21:19:33
struts2 往数据库存入数据出现重复存入
接受页面用户注册传来的数据存入MYSQL时 如果正常执行 return SUCCESS;命令 就会把数据存入MYSQL2次 如果没有没有执行return SUCCESS;命令就会正常存入一次 请帮帮我吧
RegisterAction.java

package com.god.sd;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;


public class RegisterAction extends ActionSupport{
private String msg;
public DB db = new DB();
public Connection conn;
public ResultSet rs;
public Statement stmt;
public String sql;
private String userName;
private String password;



public String execute() throws Exception{
try{

conn = db.getConn();
stmt = db.getStmt(conn);
System.out.println(conn);

sql = "select*from userid where username='" +this.userName+"' && password='"+ this.password + "'";
rs = db.executeQuery(stmt, sql);

if(rs.next()){
this.msg = "用户名已存在";
return INPUT;
}
conn.close();
stmt.close();
rs.close();

}catch(SQLException e){
e.printStackTrace();
}
return add();


public String add() throws Exception{

try {
conn = db.getConn();
stmt = db.getStmt(conn);;
String sql = "insert into userid value(null,'"+ this.userName+"','"+this.password+"',1);";
 
int a = stmt.executeUpdate(sql);
System.out.println(a);
if(a == 0){
System.out.println("添加失败");  
}else{
System.out.println("添加成功");
}
conn.close();
stmt.close();
return SUCCESS;
} catch (Exception e) {
e.printStackTrace();
}
return SUCCESS;
 
}
 
public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}


}

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
  "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
  "http://struts.apache.org/dtds/struts-2.0.dtd">
   
<struts>
   
  <constant name="struts.i18n.encoding" value="UTF-8"></constant>
  <constant name="struts.devMode" value="true" />
   

  <package name="front" extends="struts-default" >
   
  <action name="">
  <result>
  /logon.jsp
  </result>
  </action>  
   
   
  <action name="Logon" class="com.god.sd.Logon">
  <result name="error">/fail.jsp</result>
  <result name="success">/success.jsp</result>
  </action>
   
   
  <action name="Register" class="com.god.sd.RegisterAction">
   
  <result name="success">/success.jsp</result>
  相关解决方案
本站暂不开放注册!
内测阶段只得通过邀请码进行注册!