完整的CRUD——javaweb
1,总体架构
index是进去的页面,
可以跳转Insert的增加页面,operatePerson是根据传进来的URI来判断增删改查的页面,
DbManager.java是封装的数据库操作类, Pagination.java是页脚的信息栏
2,index页面
final int pageSize = 5;//一页显示多少纪录
int pageNum = 1;//当前页数
int pageCount = 1;//总页数
int recordCount = 0;//总记录数
<form action="operatePerson.jsp" method="post">
<table border="1">
<%
for(; resultSet.next();){
out.println("<tr>");
String name = resultSet.getString("name");
out.println("<td>" + name + "</td>");
out.println("<td>" + resultSet.getString("age") + "</td>");
out.println("<td>" + resultSet.getString("sex") + "</td>");
out.println("<td><a href='operatePerson.jsp?action=delete&name=" + name +"'>删除</a></td>");
out.println("<td><a href='operatePerson.jsp?action=edit&name=" + name +"'>修改</a></td>");
out.println("</tr>");
}
%>
</table>
<%=Pagination.getPagination(pageNum, pageCount
, recordCount, request.getRequestURI()) %>
画出表,包括页脚,(上面的form其实没有什么用
分页技术使用数据库的 select * from person limit ?,? ----意思是从哪条开始(不包括这一条)的 n条记录
问号使用preparedStatement语句来实现
代码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.sql.DriverManager"%>
<%@ page import="java.sql.Connection"%>
<%@ page import="java.sql.Statement"%>
<%@ page import="java.sql.ResultSet"%>
<%@ page import="java.sql.PreparedStatement"%>
<%@ page import="java.sql.SQLException"%>
<%@ page import="testPackage.DbManager" %>
<%@ page import="testPackage.Pagination" %>
<%
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">
-->
</head> <%
final int pageSize = 5;//一页显示多少纪录
int pageNum = 1;//当前页数
int pageCount = 1;//总页数
int recordCount = 0;
try{//当前页数
pageNum = Integer.parseInt(request.getParameter("pageNum"));
System.out.println("0000:" + pageNum);
}catch(Exception e){}
String sql = null;
Connection con = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try{
sql = "select count(*) from person";
recordCount = DbManager.getCount(sql);
pageCount = (recordCount + pageSize - 1) / pageSize;
int startRecord = (pageNum - 1) * pageSize;
sql = "select * from person limit ?,?";
con = DbManager.getConnection();
preparedStatement = con.prepareStatement(sql);
DbManager.setParams(preparedStatement, startRecord, pageSize);
resultSet = preparedStatement.executeQuery();
%>
<body>
<a href="Insert.jsp">新建一个</a>
<form action="operatePerson.jsp" method="post">
<table border="1">
<%
for(; resultSet.next();){
out.println("<tr>");
String name = resultSet.getString("name");
out.println("<td>" + name + "</td>");
out.println("<td>" + resultSet.getString("age") + "</td>");
out.println("<td>" + resultSet.getString("sex") + "</td>");
out.println("<td><a href='operatePerson.jsp?action=delete&name=" + name +"'>删除</a></td>");
out.println("<td><a href='operatePerson.jsp?action=edit&name=" + name +"'>修改</a></td>");
out.println("</tr>");
}
%>
</table>
<%=Pagination.getPagination(pageNum, pageCount
, recordCount, request.getRequestURI()) %>
<br/>
<%=pageNum %>
</form>
<%
}catch(SQLException e1){
out.println("0001" + e1.getMessage());
}
finally {
if (resultSet != null)
resultSet.close();
if (preparedStatement != null)
preparedStatement.close();
if (con != null)
con.close();
}
%>
</body>
</html>
2,operatePerson.jsp页面
我写的时候没有使用DbManager类,在里面的增删改都用了原始的操作
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");//一定要
String action = request.getParameter("action");//先接受是什么操作
增:request.getPararmeter("name...")通过这个方法来获得表传进来的数据
删:request.getPararmeter("name")通过这个方法来获得uri传进来的paramer
改:request.getPararmeter("name")通过这个方法来获得uri传进来的paramer,(我设计的时候没有完善好,默认他们不能有同名,所以不能改名字
request.setAttribute("name", resultSet.getString("name")//把传进来的参数穿进去request里面,用forward转向到insert的页面在,那样insert可以从request里面提取数据(同时也把"save"信息传过去),和真正的插入有了区别
在insert会判断是save的传递,把数据传回来operate页面,做真正的修改
3,insert页面
会根据传过来的action判断是插入还是修改,以此来修改uri,form表给的提交方式要改为post ,因为这样表格的内容就不能形象uri的传递,
value="${name}"的时候,在修改的时候会显示值,注意:el表达式,${name}或者${requestScope.name}而不是${request.name}
4,Pagination.java
页脚,用StringBuffer类,append字符串
5,DbManager.java
数据库管理类
public static Connection getConnection(String dbName, String userName,String password)
public static Connection getConnection() //获得con对象
public static void setParams(PreparedStatement preparedStatement,Object... params) //把preparedStatement放进去,发若干个参数,preparedStatement.setInt.....之类的
public static int executeUpdate(String sql)
public static int executeUpdate(String sql, Object... params) //对上面方法的封装,穿进去sql的字符串就行了
源码:
DbManager
package testPackage; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types; public class DbManager {
public static Connection getConnection() throws SQLException,
ClassNotFoundException {
return getConnection("test", "kooing", "");
} public static Connection getConnection(String dbName, String userName,
String password) throws SQLException, ClassNotFoundException {
String url = "jdbc:mysql://localhost:3306/" + dbName;
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url);
return con;
} public static void setParams(PreparedStatement preparedStatement,
Object... params) throws SQLException {
for (int i = 1; i <= params.length; i++) {
Object param = params[i - 1];
if (param == null) {
preparedStatement.setNull(i, Types.NULL);
} else if (param instanceof Integer) {
preparedStatement.setInt(i, (Integer) param);
} else if (param instanceof String) {
preparedStatement.setString(i, (String) param);
}
}
} public static int executeUpdate(String sql) throws SQLException,
ClassNotFoundException {
return executeUpdate(sql, new Object[] {});
} public static int executeUpdate(String sql, Object... params)
throws SQLException, ClassNotFoundException {
Connection con = null;
PreparedStatement preparedStatement = null;
try {
con = getConnection();
preparedStatement = con.prepareStatement(sql);
setParams(preparedStatement, params);
return preparedStatement.executeUpdate();
} finally {
if (preparedStatement != null)
preparedStatement.close();
if (con != null)
con.close();
}
} public static int getCount(String sql) throws SQLException,
ClassNotFoundException {
Connection con = null;
Statement statement = null;
ResultSet rs = null;
try {
con = getConnection();
statement = con.createStatement();
rs = statement.executeQuery(sql);
rs.next();
return rs.getInt(1);
} finally {
if (rs != null)
rs.close();
if (statement != null)
statement.close();
if (con != null)
con.close();
}
}
}
Pagination
package testPackage; public class Pagination {
public static String getPagination(int pageNum, int pageCount,
int recordCount, String pageUrl) {
String url = pageUrl.contains("?") ? pageUrl : pageUrl + "?";
if (!url.endsWith("?") && !url.endsWith("&")) {
url += "&";
}
StringBuffer buffer = new StringBuffer();
buffer.append("第 " + pageNum + "/" + pageCount + "页,共" + recordCount
+ "纪录。");
buffer.append(pageNum == 1 ? "第一页" : "<a href='" + url
+ "pageNum=1'>第一页</a>");
// buffer.append(pageNum == 1 ? "第一页" : "<a href='" + url + "pageNum=" +
// 1
// + "'>第一页</a>"); buffer.append(pageNum == 1 ? "上一页" : "<a href='" + url + "pageNum="
+ (pageNum - 1) + "'>上一页</a>"); buffer.append(pageNum == pageCount ? "下一页" : "<a href='" + url
+ "pageNum=" + (pageNum + 1) + "'>下一页</a>"); buffer.append(pageNum == pageCount ? "最后一页" : "<a href='" + url
+ "pageNum=" + pageCount + "'>最后一页</a>");
return buffer.toString();
}
}
index
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.sql.DriverManager"%>
<%@ page import="java.sql.Connection"%>
<%@ page import="java.sql.Statement"%>
<%@ page import="java.sql.ResultSet"%>
<%@ page import="java.sql.PreparedStatement"%>
<%@ page import="java.sql.SQLException"%>
<%@ page import="testPackage.DbManager" %>
<%@ page import="testPackage.Pagination" %>
<%
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">
-->
</head> <%
final int pageSize = 5;//一页显示多少纪录
int pageNum = 1;//当前页数
int pageCount = 1;//总页数
int recordCount = 0;
try{//当前页数
pageNum = Integer.parseInt(request.getParameter("pageNum"));
System.out.println("0000:" + pageNum);
}catch(Exception e){}
String sql = null;
Connection con = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try{
sql = "select count(*) from person";
recordCount = DbManager.getCount(sql);
pageCount = (recordCount + pageSize - 1) / pageSize;
int startRecord = (pageNum - 1) * pageSize;
sql = "select * from person limit ?,?";
con = DbManager.getConnection();
preparedStatement = con.prepareStatement(sql);
DbManager.setParams(preparedStatement, startRecord, pageSize);
resultSet = preparedStatement.executeQuery();
%>
<body>
<a href="Insert.jsp">新建一个</a>
<form action="operatePerson.jsp" method="post">
<table border="1">
<%
for(; resultSet.next();){
out.println("<tr>");
String name = resultSet.getString("name");
out.println("<td>" + name + "</td>");
out.println("<td>" + resultSet.getString("age") + "</td>");
out.println("<td>" + resultSet.getString("sex") + "</td>");
out.println("<td><a href='operatePerson.jsp?action=delete&name=" + name +"'>删除</a></td>");
out.println("<td><a href='operatePerson.jsp?action=edit&name=" + name +"'>修改</a></td>");
out.println("</tr>");
}
%>
</table>
<%=Pagination.getPagination(pageNum, pageCount
, recordCount, request.getRequestURI()) %>
<br/>
<%=pageNum %>
</form>
<%
}catch(SQLException e1){
out.println("0001" + e1.getMessage());
}
finally {
if (resultSet != null)
resultSet.close();
if (preparedStatement != null)
preparedStatement.close();
if (con != null)
con.close();
}
%>
</body>
</html>
operate
<%@page import="java.sql.DriverManager"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.sql.DriverManager"%>
<%@ page import="java.sql.Connection"%>
<%@ page import="java.sql.Statement"%>
<%@ page import="java.sql.ResultSet"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<%
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String action = request.getParameter("action");
String sql = null;
if ("add".equals(action)) {
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
String sex = request.getParameter("sex");
sql = "insert into person values('" + name + "','" + age
+ "','" + sex + "')";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "kooing", "");
Statement sm = con.createStatement();
int resultSet = sm.executeUpdate(sql);
out.println(sql);
} catch (Exception e) { }
}
if ("delete".equals(action)) {
String name = request.getParameter("name");
System.out.println(name);
sql = "delete from person where name = '" + name + "'";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "kooing", "");
Statement sm = con.createStatement();
int resultSet = sm.executeUpdate(sql);
out.println(sql);
} catch (Exception e) { }
}
if ("edit".equals(action)) {
try {
String name = request.getParameter("name");
sql = "select * from person where name ='" + name + "'";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "kooing", "");
Statement sm = con.createStatement();
ResultSet resultSet = sm.executeQuery(sql);
out.println(sql);
resultSet.next();
request.setAttribute("name", resultSet.getString("name"));
request.setAttribute("age", resultSet.getString("age"));
request.setAttribute("sex", resultSet.getString("sex"));
request.setAttribute("action", action);
request.getRequestDispatcher("Insert.jsp").forward(request,
response);
} catch (Exception e) {
}
}
if("save".equals(action)){
String name = request.getParameter("name");
int age = Integer.parseInt(request.getParameter("age"));
String sex = request.getParameter("sex");
sql = "update person set "
+ "name='" + name
+ "',age='" + age
+ "',sex='" + sex + "' where name ='" + name +"'";
System.out.println(sql);
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test",
"kooing", "");
Statement sm = con.createStatement();
int result = sm.executeUpdate(sql);
}
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>My JSP 'operatePerson.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>
This is my JSP page.
<br>
<a href="index.jsp">主页</a>
</body>
</html>
insert
<%@ 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 'Insert.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>
<%
String myAction = (String)request.getAttribute("action");
myAction = myAction == null? "add" : "save";
System.out.println(myAction);
System.out.println(request.getAttribute("name"));
System.out.println(request.getAttribute("age"));
System.out.println(request.getAttribute("sex"));
%>
<form action="operatePerson.jsp?action=<%=myAction %>" method="post">
姓名<input type="text" name="name" value="${name }"><br/>
年龄<input type="text" name="age" value="${age }"><br/>
性别<input type="text" name="sex" value="${sex }"><br/>
<input type="submit">
</form>
</body>
</html>
完整的CRUD——javaweb的更多相关文章
- Servlet(六):连接数据库,完整的CRUD
Servlet的知识点大致讲完了,今天补充下与之相关的一些小知识,然后做一个完整的小例子. 一.MVC设计模式 1.MVC设计模式是什么? 在了解MVC之前,先聊聊Model1.Model2开发模式. ...
- SpringMVC+easyUI 分页,查询 (完整的CRUD)
最终完毕CRUD的功能了,注意,这里会对前面有一些修改,UserController的listUser() 已经改写了,如今把所有整理一下吧. JSP: <%@ page language=&q ...
- [MyBatis]完整MyBatis CRUD工程
下载地址:https://files.cnblogs.com/files/xiandedanteng/Person191005.rar pom.xml:这个文件主要是引入依赖 <project ...
- JavaWeb学习总结(转载)
JavaWeb学习总结(五十三)--Web应用中使用JavaMail发送邮件 JavaWeb学习总结(五十二)--使用JavaMail创建邮件和发送邮件 JavaWeb学习总结(五十 ...
- Hibernate(5)—— 联合主键 、一对一关联关系映射(xml和注解) 和 领域驱动设计
俗话说,自己写的代码,6个月后也是别人的代码……复习!复习!复习!涉及的知识点总结如下: One to One 映射关系 一对一单向外键(XML/Annotation) 一对一双向外键关联(XML/A ...
- 纯前端JSON文件编辑器[0]
准备工作 参考资料: FileReader(用来获取上传文件的数据) <download>(用来设置下载文件的名称) Blob(用来存储数据的一个容器) createObjectURL(用 ...
- angularjs的简单应用(一)
AngularJS是为了克服html在构建应用上的不足而设计的.HTML是一门很好的为静态文本展示设计的声明式语言,但要构建WEB应用的话它就显得乏力了. AngularJS使用了不同的方法,它尝试去 ...
- 前端的数据库:IndexedDB 。 ps:入门
应用程序需要数据.对大多数Web应用程序来说,数据在服务器端组织和管理,客户端通过网络请求获取.随着浏览器变得越来越有能力,因此可选择在浏览器存储和操纵应用程序数据. 本文向你介绍名为IndexedD ...
- 演练5-5:Contoso大学校园管理系统5
Contoso University示例网站演示如何使用Entity Framework 5创建ASP.NET MVC 4应用程序. Entity Framework有三种处理数据的方式: Data ...
随机推荐
- Android Studio 入门级教程
引用原文:http://www.cnblogs.com/abao0/p/6934023.html 写博客是为了记住自己容易忘记的东西,另外也是对自己工作的总结,文章可以转载,无需版权.希望尽自己的努力 ...
- JavaEE初始化时静态代码块加载问题
1.使用java.exe命令运行某个类的时java.exe Person2.创建一个类的对象时Person p=new Person();3.访问类中的静态成员变量(赋值/获取值)System.out ...
- Graph_Master(连通分量_A_双连通分量+桥)
hdu 5409 题目大意:给出一张简单图,求对应输入的m条边,第i-th条边被删除后,哪两个点不连通(u,v,u<v),若有多解,使得u尽量大的同时v尽量小. 解题过程:拿到题面的第一反应缩点 ...
- Spark Configuration配置
Spark可以通过三种方式配置系统: 通过SparkConf对象, 或者Java系统属性配置Spark的应用参数 通过每个节点上的conf/spark-env.sh脚本为每台机器配置环境变量 通过lo ...
- 前端人脸识别框架Tracking.js与JqueryFaceDetection
这篇文章主要就介绍两种前端的人脸识别框架(Tracking.js和JqueryFaceDetection) 技术特点 Tracking.js是使用js封装的一个框架,使用起来需要自己配置许多的东西,略 ...
- angular 图片懒加载(延迟加载)
github 原文 https://github.com/Treri/me-lazyload me-lazyload angular 的图像资源延迟加载指令 例子(Demo) 演示网站(Demo Si ...
- 阻止a标签跳转四种方法 兼容各大浏览器(包括IE)
阻止a标签跳转四种方法 兼容各大浏览器(包括IE) HTML <!--第一种--> <a href="javascript:;">我不会被跳转</a& ...
- javascript异步编程的几种方法
目前工作中用的比较多的异步模式编程有如下几种方法 一 回调函数 这是异步编程最基本的方法,假设有两个函数f1和f2,后者等待前者的执行结果 f1(); f2(); 如果f1是一个很耗时的任务,可以考虑 ...
- Appium 自动化测试(4)-- 脚本开发:官方demo演示 android_contacts.py
前提:根据前面的环境搭建介绍,安装好相关环境 step1:启动android模拟器 step2:启动Appium服务端 step3:演示代码执行 这里执行的是官方的演示代码:通讯录管理app,安装打开 ...
- request方法传入动态参数的一个"误区"
晚上写了一个请求类,传了一个动态参数进去,实例化测试的时候,发现请求数据根本没法读到,先附上代码 import requests class MyRequests: def send_request( ...