操作指南:

一、前端界面和后台服务器一一对应:查找出现的配对码“****”

二、在不使用框架的前提下,新建一个JavaWeb应用。

三、课时跨越:.§.第n课时


 

第1课时项目架构简单搭建及登录功能实现
一、环境介绍
二、项目介绍
  必须掌握java 基础,面向对象,JDBC,html,css,javascript,jsp,servlet 基础
三、登录界面简单设计
四、Servlet配置
五、Jsp EL表达式应用
六、客户端跳转 VS服务器端跳转
七、小作业——浏览器兼容

①环境要搭建好:乱码问题、服务器和IDE;

②新建一个Dynamic Web Project :StudentInfoManage、Dynamic web module version = 2.5;

  2.1、WebContent或WebRoot文件夹/WEB-INF/lib中引进jar包:mysql-connector-java-3.1.12-bin.jar;

  2.2、在src建包:dao、model、util、web;

  2.3、新建java文件:model.User、dao.UserDao、util.DbUtil、util.StringUtil;

package model;

public class User {
    private int id;
    private String userName;
    private String password;
    public User() {
        super();
    }
    public User(String userName, String password) {
        super();
        this.userName = userName;
        this.password = password;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    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;
    }
}
package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import model.User;

public class UserDao {

    public User login(Connection con,User user) throws Exception{
        User resultUser=null;
        String sql="select * from t_user where userName=? and password=?";
        PreparedStatement pstmt=con.prepareStatement(sql);
        pstmt.setString(1, user.getUserName());
        pstmt.setString(2, user.getPassword());
        ResultSet rs=pstmt.executeQuery();
        if(rs.next()){
            resultUser=new User();
            resultUser.setUserName(rs.getString("userName"));
            resultUser.setPassword(rs.getString("password"));
        }
        return resultUser;
    }
}
package util;

import java.sql.Connection;
import java.sql.DriverManager;

public class DbUtil {

    private String dbUrl="jdbc:mysql://localhost:3306/db_studentInfo";
    private String dbUserName="root";
    private String dbPassword="root";
    private String jdbcName="com.mysql.jdbc.Driver";
    
