使用Struts2+JavaScript+Ajax实现成绩录入功能

基本需求:使用Struts2框架成绩录入功能。画面概要:(图1)


数据库表格 (tbl_scoreinfo):

姓名

Username

Varchar2(20)

 

课程名

Classname

Varchar2(20)

 

分数

Score

Number(4,1)

0-150

详细说明:

1,  当画面【初期化】显示时:

A)   画面姓名,课程,分数三个文本输入框,内容为空。

2,  当点击【保存】按钮时:

A)   输入检查

姓名,课程,分数都为为必须输入项目,如未输入,请报错!

分数,请做数据检查 0,150之间,可以包含130.5这样的数据,但无130.1这样的数据!

B)   输入完成后,请将输入数据插入到数据库表中。

C)   当数据已经存在时,请报错!

完成要求:

1,  实现追加功能,数据库插入

2,  实现数据检查(javascript)

3,  实现消息提示

(当追加成功,画面显示“保存成功”,并清空表单数据,等待二次数据填写)

  当有相同数据存在时,画面显示“数据已存在”,并要求用户修改数据。

web.xml:



	

	
		struts2
		org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
	

	
		struts2
		/*
	

	
		add.jsp
	



struts.xml:





    
    

    
        
            success.jsp
            error.jsp
        
    


add.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>






My JSP 'index.jsp' starting page










	
姓名:

课程:

分数:    

add.js:

function basicAjax(path, method, funcs) {
	var request;
	if (window.XMLHttpRequest) {
		request = new XMLHttpRequest();
	} else {
		request = new ActiveXObject("Microsoft.XMLHTTP");
	}
	request.onreadystatechange = function() {
		if (request.readyState == 4 && request.status == 200) {
			var back = request.responseText;
			funcs(back);
		}
	};
	request.open(method, path, true);
	if ("POST" == method) {
		request.send(path);
	} else {
		request.send();
	}
}

function onSubmit(){
	var username = document.addinfo.username.value;
    if (username.length == 0) {
    	alert("姓名不能为空!");  
        document.addinfo.username.focus();  
        return false;  
    } 
	var classname = document.addinfo.classname.value;
    if (classname.length == 0) {
    	alert("课程不能为空!");  
        document.addinfo.classname.focus();  
        return false;  
    } 
	var score = document.addinfo.score.value;
    if (score.length == 0) {
    	alert("分数不能为空!");  
        document.addinfo.score.focus();  
        return false;  
    } 
    
    /*//0-100之间数字的正则表达式,可以是整数,也可以含1位或者2位小数,含0和100
    var reg1 = /^(\d{1,2}(\.\d{1,2})?|100|100\.0|100\.00)$/;
    var reg2 = /^(\d{1,2}(\.\d{1,2})?|100(\.0{1,2})?)$/;
    
    //0-150之间的整数
    var reg = /^((\d{1,2})|(1[0-4]\d)|(150))$/;*/
    
	//数据检查 0,150之间,可以包含130.5这样的数据,但无130.1这样的数据
	var reg = /^(((\d{1,2})|(1[0-4]\d))(\.(0|5))?|(150|150\.0))$/;
	
    if(score.length > 0 && !reg.test(score)){
		alert("请重新输入0-150的分数!");  
		document.addinfo.score.focus();
		return false; 
    }
    var param = "scoreinfo.username=" + username + "&scoreinfo.classname=" 
          + classname + "&scoreinfo.score=" + score;
	var path = "./ScoreinfoAction_check?" + param;
		 
	basicAjax(path, "POST", function(result){
		if("exist" == result){
			alert("数据已存在,请重新输入!");
			document.addinfo.username.focus();
		}else{
			//document.addinfo.submit();
			var path = "./ScoreinfoAction_insert?" + param;
			basicAjax(path, "POST", function(result){
				if(1 == result){
					alert("保存成功!");
					//document.addinfo.reset();
					clearForm("addinfo");
					document.addinfo.username.focus(); 
				}else{
					alert("保存失败!");
				}
			});
		}
	});
}

function clearForm(id){
	var formId = document.getElementById(id);
	if (formId == undefined) {
	    return;
	}
	for(var i=0; i

Scoreinfo.java:

package zbiti.model;


public class Scoreinfo {


	private String username;
	private String classname;
	private double score;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getClassname() {
		return classname;
	}
	public void setClassname(String classname) {
		this.classname = classname;
	}
	public double getScore() {
		return score;
	}
	public void setScore(double score) {
		this.score = score;
	}
}



DB.java:

package zbiti.util;

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

public class DB {

	public static Connection getConnection(){
		Connection conn = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/project","root","root");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	public static PreparedStatement prepare(Connection conn, String sql){
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return ps;
	}
	
	public static void close(Connection conn){
		try {
			if(conn != null){
				conn.close();
				conn = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public static void close(PreparedStatement ps){
		try {
			if(ps != null){
				ps.close();
				ps = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public static void close(ResultSet rs){
		try {
			if(rs != null){
				rs.close();
				rs = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

ScoreinfoAction.java:

package zbiti.action;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import zbiti.model.Scoreinfo;
import zbiti.service.ScoreinfoService;

import com.opensymphony.xwork2.ActionSupport;

public class ScoreinfoAction extends ActionSupport {

	private static final long serialVersionUID = 1L;

	private ScoreinfoService service = new ScoreinfoService();
	private Scoreinfo scoreinfo;

	public Scoreinfo getScoreinfo() {
		return scoreinfo;
	}

	public void setScoreinfo(Scoreinfo scoreinfo) {
		this.scoreinfo = scoreinfo;
	}

	public String add() {
		int count = service.add(scoreinfo);
		if (count > 0) {
			return SUCCESS;
		} else {
			return ERROR;
		}
	}
	
	public String check() {
		int exist = service.check(scoreinfo);
		HttpServletResponse response = ServletActionContext.getResponse();
		try {
			if(exist == 1){
				response.getWriter().print("exist");
			}else{
				response.getWriter().print(" ");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public String insert() {
		int count = service.add(scoreinfo);
		HttpServletResponse response = ServletActionContext.getResponse();
		try {
			if(count > 0){
				response.getWriter().print(1);
			}else{
				response.getWriter().print(0);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

}

ScoreinfoService.java:

package zbiti.service;

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

import zbiti.model.Scoreinfo;
import zbiti.util.DB;

public class ScoreinfoService {

	public int add(Scoreinfo sc){
		Connection conn = DB.getConnection();
		String sql = "insert into tbl_scoreinfo (username,classname,score) value(?,?,?)";
		PreparedStatement ps = DB.prepare(conn, sql);
		int rowNum = 0;
		try {
			ps.setString(1, sc.getUsername());
			ps.setString(2, sc.getClassname());
			ps.setDouble(3, sc.getScore());
			rowNum = ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			DB.close(ps);
			DB.close(conn);
		}
		return rowNum;
	}
	
	public int check(Scoreinfo scoreinfo){
		Connection conn = DB.getConnection();
		String sql = "select count(1) from tbl_scoreinfo where username=? and classname=? and score=?";
		PreparedStatement ps = DB.prepare(conn, sql);
		ResultSet rs = null;
		int rowNum = 0;
		try {
			ps.setString(1, scoreinfo.getUsername());
			ps.setString(2, scoreinfo.getClassname());
			ps.setDouble(3, scoreinfo.getScore());
			rs = ps.executeQuery();
			while(rs.next()){
				rowNum = rs.getInt(1);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			DB.close(ps);
			DB.close(conn);
		}
		return rowNum;
	}
}

所需jar包:图2





你可能感兴趣的:(struts)