Web前端HTML+与JQuery+JSP/Servlet与MySQL数据库:实现登录,增删改查+条件查询功能。

登录界面:

Web前端HTML+与JQuery+JSP/Servlet与MySQL数据库:实现登录,增删改查+条件查询功能。_第1张图片

登录后查询所有功能:

Web前端HTML+与JQuery+JSP/Servlet与MySQL数据库:实现登录,增删改查+条件查询功能。_第2张图片

修改功能:

Web前端HTML+与JQuery+JSP/Servlet与MySQL数据库:实现登录,增删改查+条件查询功能。_第3张图片

添加功能:

Web前端HTML+与JQuery+JSP/Servlet与MySQL数据库:实现登录,增删改查+条件查询功能。_第4张图片

MySQL数据库:

#创建数据库
create database 207userExam;
#使用数据库
use 207userExam;
#创建用户表
create table `user`(
	id int primary key auto_increment comment'主键自增',
	username varchar(30) not null comment'用户名',
	password varchar(30) not null comment'密码',
	regDate datetime comment'日期'
)charset'utf8';
#创建年级表
create table grade(
	id int primary key auto_increment,
	gradeName varchar(30) not null
)charset'utf8';
#创建考试信息表
create table examinfo(
	id int primary key auto_increment,
	name varchar(50) not null,
	gradeid int not null,
	examDate datetime comment'考试日期'
)charset'utf8';
#创建主外键关系
alter table examinfo add constraint fk_grade_examinfo foreign key(gradeid) references grade(id);
#添加用户数据
insert into `user` values
('1','admin','admin','2019-10-29');
#添加年级数据
insert into grade values
('1','s1学期一'),('2','s2学期二'),('3','y2学期三');
#添加考试信息数据
insert into examinfo values
('1','logicjava','1','2019-10-29'),
('2','winfom','1','2019-10-29'),
('3','javaoop','2','2019-10-29'),
('4','jsp/Servlet','2','2019-10-29'),
('5','bootstrap','3','2019-10-29'),
('6','spring','3','2019-10-29');
#表连查/二表
select * from examInfo as e inner join grade as g on e.`gradeId`=g.id;
#三表连查
select * from grade as g inner join examinfo as f on g.id=f.id left join `user` as u on g.id=u.id;

MyEclipse项目搭建结构
Web前端HTML+与JQuery+JSP/Servlet与MySQL数据库:实现登录,增删改查+条件查询功能。_第5张图片Web前端HTML+与JQuery+JSP/Servlet与MySQL数据库:实现登录,增删改查+条件查询功能。_第6张图片一、创建BaseDao连接数据库工具类

package org.exam.util;
import java.sql.*;
public class BaseDao {
	private static final String DRIVER = "com.mysql.jdbc.Driver";
	private final String url = "jdbc:mysql://localhost:3306/207userexam";
	private final String user = "root";
	private final String password = "root";
	
