实体类RainManage:
package org.news.entity;
import java.util.Date;
public class RainManage {
//districtName,monitorTime,rain,monitoringStation,monitoringAddress
private Integer id; //主键id
private String districtName; //区域名称
private Date monitorTime; //监测时间
private Integer rain; //雨量
private String monitoringStation;//监测站
private String monitoringAddress;//站点地址
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDistrictName() {
return districtName;
}
public void setDistrictName(String districtName) {
this.districtName = districtName;
}
public Date getMonitorTime() {
return monitorTime;
}
public void setMonitorTime(Date monitorTime) {
this.monitorTime = monitorTime;
}
public Integer getRain() {
return rain;
}
public void setRain(Integer rain) {
this.rain = rain;
}
public String getMonitoringStation() {
return monitoringStation;
}
public void setMonitoringStation(String monitoringStation) {
this.monitoringStation = monitoringStation;
}
public String getMonitoringAddress() {
return monitoringAddress;
}
public void setMonitoringAddress(String monitoringAddress) {
this.monitoringAddress = monitoringAddress;
}
}
BaseDao层:
package org.news.dao;
/**
* 操作数据库的通用类
* @author Think
*
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.*;
import javax.sql.DataSource;
public class BaseDao {
protected Connection connection = null;
protected PreparedStatement preparedStatement = null;
protected ResultSet resultSet = null;
// 1、打开数据库
public Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/rain?useUnicode=true&characterEncoding=utf-8", "rootel","908071");
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
// 2、关闭所有资源
public void closeAll(Connection connection,
PreparedStatement preparedStatement, ResultSet result) {
if (result != null) {
try {
result.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// 3、增、删、改通用方法
public int executeUpdate(String sql, Object... param) {
int num = 0;// 影响行数
connection = this.getConnection();
try {
preparedStatement = connection.prepareStatement(sql);
// 为参数进行赋值
if (param != null) {
for (int i = 0; i < param.length; i++) {
preparedStatement.setObject(i + 1, param[i]);
}
}
// 执行SQL语句
num = preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
this.closeAll(connection, preparedStatement, null);
}
return num;
}
/**
* 执行查询操作 备注:此方法适用于纯查询使用,若是输入加查询需要另外设计
*
* @param sql
* 语句
* @return
*/
public ResultSet executeQuery(String sql, Object... param) {
connection = this.getConnection();
try {
// 发送SQL语句
preparedStatement = connection.prepareStatement(sql);
// 参数进行赋值
if (param != null) {
for (int i = 0; i < param.length; i++) {
preparedStatement.setObject(i + 1, param[i]);
}
}
// 返回结果集
resultSet = preparedStatement.executeQuery();
} catch (Exception e) {
closeAll(connection, preparedStatement, resultSet); // 关闭所有连接
System.out.println("发生异常:\n" + e.getMessage());
}
return resultSet;
}
}
接口类RainManageDao:
package org.news.dao;
import java.sql.SQLException;
import java.util.List;
import org.news.entity.RainManage;
public interface RainManageDao {
//全部雨量信息
List<RainManage> getAll() throws SQLException;
//根据ID删除雨量信息
int Del(int id);
//添加雨量
int insert(RainManage rainManage);
}
实现类RainManageDaoImpl:
package org.news.dao.impl;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.news.dao.BaseDao;
import org.news.dao.RainManageDao;
import org.news.entity.RainManage;
public class RainManageDaoImpl extends BaseDao implements RainManageDao {
//显示全部信息
@Override
public List<RainManage> getAll() throws SQLException {
connection = super.getConnection();
String sql = "select * from tb_rainquality ";
preparedStatement = connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
RainManage rainManage = null;
List<RainManage> list = new ArrayList<RainManage>();
//districtName,monitorTime,rain,monitoringStation,monitoringAddress
while (resultSet.next()){
rainManage=new RainManage();
rainManage.setId(resultSet.getInt("id"));
rainManage.setDistrictName(resultSet.getString("districtName"));
rainManage.setMonitorTime(resultSet.getDate("monitorTime"));
rainManage.setRain(resultSet.getInt("rain"));
rainManage.setMonitoringStation(resultSet.getString("monitoringStation"));
rainManage.setMonitoringAddress(resultSet.getString("monitoringAddress"));
list.add(rainManage);
}
// 关闭文档流
super.closeAll(connection, preparedStatement, resultSet);
return list;
}
@Override
public int Del(int id) {
String sql="DELETE FROM tb_rainquality WHERE id=?";
int result=0;
result=super.executeUpdate(sql,id);
return result;
}
@Override
public int insert(RainManage rainManage) {
String sql= "INSERT INTO tb_rainquality(districtName,monitorTime,rain,monitoringStation,monitoringAddress) VALUE(?,?,?,?,?);";
int result=0;
result=this.executeUpdate(sql,rainManage.getDistrictName(),rainManage.getMonitorTime(),rainManage.getRain(),
rainManage.getMonitoringStation(),rainManage.getMonitoringAddress());
return result;
}
}
服务层接口RainManageService类:
package org.news.service;
import java.sql.SQLException;
import java.util.List;
import org.news.entity.RainManage;
public interface RainManageService {
//全部雨量信息
List<RainManage> getAll() throws SQLException;
//根据ID删除雨量信息
int Del(int id);
//添加雨量
int insert(RainManage rainManage);
}
RainManageServiceImpl实现服务接口 类:
package org.news.service.impl;
import java.sql.SQLException;
import java.util.List;
import org.news.dao.RainManageDao;
import org.news.dao.impl.RainManageDaoImpl;
import org.news.entity.RainManage;
import org.news.service.RainManageService;
public class RainManageServiceImpl implements RainManageService {
@Override
public List<RainManage> getAll() throws SQLException {
RainManageDao rainManageDao =new RainManageDaoImpl();
return rainManageDao.getAll();
}
@Override
public int Del(int id) {
RainManageDao rainManageDao =new RainManageDaoImpl();
return rainManageDao.Del(id);
}
@Override
public int insert(RainManage rainManage) {
RainManageDao rainManageDao =new RainManageDaoImpl();
return rainManageDao.insert(rainManage);
}
}
BaseServlet反射辅助类:
package org.news.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class BaseServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public BaseServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
@Override
protected void service(HttpServletRequest request,HttpServletResponse response){
//创建java反射实现调用方法
//不需要依赖实例化的对象就可以拿到所有类的资源
try {
request.setCharacterEncoding("utf-8");
Class clazz=this.getClass();
String opr= request.getParameter("opr");
//this是拿到所有子类对象
//一开始加载主页的时候没有参数,默认是加载全部显示数据
if(opr==null){
opr="list";
}
//要找的方法的条件
Method me= clazz.getMethod(opr,
HttpServletRequest.class,
HttpServletResponse.class);
//调用method的方法
me.invoke(this,request, response);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
删除,DelServlet类:
package org.news.servlet;
import org.news.service.RainManageService;
import org.news.service.impl.RainManageServiceImpl;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name="DelServlet",urlPatterns = "/DelServlet")
public class DelServlet extends BaseServlet {
public void del(HttpServletRequest request, HttpServletResponse response){
response.setCharacterEncoding("utf-8");
int id=Integer.parseInt(request.getParameter("id"));
RainManageService rainManageService=new RainManageServiceImpl();
int result=rainManageService.Del(id);
//System.out.println(result);
}
}
添加,InsertServlet类:
package org.news.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.lang.model.element.NestingKind;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.news.entity.RainManage;
import org.news.service.RainManageService;
import org.news.service.impl.RainManageServiceImpl;
@WebServlet(name = "InsertServlet", urlPatterns = "/InsertServlet")
public class InsertServlet extends BaseServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
//添加的方法
public void insert(HttpServletRequest request, HttpServletResponse response) throws IOException, ParseException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out;
String contextPath = request.getContextPath();
//districtName,monitorTime,rain,monitoringStation,monitoringAddress
String districtName = request.getParameter("districtName");
Date monitorTime = new
SimpleDateFormat("yyyy-MM-dd")
.parse(request.getParameter("monitorTime"));
int rain = Integer.parseInt(request.getParameter("rain"));
String monitoringStation = request.getParameter("monitoringStation");
String monitoringAddress = request.getParameter("monitoringAddress");
RainManageService rainManageService = new RainManageServiceImpl();
RainManage rainManage = new RainManage();
rainManage.setDistrictName(districtName);
rainManage.setMonitorTime(monitorTime);
rainManage.setRain(rain);
rainManage.setMonitoringStation(monitoringStation);
rainManage.setMonitoringAddress(monitoringAddress);
int result = rainManageService.insert(rainManage);
out = response.getWriter();
if (result == -1) {
out.print("<script type=\"text/javascript\">");
out.print("alert(\"添加没有成功\");");
out.print("</script>");
} else if (result == 0) {
out.print("<script type=\"text/javascript\">");
out.print("alert(\"未找到相关信息\");");
out.print("</script>");
} else {
out.print("<script type=\"text/javascript\">");
out.print("alert(\"已经成功添加信息,点击确认返回首页\");");
out.print("location.href=\"" + contextPath
+ "/ListServlet?opr=list\";");
out.print("</script>");
}
}
}
显示全部信息的ListServlet类:
package org.news.servlet;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.news.entity.RainManage;
import org.news.service.RainManageService;
import org.news.service.impl.RainManageServiceImpl;
@WebServlet(name = "ListServlet", value = "/ListServlet")
public class ListServlet extends BaseServlet {
private static final long serialVersionUID = 1L;
// 查询
public void list(HttpServletRequest request, HttpServletResponse response) throws SQLException, ServletException, IOException {
RainManageService productService = new RainManageServiceImpl();
List<RainManage> list = new ArrayList<RainManage>();
list = productService.getAll();
request.setAttribute("list", list);
request.getRequestDispatcher("index.jsp").forward(request, response);
}
}
index.jsp主页:
<%--
Created by IntelliJ IDEA.
User: Think
Date: 2020/3/1
Time: 20:19
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>雨量信息输出</title>
</head>
<style>
* {
margin: 0px;
padding: 0px;
margin: auto;
}
tr:nth-child(2n) {
background-color: #fbc9a7
}
div {
text-align: center;
}
</style>
<body>
<script type="text/javascript" src="js/jquery-1.12.4.js"></script>
<script>
function del(id) {
var id2="#"+id;
//alert("进来了del")
var flag = confirm("确定要删除吗?");
if (flag == true) {
$(function () {
$.ajax({
url: "DelServlet?opr=del",//要提交的url路径
type: "get", // 发送的请求方法
data: "id=" + id, // 要发送到服务器的数据
dataType: "text", // 指定返回的数据格式
success: function (id) { //响应成功后要执行的代码
//在这里移除文本样式
$(id2).parent().parent().remove();
},
error: function () { // 请求失败后要执行的代码
alert("用户名验证时出现错误,请稍后再试或与管理员联系!");
}
});
});
}
}
</script>
<div>
<h3>雨量监测信息</h3>
<table border="1">
<tr>
<td>序号</td>
<td>区域名称</td>
<td>监测时间</td>
<td>雨量值(mm)</td>
<td>监测站</td>
<td>站点地址</td>
<td>操作</td>
</tr>
<c:forEach items="${requestScope.list}" var="i">
<tr>
<td>${i.id}</td>
<td>${i.districtName}</td>
<td>${i.monitorTime}</td>
<td>${i.rain}</td>
<td>${i.monitoringStation}</td>
<td>${i.monitoringAddress}</td>
<td><a href="javaScript:del(${i.id})" id="${i.id}">删除</a></td>
</tr>
</c:forEach>
</table>
<a href="insert.jsp">新增雨量监测信息</a>
</div>
</body>
</html>
Insert.jsp页面:
<%--
Created by IntelliJ IDEA.
User: Think
Date: 2020/3/1
Time: 22:23
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>新增雨量监测信息</title>
</head>
<style>
*{
margin: 0px;
padding: 0px;
margin: auto;
}
</style>
<body>
<script type="text/javascript" src="js/jquery-1.12.4.js"></script>
<script>
$(function () {
//清空事件
$('#reset').click(function () {
$('[type=text]').val('');
})
//保存的点击事件
$('#save').click(function(){
var districtName=$('#districtName').val();
var monitorTime=$('#monitorTime').val();
var r=new RegExp(/^(\d{4})-(0\d{1}|1[0-2])-(0\d{1}|[12]\d{1}|3[01])$/);//日期格式验证的正则表达式
var num=new RegExp(/^\d{1}$/);
var rain=$('#rain').val();
var monitoringStation=$('#monitoringStation').val();
var monitoringAddress=$('#monitoringAddress').val();
// alert(monitoringAddress+"测试成功")
if (districtName==""||monitorTime==""
||rain==""||monitoringStation==""
||monitoringAddress=="") {
alert("所有选项必填!")
}else if (!r.test(monitorTime)){
alert("日期格式不正确,必须是yyyy-MM-dd格式!")
}else if (!num.test(rain)){
alert("雨量值有误!");
}else{
window.location.href="javascript:document.form.submit()";
}
})
})
</script>
<div>
<h3>新增雨量监测信息</h3>
<form name="form" action="InsertServlet?opr=insert" method="post">
区域名称:<input type="text" name="districtName" id="districtName"><br>
监测时间:<input type="text" name="monitorTime" id="monitorTime"><span>yyyy-MM-dd格式</span><br>
雨量值(mm):<input type="text" name="rain" id="rain"><br>
监测站:<input type="text" name="monitoringStation" id="monitoringStation"><br>
站点地址:<input type="text" name="monitoringAddress" id="monitoringAddress"><br>
<input type="button" value="保存" id="save">
<input type="button" value="重置" id="reset">
<a href="javascript:history.go(-1)"><button type="button">返回</button></a>
</form>
</div>
</body>
</html>
来源:CSDN
作者:^Truth
链接:https://blog.csdn.net/qq_44739706/article/details/104619449