注意要排除掉和自己比的情况
代码书写顺序:
--DAO
--Action
--struts.xml
--JSP
Action:
struts.xml
Jsp:
代码书写顺序:
--DAO
--Action
--struts.xml
--JSP
DAO:
public Cost findByNameOthers(String name,Integer id) throws DAOException {
if(name==null){
return null;
}
String sql = "select * from cost where name=? and id<>?";
Connection con = DBUtil.getConnection();
try {
PreparedStatement ps = con.prepareStatement(sql);
ps.setObject(1, name);
ps.setObject(2, id);
ResultSet rs = ps.executeQuery();
if(rs.next()){
Cost cost = createCost(rs);
return cost;
}
} catch (SQLException e) {
e.printStackTrace();
throw new DAOException("按照名称查询失败",e);
}finally{
DBUtil.close(con);
}
return null;
}
Action:
public class CheckCostNameOthersAction {
public String execute(){
ICostDAO dao = DAOFactory.getCostDAO();
try {
Cost cost = dao.findByNameOthers(name, id);
if(cost==null){
info.put("pass", true);
info.put("message", "资费名称可用");
}else{
info.put("pass", false);
info.put("message", "资费名称不可用");
}
} catch (DAOException e) {
e.printStackTrace();
info.put("pass", false);
info.put("message", "系统出现异常");
}
return "success";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Map<String, Object> getInfo() {
return info;
}
public void setInfo(Map<String, Object> info) {
this.info = info;
}
//input
private String name;
private Integer id;
//output
private Map<String, Object> info = new HashMap<String, Object>();
}
struts.xml
<!-- 修改时校验资费名称 -->
<action class="netctoss.action.CheckCostNameOthersAction" name="checkCostNameOthers">
<result type="json" name="success">
<param name="root">info</param>
</result>
</action>
Jsp:
<s:textfield name="cost.name" οnblur="checkCostName();" id="costName" cssClass="width300"/>
<span class="required">*</span>
<div class="validate_msg_short" id="costNameMsg">50长度的字母、数字、汉字和下划线的组合</div>
<!--javascript-->
//校验资费名称
function checkCostName(){
var costName = $("#costName").val();
var costId = $("#costId").val();
if(costName==""){
$("#costNameMsg").text("资费名称不能为空").addClass("error_msg");
}
//校验资费名称是否重复
$.post(
"checkCostNameOthers",
{"name":costName,"id":costId},
function(data){
var info = data;
alert(info);
$("#costNameMsg").text(info.message);
if(info.pass){
$("#costNameMsg").removeClass("error_msg");
}else{
$("#costNameMsg").addClass("error_msg");
}
}
);
}