    public Connection getCon() throws Exception{
        Class.forName(jdbcName);
        Connection con=DriverManager.getConnection(dbUrl,dbUserName,dbPassword);
        return con;
    }
    public void closeCon(Connection con) throws Exception{
        if(con!=null){
            con.close();
        }
    }
    public static void main(String[] args) {
        DbUtil dbUtil=new DbUtil();
        try {
            dbUtil.getCon();
            System.out.println("数据库连接成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package util;

public class StringUtil {

    public static boolean isEmpty(String str){
        if("".equals(str)|| str==null){
            return true;
        }else{
            return false;
        }
    }
    public static boolean isNotEmpty(String str){
        if(!"".equals(str)&&str!=null){
            return true;
        }else{
            return false;
        }
    }
}

③在MySQL使用UTF-8,建立数据库db_studentInfo,表t_user,列userId,userName,password

  3.1、测试数据库连接:运行DbUtil.main()方法;

  3.2、随时测试相关方法。

④在WebContent或WebRoot,设计登录界面:index.jsp,注意:page标签charset=UTF-8,pageEncoding="UTF-8",meta标签charset=UTF-8

  4.1、title

  4.2.1、设计背景图

  4.2.2、【图片】新建images/login.jpg

  4.2.3、【工具】FireFox火狐浏览器的FireBug开发工具

  4.2.4、【提示】背景图片最好与<table>标签同大小

<div align="center" style="padding-top: 50px;">
        <table  width="740" height="500" background="images/login.jpg" >    
        </table>
    </div>

  4.3、设计“输入框”和“按钮”:在4.2.4的基础上,修改成

  4.4、【机制】通过form中的action请求login和post方法,服务器在web.xml中找到并执行所对应的Servlet。

<div align="center" style="padding-top: 50px;">
        <form action="login" method="post">
        <table  width="740" height="500" background="images/login.jpg" >
            <tr height="180">
                <td colspan="4"></td>
            </tr>
            <tr height="10">
                <td width="40%"></td>
                <td width="10%">用户名:</td>><!--【机制】JSP的EL表达式——增加用户体验“7861”-->
                <td><input type="text" value="${userName }" name="userName" id="userName"/></td>
                <td width="30%"></td>
            </tr>
            <tr height="10">
                <td width="40%"></td>
                <td width="10%">密  码:</td>><!--【机制】JSP的EL表达式——增加用户体验“7862”-->
                <td><input type="password" value="${password }" name="password" id="password"/></td>
                <td width="30%"></td>
            </tr>
            <tr height="10">
                <td width="40%"></td>
                <td width="10%"><input type="submit" value="登录"/></td>
                <td><input type="button" value="重置"/></td>
                <td width="30%"></td>
            </tr>
            <tr height="10">
                <td width="40%"></td>
                <td colspan="3"><!--【机制】JSP的EL表达式-->
                    <font color="red">${error }</font>
                </td>
            </tr>
            <tr >
                <td></td>
            </tr>
        </table>
        </form>
    </div>

  4.4.1、实现JavaScript“重置”功能:在index.jsp中找到此行并新增下划线部分

<td><input type="button" value="重置" onclick="resetValue()"/></td>

  4.4.2、在index.jsp中<head>标签中新增

<script type="text/javascript">
    function resetValue(){
        document.getElementById("userName").value="";
        document.getElementById("password").value="";
    }
</script>

⑤在web文件夹中新建Servlet文件:LoginServlet

  5.1、重写doGet()和doPost()方法,进行“服务器端验证”

  5.2、防止直接进入,可使用第额课时的Session

  5.3、测试的时候,要在t_user表中新增数据

package web;

import java.io.IOException;
import java.sql.Connection;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import dao.UserDao;
import model.User;
import util.DbUtil;
import util.StringUtil;

public class LoginServlet extends HttpServlet{

    DbUtil dbUtil=new DbUtil();
    UserDao userDao=new UserDao();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws gradedException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String userName=request.getParameter("userName");//从数据包中获取相关数据
        String password=request.getParameter("password");//从数据包中获取相关数据
        request.setAttribute("userName", userName);//【机制】JSP的EL表达式使用方法——增加用户体验“7861”
        request.setAttribute("password", password);//【机制】JSP的EL表达式使用方法——增加用户体验“7862”
        if(StringUtil.isEmpty(userName)||StringUtil.isEmpty(password)){
            request.setAttribute("error", "用户名或密码为空!");//【机制】JSP的EL表达式使用方法
            request.getRequestDispatcher("index.jsp").forward(request, response);//【机制】服务器跳转
            return;
        }
        User user=new User(userName,password);
        Connection con=null;
        try {
            con=dbUtil.getCon();
            User currentUser=userDao.login(con, user);
            if(currentUser==null){//【机制】JSP的EL表达式使用方法
                request.setAttribute("error", "用户名或密码错误!");
                // 【机制】服务器跳转
                request.getRequestDispatcher("index.jsp").forward(request, response);
            }else{
                // 【机制】获取Session.§.第2课时——显示当前用户“9648”
                HttpSession session=request.getSession();
                session.setAttribute("currentUser", currentUser);
                // 【机制】客户端跳转
                response.sendRedirect("main.jsp");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{//【提示】记得关闭
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

⑥在WebContent/WEB-INF/web.xml,新增:

<servlet>
      <servlet-name>LoginServlet</servlet-name>
      <servlet-class>web.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>LoginServlet</servlet-name>
      <url-pattern>/login</url-pattern>
  </servlet-mapping>

end.1


第2课时主界面简单实现
一、easyui简单介绍Demo:JQuery EasyUI中文网  http://www.jeasyui.net/二、主界面简单实现
三、权限验证 Session讲解

// 获取Session.§.第2课时
HttpSession session=request.getSession();
session.setAttribute("currentUser", currentUser);
<%
    // 权限验证.§.第2课时
    if(session.getAttribute("currentUser") == null) {
        response.sendRedirect("index.jsp");
        return;
    }
%>

 

①EasyUI实现:参考jar包中的Demo文件夹

  1.1、在WebContent或WebRoot文件夹中引进jar包:jquery-easyui-1.3.3.jar; 

注意:page标签charset=UTF-8,pageEncoding="UTF-8",meta标签charset=UTF-8

注意:href根据所放位置和所放文件夹命名有关系

<link rel="stylesheet" type="text/css"
    href="jquery-easyui-1.3.3/themes/default/easyui.css">
<link rel="stylesheet" type="text/css"
    href="jquery-easyui-1.3.3/themes/icon.css">
<script type="text/javascript" src="jquery-easyui-1.3.3/jquery.min.js"></script>
<script type="text/javascript"
    src="jquery-easyui-1.3.3/jquery.easyui.min.js"></script>
<script type="text/javascript"
    src="jquery-easyui-1.3.3/locale/easyui-lang-zh_CN.js"></script>

②【图片】新建images/main.jpg,

③修改<body>标签属性,

<body class="easyui-layout">
    <div region="north" style="height: 80px; background-color: #E0EDFF">
        <div align="left" style="width: 80%; float: left">
            <img src="images/main.jpg">
        </div>
        <div style="padding-top: 50px; padding-right: 20px;">
            当前用户: <font color="red">${currentUser.userName }</font><!--显示当前用户"9648" -->
        </div>

    </div>
    <div region="center">
        <div class="easyui-tabs" fit="true" border="false" id="tabs">
            <div title="首页">
                <div align="center" style="padding-top: 100px;">
                    <font color="red" size="10">欢迎使用</font>
                </div>
            </div>
        </div>
    </div>
    <div region="west" style="width: 150px;" title="导航菜单" split="true">
        <ul id="tree"></ul>
    </div>
    <div region="south" style="height: 50px;" align="center">
        版权所有<a href="http://www.baidu.com">百度一下,你就知道</a>
    </div>
</body>

④【机制】JS中$(function(){});文本加载完才会执行。

  4.1、新增数据树

<script type="text/javascript">
    $(function() {
        // 数据
        var treeData = [ {
            text : "根",
            children : [ {
                text : "班级信息管理",
                attributes : {
                    url : "gradeInfoManage.jsp"//请求此路径
                }
            }, {
                text : "学生信息管理",
                attributes : {
                    url : "studentInfoManage.jsp"//请求此路径
                }
            } ]
        } ];

        // 实例化树菜单
        $("#tree").tree({
            data : treeData,
            lines : true,
            onClick : function(node) {
                if (node.attributes) {
                    openTab(node.text, node.attributes.url);
                }
            }
        });

        // 新增Tab
        function openTab(text, url) {
            if ($("#tabs").tabs('exists', text)) {
                $("#tabs").tabs('select', text);
            } else {
                var content = "<iframe frameborder='0' scrolling='auto' style='width:100%;height:100%' src="
                        + url + "></iframe>";
                $("#tabs").tabs('add', {
                    title : text,
                    closable : true,
                    content : content
                });
            }
        }
    });
</script>

⑤在WebContent或WebRoot,创建两个JSP文件:gradeInfoManage.jsp和studentInfoManage.jsp

<%@ 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">

    <link rel="stylesheet" type="text/css" href="jquery-easyui-1.3.3/themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="jquery-easyui-1.3.3/themes/icon.css">
    <script type="text/javascript" src="jquery-easyui-1.3.3/jquery.min.js"></script>
    <script type="text/javascript" src="jquery-easyui-1.3.3/jquery.easyui.min.js"></script>
    <script type="text/javascript" src="jquery-easyui-1.3.3/locale/easyui-lang-zh_CN.js"></script>
    ...
  </head>
  <body>...</body>
</html>

⑥在main.jsp中开头补充session部分:【弊端】十个界面必须十个权限验证

⑦显示当前用户:配对码"9648"。

end.2


第3课时查询所有班级信息
一、easyui-datagrid引入
  Page 当前页
  Rows 每页的记录数
二、json jar包引入
  Json - lib
三、JsonUtil封装
四、ResponseUtil封装
五、PageBean封装
六、Mysql 分页
  String * fromtable limie start,size;
  Start=(page-1)*rows;

①在MySQL使用UTF-8,在数据库db_studentInfo,建立表t_grade,列gradeId,gradeName,gradeDesc,并弄点数据;

②设计gradeInfoManage.jsp界面:

<body>
    <table id="dg" title="班级信息" class="easyui-datagrid" fitColumns="true"
        fit="true" pagination="true" rownumbers="true" url="gradeList"
        toolbar="#tb">
        <thead>
            <tr>
                <th field="cb" checkbox="true"></th>
                <th field="gradeId" width="50" align="center">编号</th>
                <th field="gradeName" width="100" align="center">班级名称</th>
                <th field="gradeDesc" width="250" align="center">班级描述</th>
            </tr>
        </thead>
    </table>

    <div id="tb">
        <div>
            <a href="javascript:openGradeAddDialog()" class="easyui-linkbutton" iconCls="icon-add" plain="true">添加</a>|
            <a href="javascript:openGradeModifyDialog()" class="easyui-linkbutton" iconCls="icon-edit" plain="true">修改</a>| 
            <a href="javascript:deleteGrade()"
                class="easyui-linkbutton" iconCls="icon-remove" plain="true">删除</a>
        </div>
        <div>  班级信息: <input type="text" name="s_gradeText"
                id="s_gradeText" /><a href="javascript:searchGrade()"
                class="easyui-linkbutton" iconCls="icon-search" plain="true">搜索</a>
        </div>
    </div>
    <div id="dlg" class="easyui-dialog"
        style="width: 400px; height: 280px; padding: 10px 20px" closed="true"
        buttons="#dlg-buttons">
        <form id="fm" method="post">
            <table>
                <tr>
                    <td>班级名称:</td>
                    <td><input type="text" name="gradeName" id="gradeName"
                        class="easyui-validatebox" required="true" /></td>
                </tr>
                <tr>
                    <td valign="top">班级描述:</td>
                    <td><textarea rows="7" cols="30" name="gradeDesc"
                            id="gradeDesc"></textarea></td>
                </tr>
            </table>
        </form>
    </div>
    <div id="dlg-buttons">
        <a href="javascript:saveGrade()" class="easyui-linkbutton" iconCls="icon-ok" plain="true">保存</a>
        <a href="javascript:closeGradeDialog()" class="easyui-linkbutton" iconCls="icon-cancel" plain="true">关闭</a>
    </div>
    
</body>

③新建java文件:model.Grade;

package model;
import util.StringUtil;
public class Grade {
    private int gradeId;
    private String gradeName;
    private String gradeDesc;
    public Grade() {
        super();
    }
    public Grade(String gradeName, String gradeDesc) {
        super();
        if (StringUtil.isEmpty(gradeName)) {
            gradeName = "";
        }
        if (StringUtil.isEmpty(gradeDesc)) {
            gradeDesc = "";
        }
        this.gradeName = gradeName;
        this.gradeDesc = gradeDesc;
    }
    public int getGradeId() {
        return gradeId;
    }
    public void setGradeId(int gradeId) {
        this.gradeId = gradeId;
    }
    public String getGradeName() {
        return gradeName;
    }
    public void setGradeName(String gradeName) {
        this.gradeName = gradeName;
    }
    public String getGradeDesc() {
        return gradeDesc;
    }
    public void setGradeDesc(String gradeDesc) {
        this.gradeDesc = gradeDesc;
    }
}

④在web文件夹中新建Servlet文件:GradeListServlet

package web;

import java.io.IOException;
import java.sql.Connection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.GradeDao;
import model.Grade;
import model.PageBean;
import util.DbUtil;
import util.JsonUtil;
import util.ResponseUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class GradeListServlet extends HttpServlet{

    DbUtil dbUtil=new DbUtil();
    GradeDao gradeDao=new GradeDao();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String page=request.getParameter("page");
        String rows=request.getParameter("rows");
        String gradeName = request.getParameter("gradeText");
        String gradeDesc = request.getParameter("gradeText");
        Grade grade = new Grade(gradeName, gradeDesc);
        PageBean pageBean=new PageBean(Integer.parseInt(page),Integer.parseInt(rows));
        Connection con=null;
        try{
            con=dbUtil.getCon();
            JSONObject result=new JSONObject();
            JSONArray jsonArray=JsonUtil.formatRsToJsonArray(gradeDao.gradeList(con, pageBean,grade));
            int total=gradeDao.gradeCount(con, grade);
            result.put("rows", jsonArray);
            result.put("total", total);
            ResponseUtil.write(response, result);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

⑤在WebContent/WEB-INF/web.xml,新增:

<servlet>
      <servlet-name>GradeListServlet</servlet-name>
      <servlet-class>web.GradeListServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>GradeListServlet</servlet-name>
      <url-pattern>/gradeList</url-pattern>
  </servlet-mapping>

⑥重启服务,点击“学生信息管理”,gradeInfoManage.jsp页面请求gradeList地址,服务器执行GradeListServlet;在FireFox中FireBug查看post:【page】当前页和【rows】每页的记录数

⑦新建java文件:model.PageBean、dao.GradeDao、util.JsonUtil、util.ResponseUtil;

package model;

public class PageBean {

    private int page; // 第几页
    private int rows; // 每页记录数
    private int start;  // 起始页
    
    public PageBean(int page, int rows) {
        super();
        this.page = page;
        this.rows = rows;
    }
    
    public int getPage() {
        return page;
    }
    public void setPage(int page) {
        this.page = page;
    }
    public int getRows() {
        return rows;
    }
    public void setRows(int rows) {
        this.rows = rows;
    }
    public int getStart() {
        return (page-1)*rows;
    }
    public void setStart(int start) {
        this.start = start;
    }
}
package dao;

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

import model.Grade;
import model.PageBean;
import util.DbUtil;
import util.StringUtil;

public class GradeDao {

    public ResultSet gradeList(Connection con, PageBean pageBean, Grade grade)throws Exception{
        StringBuffer sb = new StringBuffer("select * from t_grade");
        if (grade != null && StringUtil.isNotEmpty(grade.getGradeName())) {
            sb.append(" and gradeName like '%"+grade.getGradeName()+"%' or gradeDesc like '%"+grade.getGradeDesc()+"%'");
        }
        if(pageBean!=null){
            sb.append(" limit "+pageBean.getStart()+","+pageBean.getRows());
        }
        PreparedStatement pstmt=con.prepareStatement(sb.toString().replaceFirst("and", "where"));
        return pstmt.executeQuery();
    }

    public int gradeCount(Connection con,Grade grade)throws Exception{
        StringBuffer sb = new StringBuffer("select count(*) as total from t_grade");
        if (grade != null && StringUtil.isNotEmpty(grade.getGradeName())) {
            sb.append(" and gradeName like '%"+grade.getGradeName()+"%'");
        }
        PreparedStatement pstmt=con.prepareStatement(sb.toString().replaceFirst("and", "where"));
        ResultSet rs=pstmt.executeQuery();
        if(rs.next()){
            return rs.getInt("total");
        }else{
            return 0;
        }
    }
    
    public int[] getGradeIdArray(Connection con) throws Exception{
        int size = gradeCount(con, null);
        int[] gradeIdArray = new int[size];
        String sql = "select * from t_grade";
        PreparedStatement pstmt = con.prepareStatement(sql);
        ResultSet rs = pstmt.executeQuery();
        int i = 0;
        while (rs.next()) {
            gradeIdArray[i++] = rs.getInt(1);
        }
        return gradeIdArray;
    }

    /**
     * delete from tableName where field in (1,3,5)
     * @param con
     * @param delIds
     * @return
     * @throws Exception
     */
    public int gradeDelete(Connection con,String delIds)throws Exception{
        String sql="delete from t_grade where gradeId in("+delIds+")";
        PreparedStatement pstmt=con.prepareStatement(sql);
        return pstmt.executeUpdate();
    }

    public int gradeAdd(Connection con, Grade grade) throws Exception{ 
        String sql = "insert into t_grade() values(null,?,?);";
        PreparedStatement pstmt = con.prepareStatement(sql);
        pstmt.setString(1, grade.getGradeName());
        pstmt.setString(2, grade.getGradeDesc());
        return pstmt.executeUpdate();
    }
    // .§.第5课时
    public int gradeModify(Connection con, Grade grade)throws Exception {
        String sql = "update t_grade set gradeName=?,gradeDesc=? where gradeId=?";
        PreparedStatement pstmt = con.prepareStatement(sql);
        pstmt.setString(1, grade.getGradeName());
        pstmt.setString(2, grade.getGradeDesc());
        pstmt.setInt(3, grade.getGradeId());
        return pstmt.executeUpdate();
    }
    
    // 测试方法
    public static void main(String[] args) {
        GradeDao gd = new GradeDao();
        Connection con = null;
        DbUtil db = new DbUtil();
        try {
            con = db.getCon();
            int[] arr = gd.getGradeIdArray(con);
            for (int i = 0; i < 40; i++) {
                gd.gradeAdd(con, new Grade(""+ (int)(Math.random()*10), "" + (int)(Math.random()*10)));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                db.closeCon(con);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
package util;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.Date;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class JsonUtil {

    public static JSONArray formatRsToJsonArray(ResultSet rs)throws Exception{
        ResultSetMetaData md=rs.getMetaData();
        int num=md.getColumnCount();
        JSONArray array=new JSONArray();
        while(rs.next()){
            JSONObject mapOfColValues=new JSONObject();
            for(int i=1;i<=num;i++){
                Object o=rs.getObject(i);
                if(o instanceof Date){
                    mapOfColValues.put(md.getColumnName(i), DateUtil.formatDate((Date)o, "yyyy-MM-dd"));
                }else{
                    mapOfColValues.put(md.getColumnName(i), rs.getObject(i));                    
                }
            }
            array.add(mapOfColValues);
        }
        return array;
    }
}
package util;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

public class ResponseUtil {

    public static void write(HttpServletResponse response,Object jsonObject)throws Exception{
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out=response.getWriter();
        out.println(jsonObject.toString());
        out.flush();
        out.close();
    }
}

第4课时查询及批量删除班级信息实现
一、easyui toolbar工具条、easyui linkbutton超链接按钮引入
二、班级信息查询实现
三、班级信息删除实现
四、Mysql SQL in用法
五、FireBug断点使用
Js 数组 join方法

①gradeInfoManage.jsp的<head>部分

<script type="text/javascript">
    var url;
    function searchGrade() {
        $('#dg').datagrid('load', {
            gradeText : $('#s_gradeText').val()
        });
    }

    function deleteGrade() {
        var selectedRows = $('#dg').datagrid('getSelections');
        if (selectedRows.length == 0) {
            $.messager.alert("系统提示", "请选择要删除的数据!");
            return;
        }
        var strIds = [];
        for (var i = 0; i < selectedRows.length; i++) {
            strIds.push(selectedRows[i].gradeId);
        }
        var ids = strIds.join(",");
        $.messager.confirm("系统提示", "您确认要删除这<font color=red>"
                + selectedRows.length + "</font>条数据吗?", function(r) {
            if (r) {
                $.post("gradeDelete", {
                    delIds : ids
                }, function(result) {
                    if (result.success) {
                        $.messager.alert("系统提示", "您已成功删除<font color=red>"
                                + selectedRows.length + "</font>条数据!");
                        $('#dg').datagrid('reload');
                    } else {
                        $.messager.alert("系统提示", "<font color=red>"+selectedRows[result.errorIndex].gradeName + "</font>"+ result.errorMsg);
                    }
                }, "json");
            } else {
                alert("no");
            }
        });
    }
    
    function openGradeAddDialog() {
        $('#dlg').dialog("open").dialog("setTitle","添加班级信息");
        url = "gradeSave";
    }
    
    function openGradeModifyDialog() {
        var selectedRows = $('#dg').datagrid('getSelections');
        var length = selectedRows.length;
        if (length != 1) {
            $.messager.alert("系统提示", "无法对<font color=red>"+length+"</font>条数据进行修改!");
            return;
        }
        var row = selectedRows[0];
        $('#dlg').dialog("open").dialog("setTitle","修改班级信息");
        $("#fm").form("load",row);
        url = "gradeSave?gradeId="+row.gradeId;
    }
    
    function closeGradeDialog() {
        $('#dlg').dialog('close');
        resetValue();
    }
    
    function resetValue() {
        $("#gradeName").val("");
        $("#gradeDesc").val("");
    }
    
    function saveGrade() {
        $("#fm").form("submit",{
            url:url,
            onSubmit:function() {
                return $(this).form("validate");
            },
            success:function(result) {
                if(result.errorMsg) {
                    $.messager.alert("系统提示",result.errorMsg);
                    return;
                } else {
                    $.messager.alert("系统提示","保存成功!");
                    resetValue();
                    $("#dlg").dialog("close");
                    $("#dg").datagrid("reload");
                }
            }
        });
    }
</script>

②在web文件夹中新建Servlet文件:GradeDeleteServlet

package web;

import java.io.IOException;
import java.sql.Connection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.GradeDao;
import dao.StudentDao;
import util.DbUtil;
import util.ResponseUtil;

import net.sf.json.JSONObject;

public class GradeDeleteServlet extends HttpServlet{
    
    DbUtil dbUtil=new DbUtil();
    GradeDao gradeDao=new GradeDao();
    StudentDao studentDao = new StudentDao();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String delIds = request.getParameter("delIds");
        Connection con=null;
        JSONObject result=new JSONObject();
        try{
            con=dbUtil.getCon();
            String[] str = delIds.split(",");
            for (int i = 0; i < str.length; i++) {
                boolean f = studentDao.getStudentByGradeId(con, str[i]);
                if (f) {
                    result.put("errorIndex",i);
                    result.put("errorMsg","班级下面有学生,不能删除!");
                    ResponseUtil.write(response, result);
                    return;
                }
            }
            int delNums = gradeDao.gradeDelete(con, delIds);
            if (delNums > 0) {
                result.put("success", "true");
                result.put("delNums", delNums);
            } else {
                result.put("errorMsg", "删除失败");
            }
            ResponseUtil.write(response, result);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

③在WebContent/WEB-INF/web.xml,新增:

<servlet>
      <servlet-name>GradeDeleteServlet</servlet-name>
      <servlet-class>web.GradeDeleteServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
      <servlet-name>GradeDeleteServlet</servlet-name>
      <url-pattern>/gradeDelete</url-pattern>
  </servlet-mapping>

第5课时班级信息添加和修改实现

一、easyui-dialog 对话框组件引入
二、easyui-validatebox 表单验证功能
三、添加和更新操作有效的合并编码
四、异步提交中文乱码问题解决
request.setCharacterEncoding("utf-8");

①在GradeDao.java中,新增gradeModify()方法:.§.第5课时

②在web文件夹中新建Servlet文件:GradeSaveServlet

package web;

import java.io.IOException;
import java.sql.Connection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.GradeDao;
import model.Grade;
import util.DbUtil;
import util.ResponseUtil;
import util.StringUtil;

import net.sf.json.JSONObject;

public class GradeSaveServlet extends HttpServlet{
    private static final long serialVersionUID = 4448691126075651701L;
    DbUtil dbUtil=new DbUtil();
    GradeDao gradeDao=new GradeDao();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
            request.setCharacterEncoding("utf-8");
            String gradeName=request.getParameter("gradeName");
            String gradeDesc=request.getParameter("gradeDesc");
            String id=request.getParameter("gradeId");
            Grade grade=new Grade(gradeName,gradeDesc);
            if(StringUtil.isNotEmpty(id)){
                grade.setGradeId(Integer.parseInt(id));
            }
            Connection con=null;
            try{
                con=dbUtil.getCon();
                int saveNums=0;
                JSONObject result=new JSONObject();
                if(StringUtil.isNotEmpty(id)){
                    saveNums=gradeDao.gradeModify(con, grade);
                }else{
                    saveNums=gradeDao.gradeAdd(con, grade);
                }
                if(saveNums>0){
                    result.put("success", "true");
                }else{
                    result.put("success", "true");
                    result.put("errorMsg", "保存失败");
                }
                ResponseUtil.write(response, result);
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                try {
                    dbUtil.closeCon(con);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

③在WebContent/WEB-INF/web.xml,新增:

<servlet>
      <servlet-name>GradeSaveServlet</servlet-name>
      <servlet-class>web.GradeSaveServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
      <servlet-name>GradeSaveServlet</servlet-name>
      <url-pattern>/gradeSave</url-pattern>
  </servlet-mapping>

第6课时学生信息查询实现
一、关联查询
二、easyui 下拉框、日期 控件介绍
三、easyui 下拉框 ajax取值
     知识点:
     1、SimpleDateFormat 使用
     2、判断对象类型instanceof

①在MySQL使用UTF-8,在数据库db_studentInfo,建立表t_student,列stuId,stuNo,stuName,sex,birthday,gradeId,email,并弄点数据;

alter table t_student add constraint FK_ID foreign key(gradeId) REFERENCES t_grade(gradeId);

③新建java文件:model.Student、dao.StudentDao;

package model;

import java.util.Date;

public class Student {

    private int stuId;
    private String stuNo;
    private String stuName;
    private String sex;
    private Date birthday;
    private int gradeId=-1;
    private String email;
    private String stuDesc;
    
    private String gradeName;
    
    
    public int getStuId() {
        return stuId;
    }
    public void setStuId(int stuId) {
        this.stuId = stuId;
    }
    public String getStuNo() {
        return stuNo;
    }
    public void setStuNo(String stuNo) {
        this.stuNo = stuNo;
    }
    public String getStuName() {
        return stuName;
    }
    public void setStuName(String stuName) {
        this.stuName = stuName;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public int getGradeId() {
        return gradeId;
    }
    public void setGradeId(int gradeId) {
        this.gradeId = gradeId;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getStuDesc() {
        return stuDesc;
    }
    public void setStuDesc(String stuDesc) {
        this.stuDesc = stuDesc;
    }
    public String getGradeName() {
        return gradeName;
    }
    public void setGradeName(String gradeName) {
        this.gradeName = gradeName;
    }
}
package dao;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Calendar;
import java.util.Random;

import model.PageBean;
import model.Student;
import util.DateUtil;
import util.DbUtil;
import util.StringUtil;


public class StudentDao {

    public ResultSet studentList(Connection con,PageBean pageBean,Student student,String bbirthday,String ebirthday)throws Exception{
        StringBuffer sb=new StringBuffer("select * from t_student s,t_grade g where s.gradeId=g.gradeId");
        if(StringUtil.isNotEmpty(student.getStuNo())){
            sb.append(" and s.stuNo like '%"+student.getStuNo()+"%'");
        }
        if(StringUtil.isNotEmpty(student.getStuName())){
            sb.append(" and s.stuName like '%"+student.getStuName()+"%'");
        }
        if(StringUtil.isNotEmpty(student.getSex())){
            sb.append(" and s.sex ='"+student.getSex()+"'");
        }
        if(student.getGradeId()!=-1){
            sb.append(" and s.gradeId ='"+student.getGradeId()+"'");
        }
        if(StringUtil.isNotEmpty(bbirthday)){
            sb.append(" and TO_DAYS(s.birthday)>=TO_DAYS('"+bbirthday+"')");
        }
        if(StringUtil.isNotEmpty(ebirthday)){
            sb.append(" and TO_DAYS(s.birthday)<=TO_DAYS('"+ebirthday+"')");
        }
        if(pageBean!=null){
            sb.append(" order by s.stuId asc limit "+pageBean.getStart()+","+pageBean.getRows());
        }
        PreparedStatement pstmt=con.prepareStatement(sb.toString());
        return pstmt.executeQuery();
    }
    
    public int studentCount(Connection con,Student student,String bbirthday,String ebirthday)throws Exception{
        StringBuffer sb=new StringBuffer("select count(*) as total from t_student s,t_grade g where s.gradeId=g.gradeId");
        if(StringUtil.isNotEmpty(student.getStuNo())){
            sb.append(" and s.stuNo like '%"+student.getStuNo()+"%'");
        }
        if(StringUtil.isNotEmpty(student.getStuName())){
            sb.append(" and s.stuName like '%"+student.getStuName()+"%'");
        }
        if(StringUtil.isNotEmpty(student.getSex())){
            sb.append(" and s.sex ='"+student.getSex()+"'");
        }
        if(student.getGradeId()!=-1){
            sb.append(" and s.gradeId ='"+student.getGradeId()+"'");
        }
        if(StringUtil.isNotEmpty(bbirthday)){
            sb.append(" and TO_DAYS(s.birthday)>=TO_DAYS('"+bbirthday+"')");
        }
        if(StringUtil.isNotEmpty(ebirthday)){
            sb.append(" and TO_DAYS(s.birthday)<=TO_DAYS('"+ebirthday+"')");
        }
        PreparedStatement pstmt=con.prepareStatement(sb.toString());
        ResultSet rs=pstmt.executeQuery();
        if(rs.next()){
            return rs.getInt("total");
        }else{
            return 0;
        }
    }
    
    public int studentDelete(Connection con,String delIds)throws Exception{
        String sql="delete from t_student where stuId in("+delIds+")";
        PreparedStatement pstmt=con.prepareStatement(sql);
        return pstmt.executeUpdate();
    }
    
    public int studentAdd(Connection con, Student student) throws Exception{ 
        String sql = "INSERT INTO `t_student`(`stuId`, `stuNo`, `stuName`, `sex`, `birthday`, `gradeId`, `email`, `stuDesc`) "
                + "VALUES (null,?,?,?,?,?,?,?)";
        PreparedStatement pstmt = con.prepareStatement(sql);
        pstmt.setString(1, student.getStuNo());
        pstmt.setString(2, student.getStuName());
        pstmt.setString(3, student.getSex());
        pstmt.setDate(4, new java.sql.Date(student.getBirthday().getTime()));
        pstmt.setInt(5, student.getGradeId());
        pstmt.setString(6, student.getEmail());
        pstmt.setString(7, student.getStuDesc());
        return pstmt.executeUpdate();
    }
    
    public int studentModify(Connection con, Student student) throws Exception{ 
        String sql = "update t_student set stuNo=?,stuName=?,sex=?,birthday=?,gradeId=?,email=?,stuDesc=? where stuId=?";
        PreparedStatement pstmt = con.prepareStatement(sql);
        pstmt.setString(1, student.getStuNo());
        pstmt.setString(2, student.getStuName());
        pstmt.setString(3, student.getSex());
        pstmt.setDate(4, new java.sql.Date(student.getBirthday().getTime()));
        pstmt.setInt(5, student.getGradeId());
        pstmt.setString(6, student.getEmail());
        pstmt.setString(7, student.getStuDesc());
        pstmt.setInt(8, student.getStuId());
        return pstmt.executeUpdate();
    }
    
    public boolean getStudentByGradeId(Connection con, String gradeId) throws Exception {
        String sql = "select * from t_student where gradeId = ?";
        PreparedStatement pstmt = con.prepareStatement(sql);
        pstmt.setString(1, gradeId);
        ResultSet rs = pstmt.executeQuery();
        if (rs.next()) {
            return true;
        } else {
            return false;
        }
    }
    
    public static void main(String[] args) {
        StudentDao dao = new StudentDao();
        DbUtil db = new DbUtil();
        Connection con = null;
        try {
            con = db.getCon();
            for (int i = 0; i < 40; i++) {
                dao.studentAdd(con, dao.createRandomStudent(con, i));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public Student createRandomStudent(Connection con, int i) throws Exception {
        Random r = new Random();
        int[] arr = new GradeDao().getGradeIdArray(con);
        Student student = new Student();
        student.setStuNo(r.nextInt(1000000000)+"");
        student.setStuName("a"+i);
        student.setSex(r.nextBoolean() ? "男" : "女");
        student.setBirthday(DateUtil.getRandomDate());
        student.setGradeId(arr[r.nextInt(arr.length)]);
        student.setEmail(r.nextInt(1000000000)+"@qq.com");
        student.setStuDesc(DateUtil.formatDate(new Date(Calendar.getInstance().getTimeInMillis()), DateUtil.PATTERN_DATE));
        return student;
    }
}

④在web文件夹中新建Servlet文件:StudentListServle

package web;

import java.io.IOException;
import java.sql.Connection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import dao.StudentDao;
import model.PageBean;
import model.Student;
import util.DbUtil;
import util.JsonUtil;
import util.ResponseUtil;
import util.StringUtil;

public class StudentListServlet extends HttpServlet{
    
    private static final long serialVersionUID = -5759695122299600894L;
    DbUtil dbUtil=new DbUtil();
    StudentDao studentDao=new StudentDao();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String stuNo=request.getParameter("stuNo");
        String stuName=request.getParameter("stuName");
        String sex=request.getParameter("sex");
        String bbirthday=request.getParameter("bbirthday");
        String ebirthday=request.getParameter("ebirthday");
        String gradeId=request.getParameter("gradeId");
        
        Student student = new Student();
        if(stuNo != null){
            student.setStuNo(stuNo);
            student.setStuName(stuName);
            student.setSex(sex);
            if(StringUtil.isNotEmpty(gradeId)){
                student.setGradeId(Integer.parseInt(gradeId));
            }
        }
        
        String page=request.getParameter("page");
        String rows=request.getParameter("rows");

        PageBean pageBean=new PageBean(Integer.parseInt(page),Integer.parseInt(rows));
        Connection con=null;
        try{
            con=dbUtil.getCon();
            JSONObject result=new JSONObject();
            JSONArray jsonArray=JsonUtil.formatRsToJsonArray(studentDao.studentList(con, pageBean, student, bbirthday, ebirthday));
            int total=studentDao.studentCount(con, student, bbirthday, ebirthday);
            result.put("rows", jsonArray);
            result.put("total", total);
            ResponseUtil.write(response, result);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

⑤在WebContent/WEB-INF/web.xml,新增:

<servlet>
      <servlet-name>StudentListServlet</servlet-name>
      <servlet-class>web.StudentListServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
      <servlet-name>StudentListServlet</servlet-name>
      <url-pattern>/studentList</url-pattern>
  </servlet-mapping>

⑥studentInfoManage.jsp新增部分:<head>和<body>

<script type="text/javascript">

    var url;
    function searchStudent() {
        $('#dg').datagrid('load', {
            stuNo : $("#s_stuNo").val(),
            stuName : $("#s_stuName").val(),
            sex : $("#s_sex").combobox("getValue"),
            bbirthday : $("#s_bbirthday").datebox("getValue"),
            ebirthday : $("#s_ebirthday").datebox("getValue"),
            gradeId : $("#s_gradeId").combobox("getValue")
        });
    }

    function deleteStudent() {
        var selectedRows = $('#dg').datagrid('getSelections');
        if (selectedRows.length == 0) {
            $.messager.alert("系统提示", "请选择要删除的数据!");
            return;
        }
        var strIds = [];
        for (var i = 0; i < selectedRows.length; i++) {
            strIds.push(selectedRows[i].stuId);
        }
        var ids = strIds.join(",");
        $.messager.confirm("系统提示", "您确认要删除这<font color=red>"
                + selectedRows.length + "</font>条数据吗?", function(r) {
            if (r) {
                $.post("studentDelete", {
                    delIds : ids
                }, function(result) {
                    if (result.success) {
                        $.messager.alert("系统提示", "您已成功删除<font color=red>"
                                + selectedRows.length + "</font>条数据!");
                        $('#dg').datagrid('reload');
                    } else {
                        $.messager.alert("系统提示", result.errorMsg);
                    }
                }, "json");
            } else {
                alert("no");
            }
        });
    }

    function openStudentAddDialog() {
        $('#dlg').dialog("open").dialog("setTitle", "添加学生信息");
        url = "studentSave";
    }
    
    function openStudentModifyDialog() {
        var selectedRows = $('#dg').datagrid('getSelections');
        var length = selectedRows.length;
        if (length != 1) {
            $.messager.alert("系统提示", "无法对<font color=red>"+length+"</font>条数据进行修改!");
            return;
        }
        var row = selectedRows[0];
        $('#dlg').dialog("open").dialog("setTitle", "修改学生信息");
        $("#fm").form("load",row);
        url = "studentSave?stuId="+row.stuId;
    }
    
    function saveStudent(){
        $("#fm").form("submit",{
            url:url,
            onSubmit:function(){
                if($('#sex').combobox("getValue")==""){
                    $.messager.alert("系统提示","请选择性别");
                    return false;
                }
                if($('#gradeId').combobox("getValue")==""){
                    $.messager.alert("系统提示","请选择所属班级");
                    return false;
                }
                return $(this).form("validate");
            },
            success:function(result){
                if(result.errorMsg){
                    $.messager.alert("系统提示",result.errorMsg);
                    return;
                }else{
                    $.messager.alert("系统提示","保存成功");
                    resetValue();
                    $("#dlg").dialog("close");
                    $("#dg").datagrid("reload");
                }
            }
        });
    }
    
    function closeStudentDialog() {
        $('#dlg').dialog('close');
        resetValue();
    }
    
    function resetValue(){
        $("#stuNo").val("");
        $("#stuName").val("");
        $("#sex").combobox("setValue","");
        $("#birthday").datebox("setValue","");
        $("#gradeId").combobox("setValue","");
        $("#email").val("");
        $("#stuDesc").val("");
    }
    
</script>
<body>
    <table id="dg" title="学生信息" class="easyui-datagrid" fitColumns="true"
        pagination="true" rownumbers="true" url="studentList" fit="true"
        toolbar="#tb">
        <thead>
            <tr>
                <th field="cb" checkbox="true"></th>
                <th field="stuId" width="50" align="center">编号</th>
                <th field="stuNo" width="100" align="center">学号</th>
                <th field="stuName" width="100" align="center">姓名</th>
                <th field="sex" width="100" align="center">性别</th>
                <th field="birthday" width="100" align="center">出生日期</th>
                <th field="gradeId" width="100" align="center"hidden="true">班级Id</th>
                <th field="gradeName" width="100" align="center">班级名称</th>
                <th field="email" width="150" align="center">Email</th>
                <th field="stuDesc" width="250" align="center">学生备注</th>
            </tr>
        </thead>
    </table>

    <div id="tb">
        <div>
            <a href="javascript:openStudentAddDialog()" class="easyui-linkbutton"
                iconCls="icon-add" plain="true">添加</a> <a
                href="javascript:openStudentModifyDialog()"
                class="easyui-linkbutton" iconCls="icon-edit" plain="true">修改</a> <a
                href="javascript:deleteStudent()" class="easyui-linkbutton"
                iconCls="icon-remove" plain="true">删除</a>
        </div>
        <div>
             学号: <input type="text" name="s_stuNo" id="s_stuNo"    size="10" /> 
             姓名: <input type="text" name="s_stuName" id="s_stuName" size="10" />  性别: 
            <select    class="easyui-combobox" id="s_sex" name="s_sex" editable="false" panelHeight="auto">
                <option value="">请选择...</option>
                <option value="男">男</option>
                <option value="女">女</option>
            </select> 
             出生日期: <input class="easyui-datebox" name="s_bbirthday"    id="s_bbirthday" editable="false" size="10" />
            -><input class="easyui-datebox" name="s_ebirthday" id="s_ebirthday" editable="false" size="10" /> 
             所属班级: <input class="easyui-combobox" id="s_gradeId" name="s_gradeId" size="10" data-options="panelHeight:'250',editable:false,valueField:'gradeId',textField:'gradeName',url:'gradeComboList'" />
            <a href="javascript:searchStudent()" class="easyui-linkbutton"
                iconCls="icon-search" plain="true">搜索</a>
        </div>
    </div>
<div id="dlg" class="easyui-dialog" style="width: 570px;height: 350px;padding: 10px 20px"
        closed="true" buttons="#dlg-buttons">
        <form id="fm" method="post">
            <table cellspacing="5px;">
                <tr>
                    <td>学号:</td>
                    <td><input type="text" name="stuNo" id="stuNo" class="easyui-validatebox" required="true"/></td>
                    <td>     </td>
                    <td>姓名:</td>
                    <td><input type="text" name="stuName" id="stuName" class="easyui-validatebox" required="true"/></td>
                </tr>
                <tr>
                    <td>性别:</td>
                    <td><select class="easyui-combobox" id="sex" name="sex" editable="false" panelHeight="auto" style="width: 155px">
                        <option value="">请选择...</option>
                        <option value="男">男</option>
                        <option value="女">女</option>
                    </select></td>
                    <td></td>
                    <td>出生日期:</td>
                    <td><input class="easyui-datebox" name="birthday" id="birthday" required="true" editable="false" /></td>
                </tr>
                <tr>
                    <td>班级名称:</td>
                    <td><input class="easyui-combobox" id="gradeId" name="gradeId"  data-options="panelHeight:'150',editable:false,valueField:'gradeId',textField:'gradeName',url:'gradeComboList'"/></td>
                    <td></td>
                    <td>Email:</td>
                    <td><input type="text" name="email" id="email" class="easyui-validatebox" required="true" validType="email"/></td>
                </tr>
                <tr>
                    <td valign="top">学生备注:</td>
                    <td colspan="4"><textarea rows="7" cols="50" name="stuDesc" id="stuDesc"></textarea></td>
                </tr>
            </table>
        </form>
    </div>
    <div id="dlg-buttons">
        <a href="javascript:saveStudent()" class="easyui-linkbutton" iconCls="icon-ok" plain="true">保存</a>
        <a href="javascript:closeStudentDialog()" class="easyui-linkbutton" iconCls="icon-cancel" plain="true">关闭</a>
    </div>
    
</body>

⑦新建java文件:util.DateUtil;

package util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

public class DateUtil {

    /**
     * yyyy年MM月dd日 hh:mm:ss
     */
    public static final String PATTERN_DATE = "yyyy年MM月dd日 hh:mm:ss";
    /**
     * yyyy-MM-dd
     */
    public static final String PATTERN_DATE_1 = "yyyy-MM-dd";
    private static SimpleDateFormat sdf=new SimpleDateFormat(PATTERN_DATE);
    
    public static String formatDate(Date date,String format){
        String result="";
        if(date!=null){
            result=sdf.format(date);
        }
        return result;
    }
    
    public static Date parseDate(String date, String pattern){
        Date d = null;
        if (!StringUtil.isEmpty(pattern)) {
            sdf.applyPattern(pattern);
        }
        try {
            d = sdf.parse(date);
            if (d == null) {
                throw new NullPointerException("【DateUtil.java】无法转换成日期类型!");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return d;
    }
    
    private static Random r = new Random();
    
    public static Date getRandomDate() {
        Calendar cal = Calendar.getInstance();
        cal.set(r.nextInt(cal.get(Calendar.YEAR)-1970)+1970, r.nextInt(12), 1);
        cal.add(Calendar.DAY_OF_YEAR, r.nextInt(365));
        return cal.getTime();
    }
    
    public static void main(String[] args) {
        
        try {
            System.out.println(parseDate("2016年07月11日 12:12:12", null));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
}

⑧在web文件夹中新建Servlet文件:GradeComboListServlet

package web;

import java.io.IOException;
import java.sql.Connection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import dao.GradeDao;
import model.Grade;
import util.DbUtil;
import util.JsonUtil;
import util.ResponseUtil;

public class GradeComboListServlet extends HttpServlet{
    
    DbUtil dbUtil=new DbUtil();
    GradeDao gradeDao=new GradeDao();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Connection con=null;
        try{
            con=dbUtil.getCon();
            JSONArray jsonArray=new JSONArray();
            Grade grade = new Grade("请选择", "");
            JSONObject obj = new JSONObject();
            obj.put("id", "");
            obj.put("gradeName", "请选择");
            obj.put("gradeDesc", "");
            jsonArray.add(grade);
            jsonArray.addAll(JsonUtil.formatRsToJsonArray(gradeDao.gradeList(con, null,null)));
            ResponseUtil.write(response, jsonArray);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

⑨在WebContent/WEB-INF/web.xml,新增:

<servlet>
      <servlet-name>GradeComboListServlet</servlet-name>
      <servlet-class>web.GradeComboListServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
      <servlet-name>GradeComboListServlet</servlet-name>
      <url-pattern>/gradeComboList</url-pattern>
  </servlet-mapping>

第7课时学生信息查询及删除实现

一、easyui 下拉框,日期控件取值
$("#s_sex").....dbobox("getValue")
二、mysql 日期范围查询
TO_DAYS()

①在web文件夹中新建Servlet文件:StudentDeleteServlet

package web;

import java.io.IOException;
import java.sql.Connection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.StudentDao;
import util.DbUtil;
import util.ResponseUtil;

import net.sf.json.JSONObject;

public class StudentDeleteServlet extends HttpServlet{
    private static final long serialVersionUID = 4448691126075651701L;
    DbUtil dbUtil=new DbUtil();
    StudentDao studentDao=new StudentDao();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String delIds = request.getParameter("delIds");
        Connection con=null;
        try{
            con=dbUtil.getCon();
            JSONObject result=new JSONObject();
            int delNums = studentDao.studentDelete(con, delIds);
            if (delNums > 0) {
                result.put("success", "true");
                result.put("delNums", delNums);
            } else {
                result.put("errorMsg", "删除失败");
            }
            ResponseUtil.write(response, result);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

②在WebContent/WEB-INF/web.xml,新增:

<servlet>
      <servlet-name>StudentDeleteServlet</servlet-name>
      <servlet-class>web.StudentDeleteServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
      <servlet-name>StudentDeleteServlet</servlet-name>
      <url-pattern>/studentDelete</url-pattern>
  </servlet-mapping>

第8课时学生信息添加修改实现
一、easyui datagrid 列隐藏
<th field="gradeId" width="100" align="center" hidden="true"> 班级
ID</th>
二、easyui 下拉框,日期控件值设置空
$("#sex").combobox("setValue","");
$("#birthday").datebox("setValue","");
三、easyui 提交前验证
四、添加和更新操作的有效合并
五、删除年级要进行判断

①在web文件夹中新建Servlet文件:StudentSaveServlet

package web;

import java.io.IOException;
import java.sql.Connection;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.StudentDao;
import model.Student;
import util.DateUtil;
import util.DbUtil;
import util.ResponseUtil;
import util.StringUtil;

import net.sf.json.JSONObject;

public class StudentSaveServlet extends HttpServlet{
    private static final long serialVersionUID = 4448691126075651701L;
    DbUtil dbUtil=new DbUtil();
    StudentDao studentDao=new StudentDao();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            request.setCharacterEncoding("utf-8");
            String stuNo=request.getParameter("stuNo");
            String stuName=request.getParameter("stuName");
            String sex=request.getParameter("sex");
            String birthday=request.getParameter("birthday");
            String gradeId=request.getParameter("gradeId");
            String email=request.getParameter("email");
            String stuDesc=request.getParameter("stuDesc");
            String stuId=request.getParameter("stuId");
            
            Student student = new Student();
            student.setStuNo(stuNo);
            student.setStuName(stuName);
            student.setSex(sex);
            student.setBirthday(DateUtil.parseDate(birthday, DateUtil.PATTERN_DATE_1));
            student.setGradeId(Integer.parseInt(gradeId));
            student.setEmail(email);
            student.setStuDesc(stuDesc);
            if(StringUtil.isNotEmpty(stuId)){
                student.setStuId(Integer.parseInt(stuId));
            }
            Connection con=null;
            try{
                con=dbUtil.getCon();
                int saveNums=0;
                JSONObject result=new JSONObject();
                if(StringUtil.isNotEmpty(stuId)){
                    saveNums=studentDao.studentModify(con, student);
                }else{
                    saveNums=studentDao.studentAdd(con, student);
                }
                if(saveNums>0){
                    result.put("success", "true");
                }else{
                    result.put("success", "true");
                    result.put("errorMsg", "保存失败");
                }
                ResponseUtil.write(response, result);
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                try {
                    dbUtil.closeCon(con);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

        
        
    }

②在WebContent/WEB-INF/web.xml,新增:

<servlet>
      <servlet-name>StudentSaveServlet</servlet-name>
      <servlet-class>web.StudentSaveServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
      <servlet-name>StudentSaveServlet</servlet-name>
      <url-pattern>/studentSave</url-pattern>
  </servlet-mapping>