	//加载驱动
	static{
		try {
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	//建立连接
	public Connection getConnection(){
		Connection conn = null;
		try {
			 conn = DriverManager.getConnection(url, user, password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	//关闭连接
	public void closeAll(Connection conn,Statement stmt,ResultSet rs){
		if(rs!=null){
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(stmt!=null){
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(conn!=null){
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	//执行查询
	public ResultSet executeQuery(String sql,Object[] sz){
		Connection conn = getConnection();
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			 pstmt = conn.prepareStatement(sql);
			 if(sz!=null&&sz.length>0){
				 for (int i = 0; i < sz.length; i++) {
					 pstmt.setObject(i+1, sz[i]);
				}
			 }
			 rs = pstmt.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}
	//执行增删改
	public boolean executeUpdate(String sql,Object[] sz){
		Connection conn = getConnection();
		PreparedStatement pstmt = null;
		int row = 0;
		try {
			 pstmt = conn.prepareStatement(sql);
			 if(sz!=null&&sz.length>0){
				 for (int i = 0; i < sz.length; i++) {
					 pstmt.setObject(i+1, sz[i]);
				}
			 }
			 row = pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			closeAll(conn, pstmt, null);
		}
		return row>0;
	}

}

二、Web画页面布局
登录页面:login.jsp

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

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<style type="text/css">
		h1{
			text-align: center;
		}
		div{
			margin: auto;
		}
		#sub{
			text-align: center;
		}
	</style>
  </head>
  
  <body>
    <h1>教务平台登录</h1>
    <hr />
    <div>
    	<form action="loginServlet.shtml" method="post">
    		<p>
    			用户名:<input type="text" name="uName" value=""/>
    		</p>
    		<p>
    			密码:<input type="text" name="uPwd" value=""/>
    		</p>
    		<p>
    			<input type="submit" id="sub" value="登录"/>
    		</p>
    	</form>
    </div>
  </body>
</html>

查询所有主页面:index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
	<script type="text/javascript">
		$(function(){
			var gId = $("[name=gId]").attr("data");
			$("[name=gId]").val(gId);
		})
		
	</script>

  </head>
  
  <body>
    <h1 style="text-align: center;">考试信息列表</h1>
    <hr />
    <form action="selectServelt.shtml" method="post">
    	考试信息列表:<input type="text" name="eName" value="${TJ.name }" />
    	年级:
    	<select name="gId" data="${TJ.gradeid }">
  				<option value="0">全部</option>
  				<c:forEach items="${glist }" var="g">
  					<option value="${g.id }">${g.gradeName }</option>
  				</c:forEach>
  		</select>
    	<input type="submit" value="查询" />
    </form>
    <a href="add.jsp">添加</a>
    <form action="deleteServlet.shtml" method="post">
    	<input type="submit" value="批量删除" />
    	<table>
    		<tr>
    			<td>
    				<input type="checkbox" name="box" value="" />
    			</td>
    			<td>编号</td>
      			<td>考试类型名称</td>
      			<td>所属年级</td>
      			<td>考试日期</td>
      			<td>操作</td>
    		</tr>
    		<c:forEach items="${elist }" var="e">
    		<tr>
    			<td>
    				<input type="checkbox" name="boxs" value="${e.id }" />
    			</td>
    			<td>${e.id }</td>
	      		<td>${e.name }</td>
	      		<td>${e.grade.gradeName }</td>
	      		<td>${e.examDate }</td>
	      		<td>
	      			<a href="toUpdate.shtml?id=${e.id }">修改</a>
	      			<a href="delete.shtml?id=${e.id }" onclick="return confirm('确定删除吗?')">删除</a>
	      		</td>
    		</tr>
    		</c:forEach>
    	</table>
    </form>
  </body>
</html>

添加页面:add.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'add.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
    <h1>添加考试信息</h1>
    <hr />
    <form action="addServlet.shtml" method="post">
    	<p>
    		考试信息名称:<input type="text" name="eInfo" value=""/>
    	</p>
    	<p>&nbsp;&nbsp;<select name="gId">
      	  		<option value="0">全部</option>
      	  		<c:forEach items="${glist }" var="g">
      	  			<option value="${g.id }">${g.gradeName }</option>     	  			
      	  		</c:forEach>
      	  	</select>
    	</p>
    	<p>
    		考试日期:<input type="date" name="eDate" value="" />
    	</p>
    	<input type="submit" value="添加" />
    </form>
  </body>
</html>

修改页面:update.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'update.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
	<script type="text/javascript">
		$(function(){
			var gId = $("[name=gIds]").attr("data");
			$("[name=gIds]").val(gId);
		})
		
	</script>

  </head>
  
  <body>
    <h1>修改考试信息</h1>
    <hr />
    <form action="updateServlet.shtml" method="post">
    	<p>
    		<input type="hidden" name="eId" value="${exam.id }" />
    	</p>
    	<p>
    		考试信息名称:<input type="text" name="eInfo" value="${exam.name }"/>
    	</p>
    	<p>&nbsp;&nbsp;<select name="gIds" data="${exam.gradeid }">
      	  		<option value="0">全部</option>
      	  		<c:forEach items="${glist }" var="g">
      	  			<option value="${g.id }">${g.gradeName }</option>     	  			
      	  		</c:forEach>
      	  	</select>
      	</p>
      	<p>
      	  	考试日期:<input type="date" name="eDate" value="${exam.examDate }" />
      	</p>
      	<input type="submit" value="修改" />
    </form>
  </body>
</html>

三、编写实体类

package org.exam.entity;
import java.util.Date;
/**
 * 用户实体类
 * @author 065916
 *
 */
public class User {
	//定义属性
	private int id;
	private String username;
	private String password;
	private Date regDate;//日期
	
	//封装字段:提供getter/setter
	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;
	}
	public Date getRegDate() {
		return regDate;
	}
	public void setRegDate(Date regDate) {
		this.regDate = regDate;
	}

}
package org.exam.entity;
/**
 * 年级实体类
 * @author 065916
 *
 */
public class Grade {
	//定义字段
	private int id;
	private String gradeName;
	//封装
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getGradeName() {
		return gradeName;
	}
	public void setGradeName(String gradeName) {
		this.gradeName = gradeName;
	}

}
package org.exam.entity;
import java.util.Date;
/***
 * 考试信息实体类
 * @author 065916
 *
 */
public class Examinfo {
	//定义字段
	private int id;
	private String name;
	private int gradeid;
	private Date examDate;
	
	//在考试信息实体类中封装一个年级的对象
	private Grade grade;
	
	public Grade getGrade() {
		return grade;
	}
	public void setGrade(Grade grade) {
		this.grade = grade;
	}
	//封装
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getGradeid() {
		return gradeid;
	}
	public void setGradeid(int gradeid) {
		this.gradeid = gradeid;
	}
	public Date getExamDate() {
		return examDate;
	}
	public void setExamDate(Date examDate) {
		this.examDate = examDate;
	}
}

四、编写dao接口

package org.exam.dao;
import org.exam.entity.User;
/**
 * 用户接口类
 * @author 065916
 *
 */
public interface UserDao {
	//验证登录的方法
	public User checkLogin(User user);

}
package org.exam.dao;

import java.util.List;

import org.exam.entity.Grade;
//年级接口类
public interface GradeDao {
	//查询所有的年级
	public List<Grade> gatAllGrade();

}
package org.exam.dao;

import java.util.List;

import org.exam.entity.Examinfo;
//考试信息接口类
public interface ExaminfoDao {
	//查询功能+条件查询
	public List<Examinfo> getAll(Examinfo TJ);
	//按照id删除
	public boolean deleteById(int id);
	//添加考试信息
	public boolean addExaminfo(Examinfo info);
	//根据id查询考试信息对象
	public Examinfo selectExaminfoById(int id);
	//修改考试信息
	public boolean updateExaminfo(Examinfo info);

}

五、编写实现类

package org.exam.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.exam.dao.UserDao;
import org.exam.entity.User;
import org.exam.util.BaseDao;
//用户实现类
public class UserDaoImpl extends BaseDao implements UserDao{
	//查询用户
	@Override
	public User checkLogin(User user) {
		//第一步先写SQL语句
		String sql = "select * from user where username=? and password=?";
		//第二创建Object对象[]数组获取用户名/密码
		Object[] sz = {user.getUsername(),user.getPassword()};
		//第三调用查询的方法
		ResultSet rs= super.executeQuery(sql, sz);
		//第四创建对象给个空值
		User u = null;
		try {
			while(rs.next()){
				//每循环一次创建一次对象
				u = new User();
				u.setId(rs.getInt("id"));
				u.setUsername(rs.getString("username"));
				u.setPassword(rs.getString("password"));
				u.setRegDate(rs.getDate("regdate"));
				
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try {
				closeAll(rs.getStatement().getConnection(), rs.getStatement(), rs);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return u;
	}

}
package org.exam.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.exam.dao.GradeDao;
import org.exam.entity.Grade;
import org.exam.util.BaseDao;
//年级实现类
public class GradeDaoImpl extends BaseDao implements GradeDao{
	//查询所有的年级
	@Override
	public List<Grade> gatAllGrade() {
		//第一写SQL语句
		String sql = "select * from grade";
		//第二调用查询的方法
		ResultSet rs = super.executeQuery(sql, null);
		//第三创建集合对象
		List<Grade> list = new ArrayList<Grade>();
		try {
			while(rs.next()){
				//每循环一次创建对象
				Grade g = new Grade();
				g.setId(rs.getInt("id"));
				g.setGradeName(rs.getString("gradeName"));
				//放入list集合
				list.add(g);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try {
				closeAll(rs.getStatement().getConnection(), rs.getStatement(), rs);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return list;
	}

}

package org.exam.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.exam.dao.ExaminfoDao;
import org.exam.entity.Examinfo;
import org.exam.entity.Grade;
import org.exam.util.BaseDao;
//考试信息实现类
public class ExaminfoDaoImpl extends BaseDao implements ExaminfoDao{
	//查询功能+条件查询
	@Override
	public List<Examinfo> getAll(Examinfo TJ) {
		//第一写SQL语句
		String sql = "select * from examInfo as e inner join grade as g on e.`gradeId`=g.id where 1=1";
		//条件查询
		if(TJ.getName()!=null&&!TJ.getName().equals("")){
			sql = sql + " and e.name like '%"+TJ.getName()+"%'";
		}
		if(TJ.getGradeid()!=0){
			sql = sql + " and e.gradeId='"+TJ.getGradeid()+"'";
		}
		//调用查询的方法
		ResultSet rs = super.executeQuery(sql, null);
		//创建list集合对象
		List<Examinfo> list = new ArrayList<Examinfo>();
		try {
			while(rs.next()){
				//创建对象
				Examinfo exam = new Examinfo();
				exam.setId(rs.getInt("e.id"));
				exam.setName(rs.getString("e.name"));
				exam.setGradeid(rs.getInt("gradeid"));
				exam.setExamDate(rs.getDate("examDate"));
				
				//创建年级对象
				Grade grade = new Grade();
				grade.setId(rs.getInt("g.id"));
				grade.setGradeName(rs.getString("gradeName"));
				
				exam.setGrade(grade);
				//放入集合
				list.add(exam);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try {
				closeAll(rs.getStatement().getConnection(), rs.getStatement(), rs);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return list;
	}
	//按照id删除
	@Override
	public boolean deleteById(int id) {
		//第一写SQL语句
		String sql = "delete from examinfo where id=?";
		//创建对象数组获取id值
		Object[] sz = {id};
		return executeUpdate(sql, sz);
	}
	//添加考试信息
	@Override
	public boolean addExaminfo(Examinfo info) {
		//写SQL语句
		String sql = "insert into examinfo(name,gradeid,examDate) values(?,?,?)";
		//创建对象数组获取添加的值
		Object[] sz = {info.getName(),info.getGradeid(),info.getExamDate()};
		return super.executeUpdate(sql, sz);
	}
	//根据id查询考试信息对象
	@Override
	public Examinfo selectExaminfoById(int id) {
		//写SQL语句
		String sql = "select * from examinfo where id=?";
		//创建Object对象数组
		Object[] sz = {id};
		//调用BaseDao查询的方法
		ResultSet rs = super.executeQuery(sql, sz);
		//创建对象给个空值
		Examinfo e = null;
		try {
			while(rs.next()){
				e = new Examinfo();
				e.setId(rs.getInt("id"));
				e.setName(rs.getString("name"));
				e.setGradeid(rs.getInt("gradeid"));
				e.setExamDate(rs.getDate("examDate"));
			}
		} catch (SQLException e1) {
			e1.printStackTrace();
		}finally{
			try {
				closeAll(rs.getStatement().getConnection(), rs.getStatement(), rs);
			} catch (SQLException es) {
				es.printStackTrace();
			}
		}
		return e;
	}
	//修改考试信息
	@Override
	public boolean updateExaminfo(Examinfo info) {
		//写SQL语句
		String sql = "update examInfo set name=?,gradeid=?,examDate=? where id=?";
		//创建对象数组获取修改的值
		Object[] sz = {info.getName(),info.getGradeid(),info.getExamDate(),info.getId()};
		return super.executeUpdate(sql, sz);
	}

}

测试类

package org.exam.Manager;

import java.util.List;

import org.exam.dao.ExaminfoDao;
import org.exam.dao.GradeDao;
import org.exam.dao.UserDao;
import org.exam.dao.impl.ExaminfoDaoImpl;
import org.exam.dao.impl.GradeDaoImpl;
import org.exam.dao.impl.UserDaoImpl;
import org.exam.entity.Examinfo;
import org.exam.entity.Grade;
import org.exam.entity.User;

public class Test {
	public static void main(String[] args) {
		UserDao dao = new UserDaoImpl();
		User user = new User();
		user.setUsername("admin");
		user.setPassword("admin");
		User u = dao.checkLogin(user);
		System.out.println(u.getRegDate());
		
		
		
		GradeDao dao2 = new GradeDaoImpl();
		List<Grade> list = dao2.gatAllGrade();
		for (Grade grade : list) {
			System.out.println(grade.getGradeName());
		}
	}

}

六、编写Servlet实现功能

package org.exam.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 org.exam.dao.UserDao;
import org.exam.dao.impl.UserDaoImpl;
import org.exam.entity.User;
@WebServlet(urlPatterns="/loginServlet.shtml")
public class loginServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//设置编码格式
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		//接收传过来的参数
		String uName = request.getParameter("uName");
		String uPwd = request.getParameter("uPwd");
		
		//以对象为参数进行传参,将得到的参数封装到对象中
		User user = new User();
		user.setUsername(uName);
		user.setPassword(uPwd);
		
		//调用数据访问层
		UserDao dao = new UserDaoImpl();
		User u = dao.checkLogin(user);
		//工程根目录
		String contextPath = request.getContextPath();
		if(u!=null){
			response.sendRedirect(contextPath+"/selectServelt.shtml");
		}else{
			response.sendRedirect(contextPath+"/login.jsp");
		}

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
package org.exam.servlet;

import java.io.IOException;
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 org.exam.dao.ExaminfoDao;
import org.exam.dao.GradeDao;
import org.exam.dao.impl.ExaminfoDaoImpl;
import org.exam.dao.impl.GradeDaoImpl;
import org.exam.entity.Examinfo;
import org.exam.entity.Grade;
@WebServlet(urlPatterns="/selectServelt.shtml")
public class ExamInfoServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//编码格式
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		//获取页面传过来的条件参数
		String eName = request.getParameter("eName");
		String gId = request.getParameter("gId");
		
		//将参数进行非空判断后封装到对象中
		Examinfo TJ =new Examinfo();
		if(eName!=null&&!eName.equals("")){
			TJ.setName(eName);
		}
		if(gId!=null&&!gId.equals("0")){
			TJ.setGradeid(Integer.parseInt(gId));
		}
		
		//查询考试信息
		ExaminfoDao dao = new ExaminfoDaoImpl();
		List<Examinfo> elist = dao.getAll(TJ);
		//查询年级
		GradeDao gDao = new GradeDaoImpl();
		List<Grade> glist = gDao.gatAllGrade();
		//为了做数据回显,将TJ放入作用域中
		request.getSession().setAttribute("TJ", TJ);
		//将查询出的数据放入作用域
		request.getSession().setAttribute("elist", elist);
		request.getSession().setAttribute("glist", glist);
		//跳转页面,使用转发
		request.getRequestDispatcher("/index.jsp").forward(request, response);

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
package org.exam.servlet;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

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 org.exam.dao.ExaminfoDao;
import org.exam.dao.impl.ExaminfoDaoImpl;
import org.exam.entity.Examinfo;
@WebServlet(urlPatterns="/addServlet.shtml")
public class addServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//编码格式
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		String eName = request.getParameter("eInfo");
		String gId = request.getParameter("gId");
		String date =request.getParameter("eDate");
		//将字符串类型的值转换成date日期类型
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date d = null;
		try {
			d = sdf.parse(date);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Examinfo info = new Examinfo();
		info.setName(eName);
		info.setGradeid(Integer.parseInt(gId));
		info.setExamDate(d);
		ExaminfoDao dao = new ExaminfoDaoImpl();
		boolean isok = dao.addExaminfo(info);
		if(isok){
			request.getRequestDispatcher("/selectServelt.shtml").forward(request, response);
		}else{
			request.getRequestDispatcher("/add.jsp").forward(request, response);
		}

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
package org.exam.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 org.exam.dao.ExaminfoDao;
import org.exam.dao.impl.ExaminfoDaoImpl;
@WebServlet(urlPatterns="/delete.shtml")
public class danDelete extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//接受参数
		String id = request.getParameter("id");
		ExaminfoDao dao = new ExaminfoDaoImpl();
		boolean isok = dao.deleteById(Integer.parseInt(id));
		if(isok){
			request.getRequestDispatcher("/selectServelt.shtml").forward(request, response);
		}else{
			request.getRequestDispatcher("/selectServelt.shtml").forward(request, response);
		}

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
package org.exam.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 org.exam.dao.ExaminfoDao;
import org.exam.dao.impl.ExaminfoDaoImpl;
@WebServlet(urlPatterns="/deleteServlet.shtml")
public class piDeleteServelt extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String[] ids = request.getParameterValues("boxs");
		if(ids!=null&&!ids.equals("")){
			ExaminfoDao dao = new ExaminfoDaoImpl();
			boolean flag = false;
			for (int i = 0; i < ids.length; i++) {
				boolean isok = dao.deleteById(Integer.parseInt(ids[i]));
				if(isok == false){
					flag = true;
					break;
				}
			}
			if(flag == true){
				request.getRequestDispatcher("/selectServelt.shtml").forward(request, response);
			}else{
				request.getRequestDispatcher("/selectServelt.shtml").forward(request, response);
			}
		}else{
			request.getRequestDispatcher("/selectServelt.shtml").forward(request, response);
		}

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
package org.exam.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 org.exam.dao.ExaminfoDao;
import org.exam.dao.impl.ExaminfoDaoImpl;
import org.exam.entity.Examinfo;
@WebServlet(urlPatterns="/toUpdate.shtml")
public class toUpdateServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//接受id值
		String id = request.getParameter("id");
		ExaminfoDao dao = new ExaminfoDaoImpl();
		Examinfo exam = dao.selectExaminfoById(Integer.parseInt(id));
		
		//将查询出来的此考试信息对象放入作用域中,在跳转页面
		request.getSession().setAttribute("exam", exam);
		request.getRequestDispatcher("/update.jsp").forward(request, response);

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
package org.exam.servlet;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

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 org.exam.dao.ExaminfoDao;
import org.exam.dao.impl.ExaminfoDaoImpl;
import org.exam.entity.Examinfo;
@WebServlet(urlPatterns="/updateServlet.shtml")
public class updateServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//编码格式
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		//接收参数
		String eId=  request.getParameter("eId");
		String eName = request.getParameter("eInfo");
		String gId = request.getParameter("gIds");
		String date =request.getParameter("eDate");
		//将字符串类型的值转换成date日期类型
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date d = null;
		try {
			d = sdf.parse(date);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Examinfo info = new Examinfo();
		info.setId(Integer.parseInt(eId));
		info.setName(eName);
		info.setGradeid(Integer.parseInt(gId));
		info.setExamDate(d);
		
		ExaminfoDao dao = new ExaminfoDaoImpl();
		boolean isok = dao.updateExaminfo(info);
		if(isok){
			request.getRequestDispatcher("/selectServelt.shtml").forward(request, response);
		}else{
			request.getRequestDispatcher("/toUpdate.shtml").forward(request, response);
		}

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

你可能感兴趣的:(java,java动态增删改查)