业务逻辑图:
大致过程
笔记:
1.添加依赖包, mysql druid jstl
2.整合jdbc吧 basedao 的内容拿过来
3.测试basedao是否能用.编写一个列表测试
4.准备好数据表
5.创建好数据表对应的类型
6.创建userDao
7.就可以在servlet中使用userdao查询数据
8.使用jstl,添加依赖包。
导入的包
baseDao:
package com.test.dao;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import com.alibaba.druid.pool.DruidDataSource;
public class BaseDao<T> {
// 使用配置文件来记录信息,驱动、url、用户名、密码
// 使用Properties配置文件来记录信息
// 在使用增删改查之前,先要获取到配置文件的属性赋值到属性中
static String driver = null;
static String url = null;
static String username = null;
static String password = null;
// 1、把公共的内容抽取出来,现在一共有
// 构造器 在创建对象的时候会执行
public BaseDao() {
System.out.println("我是构造器");
System.out.println("初始化数据库连接");
// 1、加入数据库连接驱动(jar包)(连接的是mysql数据库,就要加入mysql的驱动)
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 2、创建连接:mysql 默认端口3306
}
// 构造代码块 构造器执行之前执行
{
System.out.println("构造代码块");
}
// 静态代码块 在类型运行之前执行
static {
System.out.println("静态代码块");
Properties properties = new Properties();
InputStream inStream;
try {
// inStream = new FileInputStream("resource/jdbc.properties");//
// 填写上相对路径//FileInputStream读取的文件路径执行文件的路径
// 使用FileInputStream的话有可能出现 异常的,在main函数中执行是没有问题的,可是使用了tomcat部署的web项目之后就会出现问题
inStream = BaseDao.class.getClassLoader().getResourceAsStream("resource/jdbc.properties");// ClassLoader
// 编译好的class的路径//
// 可以获取到tomcat中的classpath路径
properties.load(inStream);
driver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 获取数据库连接
*
* @return
* @throws SQLException
*/
public Connection getConnection() throws SQLException {
// 数据库连接,每次执行sql都要打开连接,使用完成之后要关闭连接
// 把数据库连接修改为数据库连接池
// 1、添加数据库连接池的jar包
// 2、编写数据库连接池的代码
// 2.1、创建DruidDataSource对象
DruidDataSource dataSource = new DruidDataSource();
// 2.2、设置数据库连接池的最大连接数、最小连接数
// 最小值等待数
dataSource.setMinIdle(3);
// 最大连接数
dataSource.setMaxActive(4);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.getConnection();
// return DriverManager.getConnection(url, username, password);
return dataSource.getConnection();
}
/**
* 关闭连接
*
* @param connection
* @throws SQLException
*/
private void closeConnection(Connection connection) throws SQLException {
connection.close();
}
/**
* 合并方法
*
* // insert和delete、Update区别:1、sql不一样,2、传参的数量不一样(可变长参数)
*
* // 把3个方法合并一个方法,把不一样的东西,使用参数形式传进来
*
* @param sql
* @param objects
* @return
* @throws SQLException
*/
private boolean merger(String sql, Object... objects) throws SQLException {
Connection connection = getConnection();
// 3、获取状态
PreparedStatement preparedStatement = connection.prepareStatement(sql);
// 传参
for (int i = 0; i < objects.length; i++) {
preparedStatement.setObject(i + 1, objects[i]);
}
// 4、执行sql
int i = preparedStatement.executeUpdate();
closeConnection(connection);
if (i > 0) {
return true;// 增删改成功
} else {
return false;// 增删改失败
}
}
/**
* 新增
*
* @throws ClassNotFoundException
* @throws SQLException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public boolean insert(T user)// 我有没有其他的参数,新增修改只要一个参数就可以了,对应的数据表的对象
throws ClassNotFoundException, SQLException, IllegalArgumentException, IllegalAccessException {
// 先不用泛型,先直接使用类型,用反射编写好代码,最后再加泛型
Class class1 = getPojoClass();// 使用泛型替代
Field[] fields = class1.getDeclaredFields();// 拿到所有的属性,包括私有的
String fieldstr = "";
String paramstr = "";
List obj = new ArrayList();
for (int i = 0; i < fields.length; i++) {
Id id = fields[i].getAnnotation(Id.class);// 查看属性是有拥有id注解
if (id == null) {
fields[i].setAccessible(true);// 获取私有属性的时候先开启权限
obj.add(fields[i].get(user));
fieldstr += fields[i].getName();
paramstr += "?";
if (i != fields.length - 1) {
fieldstr += ",";
paramstr += ",";
}
}
}
// 只要是自增id,可写可不写,如果id不是自增,那么就必须写
String sql = "insert into " + class1.getSimpleName() + " (" + fieldstr + ") values (" + paramstr + ");";
return merger(sql, obj.toArray());
// return true;
}
/**
* 删除
*
* @return
*
* @throws ClassNotFoundException
* @throws SQLException
*/
public boolean delete(int id) throws ClassNotFoundException, SQLException {
// 通过方法 获取泛型的类型
Class class1 = getPojoClass();
Field[] fields = class1.getDeclaredFields();
String primary = "";
for (Field field : fields) {
Id id1 = field.getAnnotation(Id.class);
if (id1 != null) {
primary = field.getName();
}
}
String sql = "delete from " + class1.getSimpleName() + " where " + primary + " = ? ;";
System.out.println(sql);
return merger(sql, id);
}
/**
* 修改
*
* 修改全部字段
*
*
* name和id,不就是在user对象中吗
*
* @throws ClassNotFoundException
* @throws SQLException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public boolean updateById(T user)
throws ClassNotFoundException, SQLException, IllegalArgumentException, IllegalAccessException {
// 9 xiaozhi 24 huangcun
// 根据user对象就可以获取到所有的属性了id=9、name=xiaozhi、age=24、address=null
// 根据id修改其他字段的信息
// 所谓的修改 就是根据主键修改其他字段的内容
// ,
// 根据传进来的属性进行修改,如果属性为空就不修改那个属性了
Class class1 = getPojoClass();
Field[] fields = class1.getDeclaredFields();
String field = "";
String where = "";
Object idzhi = null;
List list = new ArrayList();
for (int i = 0; i < fields.length; i++) {
fields[i].setAccessible(true);// 先设置权限
Id id = fields[i].getAnnotation(Id.class);
if (id == null) {// 不是主键的属性
// name = ? , age = 24 , address = null
field += fields[i].getName() + " = ? ";
if (i != fields.length - 1) {
field += " , ";
}
// 获取对象的值,并且存放到对应的sql参数位置
list.add(fields[i].get(user));
}
// 判断id!=null //就是主键,现在不能直接塞集合,就使用一个变量缓存起来,在循环外面再塞进集合
// 如果直接塞集合,id有可能是塞到第一位去了
else {
where += fields[i].getName() + " = ? ";
idzhi = fields[i].get(user);
}
}
list.add(idzhi);// id的值就可以放到集合中最后一位了
// 第一种处理方法:
// 再写一个 for循环,就是用来获取id的
String sql = "update " + class1.getSimpleName() + " set " + field + " where " + where + " ;";
return merger(sql, list.toArray());
}
/**
* 选择性修改
*
* @param user
* @return
* @throws ClassNotFoundException
* @throws SQLException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public boolean updateSelectiveById(T user)
throws ClassNotFoundException, SQLException, IllegalArgumentException, IllegalAccessException {
Class class1 = getPojoClass();
Field[] fields = class1.getDeclaredFields();
String field = "";// 容器
String where = "";
Object idzhi = null;
// Update User set 字段名 = ? ,字段名=?,字段名=? where id =?
List list = new ArrayList();
for (int i = 0; i < fields.length; i++) {
fields[i].setAccessible(true);// 先设置权限
Id id = fields[i].getAnnotation(Id.class);
if (id == null) {// 不是主键的属性
// name = 'xiaoz' , age = 24 ,只拼接有值的字段,没值的就不拼接了
if (fields[i].get(user) != null) {
field += fields[i].getName() + " = ? ";
if (i != fields.length - 1) {
field += " , ";
}
// 获取对象的值,并且存放到对应的sql参数位置
list.add(fields[i].get(user));
}
}
// 判断id!=null //就是主键,现在不能直接塞集合,就使用一个变量缓存起来,在循环外面再塞进集合
// 如果直接塞集合,id有可能是塞到第一位去了
else {
where += fields[i].getName() + " = ? ";
idzhi = fields[i].get(user);
}
}
list.add(idzhi);// id的值就可以放到集合中最后一位了
// 第一种处理方法:
// 再写一个 for循环,就是用来获取id的
// 因为拼接sql 字段中最后有一个逗号,要把逗号去掉
int i = field.lastIndexOf(",");
if (field.length() - i <= 2) {// update User set age = ? , where id = ? ;
field = field.substring(0, i - 1);
}
String sql = "update " + class1.getSimpleName() + " set " + field + " where " + where + " ;";
System.out.println(sql);
return merger(sql, list.toArray());
}
private ResultSet query(Connection connection, String sql, Object... objects) throws SQLException {
// 3、获取状态
PreparedStatement preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < objects.length; i++) {
preparedStatement.setObject(i + 1, objects[i]);
}
// 4、执行sql
return preparedStatement.executeQuery();
}
/**
* 根据id查询
*
* 分为2中类型第一种:结果返回单行数据 根据id查询 第二种:结果返回多行数据的 条件查询
*
* @param id
* @throws ClassNotFoundException
* @throws SQLException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public T selectOne(String sql, Object... objects)
throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException {
Connection connection = getConnection();
// 3、获取状态
ResultSet resultSet = query(connection, sql, objects);
// ResultSet结果集,迭代结果集,获取结果集中的数据
// 封装一个对象就可以了
Class class1 = getPojoClass();
Object object = null;// 创建一个user对象
while (resultSet.next()) {// 查看一下是否还有下一个数据
// 迭代数据的时候还要进行数据的封装,封装到对象中
object = autoSetter(resultSet, class1);
}
closeConnection(connection);
return (T) object;
}
/**
* 根据id查询
*
* @param id
* @return
* @throws ClassNotFoundException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws SQLException
*/
public T selectById(int id)
throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
Class class1 = getPojoClass();
Field[] fields = class1.getDeclaredFields();
String primary = "";
for (Field field : fields) {
Id id1 = field.getAnnotation(Id.class);
if (id1 != null) {
primary = field.getName();
}
}
String sql = "select * from " + getPojoClass().getSimpleName() + " where " + primary + " = ? ";
return selectOne(sql, id);
}
/**
* 多行数据查询
*
* @param name
* @param address
* @return
* @throws ClassNotFoundException
* @throws SQLException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public List<T> selectSome(String sql, Object... objects)
throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException {
Connection connection = getConnection();
ResultSet resultSet = query(connection, sql, objects);
// ResultSet结果集,迭代结果集,获取结果集中的数据,把所有的结果集封装到 一个集合中
List<T> list = new ArrayList<T>();
// 也是使用user对象
Class class1 = getPojoClass();
while (resultSet.next()) {// 查看一下是否还有下一个数据
Object object = autoSetter(resultSet, class1);
list.add((T) object);
}
closeConnection(connection);
return list;
}
/**
* 自动封装对象
*
* @param resultSet
* @param class1
* @return
* @throws InstantiationException
* @throws IllegalAccessException
* @throws SQLException
*/
private Object autoSetter(ResultSet resultSet, Class class1)
throws InstantiationException, IllegalAccessException, SQLException {
// 加上父类的属性封装
Class superClass = class1.getSuperclass();// 获取到父类类型
Field[] superfields = superClass.getDeclaredFields();
Object object = class1.newInstance();
Field[] fields = class1.getDeclaredFields();
// 使用集合合并2个数组
List<Field> list = new ArrayList<Field>();
list.addAll(Arrays.asList(superfields));
list.addAll(Arrays.asList(fields));
for (Field field : list) {
field.setAccessible(true);
field.set(object, resultSet.getObject(field.getName()));
}
return object;
}
/**
* 查询所有数据
*
* @return
* @throws ClassNotFoundException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws SQLException
*/
public List<T> selectAll()
throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
String sql = "select * from " + getPojoClass().getSimpleName();
return selectSome(sql);
}
/**
* 获取泛型的类型
*
* @return
*/
private Class getPojoClass() {
// 获取当前类的Class
Class c = this.getClass();
// 获取泛型<T,e>
Type t = c.getGenericSuperclass();
// 判断t是否属于ParameterizedType//是否属于泛型
if (t instanceof ParameterizedType) {
// 所有的泛型的参数,[table1]
Type[] p = ((ParameterizedType) t).getActualTypeArguments();
return (Class) p[0];
}
return null;
}
// 多表关联查询---怎么封装数据
// 可以在类型中定义泛型
// 也可以在方法中定义泛型
public <R> List<R> selectSome(Class<R> clazz, String sql, Object... obj)
throws SQLException, InstantiationException, IllegalAccessException {// R是什么类型,就由参数的R进行决定
Connection connection = getConnection();
ResultSet resultSet = query(connection, sql, obj);
List<R> list = new ArrayList<R>();
while (resultSet.next()) {
R object = (R) autoSetter(resultSet, clazz);
list.add(object);
}
return list;
}
// 多表关联查询---怎么封装数据
// 可以在类型中定义泛型
// 也可以在方法中定义泛型
public <R> R selectOne(Class<R> clazz, String sql, Object... obj)
throws SQLException, InstantiationException, IllegalAccessException {// R是什么类型,就由参数的R进行决定
Connection connection = getConnection();
ResultSet resultSet = query(connection, sql, obj);
R object = null;
while (resultSet.next()) {
object = (R) autoSetter(resultSet, clazz);
}
return object;
}
// generate生成,自动生成代码,生成Pojo
// 实现的功能把pojo类型的内容在console里面输出出来
// 最后就可以在console里面复制代码到项目里面了
// 简单一点理解:字符串拼接
public void generatePojoTitle(String tableName) throws Exception {
// 把头字母大写
tableName = tableName.toLowerCase();
tableName = tableName.substring(0, 1).toUpperCase() + tableName.substring(1, tableName.length());
String classStr = "public class " + tableName + "{ \n";
// 怎么才能知道数据表中有什么字段,类型是什么
// show full fields from table1,可以通过sql获取数据表的字段类型
Connection connection = getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("show full fields from " + tableName);
ResultSet resultSet = preparedStatement.executeQuery();
// 字段的内容
while (resultSet.next()) {
// System.out.println(resultSet.getString("field"));
// System.out.println(resultSet.getString("type"));
System.out.println();// 获取主键PRI,可以使用注解方式来规定主键
if (resultSet.getString("key").equals("PRI")) {
classStr += "@Id\n";
}
// 在类型中第一个属性就是主键
// 就是把之前的规定改为注解方式来决定主键
String type = resultSet.getString("type");
classStr += "private ";
if (type.indexOf("int") > -1) {
classStr += " int ";
} else if (type.indexOf("varchar") > -1) {
classStr += " String ";
} else if (type.indexOf("Date") > -1) {
classStr += " Date ";
}
classStr += resultSet.getString("field") + ";\n";
}
classStr += "}";
System.out.println(classStr);
}
public static void main(String[] args) throws Exception {
BaseDao baseDao = new BaseDao();
baseDao.generatePojoTitle("user");
}
}
id.java:主键id
package com.test.dao;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD })
public @interface Id {
}
数据库表设计:
user类对象:
package com.test.pojo;
import java.util.Date;
import com.test.dao.Id;
public class User {
@Id
private int id;
private String name;
private int age;
private String sex;
private Date birth;
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 getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
}
UserDao:
package com.test.userdao;
import com.test.dao.BaseDao;
import com.test.pojo.User;
public class UserDao extends BaseDao<User> {
}
jdbc.properties:数据库配置文件
driver = com.mysql.jdbc.Driver
url = jdbc:mysql://127.0.0.1:3306/j200106?useunicode=true&characterEncoding=utf8&useSSL=true
username = root
password = 123456
第一步:查
list.jsp:显示结果jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><!-- 直接cv -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<table border="1" style="border-collapse: collapse;">
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>生日</th>
</tr>
<c:forEach items="${requestScope.list}" var="item">
<tr>
<td>${item.name }</td>
<td>${item.age }</td>
<td>${item.sex }</td>
<td>${item.birth }</td>
</tr>
</c:forEach>
</table>
</body>
</html>
SelectServlet :
package com.j200106.servlet;
import java.io.IOException;
import java.sql.SQLException;
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 com.j200106.dao.UserDao;
import com.j200106.pojo.User;
@WebServlet("/SelectServlet")
public class SelectServlet extends HttpServlet {
UserDao userDao = new UserDao();
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
// 查询数据之后回显页面
List<User> list = userDao.selectAll();
// 使用请求作用域把list带到前端页面
request.setAttribute("list", list);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 跳转页面,重定向会丢失作用域,为什么?因为重定向是2次请求
// 使用的是转发
request.getRequestDispatcher("list.jsp").forward(request, response);
}
}
查:改:
list.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="/day46/SelectServlet">
姓名:<input type="text" name="name" value="${name}">
年龄:<input type="text" name="age" value="${age}"> <input type="submit"
value="查询">
</form>
<br>
<table border="1" style="border-collapse: collapse;">
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>生日</th>
<th>操作</th>
</tr>
<c:forEach items="${requestScope.list }" var="item">
<tr>
<td>${item.name }</td>
<td>${item.age }</td>
<td>${item.sex }</td>
<td>${item.birth }</td>
</tr>
</c:forEach>
</table>
</body>
</html>
selectservlet:
package com.test.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.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.test.pojo.User;
import com.test.userdao.UserDao;
@WebServlet("/SelectServlet")
public class SelectServlet extends HttpServlet {
UserDao userDao = new UserDao();
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
// request.setCharacterEncoding("UTF-8");
// response.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");// getParameter获取表单参数,setAttribute获取作用域值
String age = request.getParameter("age");
String msg = request.getParameter("msg");
request.setAttribute("msg", msg);
// 回显数据
request.setAttribute("name", name);
request.setAttribute("age", age);
String sql = "select * from user where 1=1";
List list2 = new ArrayList();
if (!"".equals(name) && name != null) {
sql += " and name like CONCAT('%',?,'%') ";//记得在sql前面加空格,要不会出现sql拼接格式错误
list2.add(name);
}
if (!"".equals(age) && age != null) {
sql += " and age like CONCAT('%',?,'%') ";
list2.add(age);
}
// List list2 = new ArrayList();
// if (!"".equals(name) && name != null) {
// sql += " and name like CONCAT('%',?,'%') ";
// list2.add(name);
// }
// if (!"".equals(age) && age != null) {
// sql += " and age like CONCAT('%',?,'%') ";
// list2.add(age);
// }
// String sql = "select * from user where name like concat('%',?,'%') and age like concat('%',?,'%')";
// 查询数据之后回显页面
// List<User> list = userDao.selectAll();
List<User> list = userDao.selectSome(sql, list2.toArray());
// 使用请求作用域吧list带到前端页面
request.setAttribute("list", list);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 跳转页面,重定向会丢失作用域,为什么?因为重定向是2次请求
// 使用转发
request.getRequestDispatcher("list.jsp").forward(request, response);
}
}
第二步:增
list.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><!-- 直接cv -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- 新增功能,跳转到新增页面 ,并不是说所有的跳转都要使用form表单,也可以使用a标签
1、直接请求到页面、2、使用servlet转发(在页面上请求servlet,然后servlet转发到指定页面)
-->
<a href="/J200106_day46/ToInsertServlet">新增</a>
<!-- 查询条件 -->
<form action="/J200106_day46/SelectServlet">
姓名:<input type="text" name="name" value="${name }">
年龄:<input type="text" name="age" value="${age }">
<input type="submit" value="查询">
</form>
<table border="1">
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>生日</th>
</tr>
<c:forEach items="${requestScope.list}" var="item">
<tr>
<td>${item.name }</td>
<td>${item.age }</td>
<td>${item.sex }</td>
<td>${item.birth }</td>
</tr>
</c:forEach>
</table>
${msg }
</body>
</html>
insert.jsp:用于输入新增内容的页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
新增页面
<form action="/J200106_day46/InsertServlet">
姓名:<input type="text" name="name"> <br>
年龄:<input type="text" name="age"><br>
性别:<input type="radio" name="sex" value="1">男<input type="radio" name="sex" value="2">女<br>
生日:<input type="date" name="birth"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
ToInsertServlet.java:跳转到新增jsp的servlet
package com.j200106.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;
/**
* 去到新增页面
*
* 功能就是跳转页面而已
*
* @author Jason
*
*/
@WebServlet("/ToInsertServlet")
public class ToInsertServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getRequestDispatcher("insert.jsp").forward(req, resp);
}
}
InsertServlet:用于实现新增操作的servlet
package com.j200106.servlet;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
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 com.j200106.dao.UserDao;
import com.j200106.pojo.User;
@WebServlet("/InsertServlet")
public class InsertServlet extends HttpServlet {
private UserDao userDao = new UserDao();
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
// 获取表单信息
String name = request.getParameter("name");
String age = request.getParameter("age");
String sex = request.getParameter("sex");
String birth = request.getParameter("birth");
// 新增到数据库,dao层
User user = new User();
user.setName(name);
user.setAge(Integer.parseInt(age));
user.setSex(Integer.parseInt(sex));
// sting 装date 使用simpdateformat
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
user.setBirth(dateFormat.parse(birth));
// 判断是否新增成功
String msg = null;
if (userDao.insert(user)) {//在这里犯了个错误,因为之前建表的时候忘了勾选自动递增导致出现了缺少id的新增错误。
msg = "新增成功";
} else {
msg = "新增失败";
}
// 提示信息就要先通过SelectServlet,在去到页面
// 跳转回列表页面,在新增的servlet中跳转到查询 的servlet,最后就可以直接查询最新的信息出来了
// request.getRequestDispatcher("/SelectServlet").forward(request, response);
response.sendRedirect("/J200106_day46/SelectServlet?msg=" + msg);
// 转发和重定向的区别
// 1、转发:一次请求、url不会改变的(列表查询的时候使用)
// 2、重定向:2次请求、url是会改变的(增删改)
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
第三步:删
list.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- 新增功能,跳转到新增页面,并不是说所有的跳转都要使用form表单,也可以用a标签
1.直接请求到页面
2.使用servlet转发(在页面上请求servlet,然后servlet转发到指定页面)
-->
<a href="/day46/ToInsertServlet">新增</a>
<br>${msg }
<form action="/day46/SelectServlet">
姓名:<input type="text" name="name" value="${name}"> 年龄:<input
type="text" name="age" value="${age}"> <input type="submit"
value="查询">
</form>
<br>
<table border="1" style="border-collapse: collapse;">
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>生日</th>
<th>操作</th>
</tr>
<c:forEach items="${requestScope.list }" var="item">
<tr>
<td>${item.name }</td>
<td>${item.age }</td>
<td>${item.sex }</td>
<td>${item.birth }</td>
<td><a
href="/day46/DeleteServlet?id=${item.id }">删除</a></td>
<!-- 修改和删除一定要记得带上id操作 -->
</tr>
</c:forEach>
</table>
</body>
</html>
DeleteServlet:
package com.test.servlet;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.SQLException;
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 com.test.userdao.UserDao;
import sun.applet.resources.MsgAppletViewer;
@WebServlet("/DeleteServlet")
public class DeleteServlet extends HttpServlet {
UserDao userDao = new UserDao();
@Override
protected void service(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
try {
String id = req.getParameter("id");
String msg = null;
if (userDao.delete(Integer.parseInt(id))) {
msg = "删除成功";
} else {
msg = "删除失败";
}
response.sendRedirect("/day46/SelectServlet?msg=" + URLEncoder.encode(msg, "UTF-8"));
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
第四步:改
list.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- 新增功能,跳转到新增页面,并不是说所有的跳转都要使用form表单,也可以用a标签
1.直接请求到页面
2.使用servlet转发(在页面上请求servlet,然后servlet转发到指定页面)
-->
<a href="/day46/ToInsertServlet">新增</a>
<br>${msg }
<form action="/day46/SelectServlet">
姓名:<input type="text" name="name" value="${name}"> 年龄:<input
type="text" name="age" value="${age}"> <input type="submit"
value="查询">
</form>
<br>
<table border="1" style="border-collapse: collapse;">
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>生日</th>
<th>操作</th>
</tr>
<c:forEach items="${requestScope.list }" var="item">
<tr>
<td>${item.name }</td>
<td>${item.age }</td>
<td>${item.sex }</td>
<td>${item.birth }</td>
<td><a href="/day46/ToUpdateServlet?id=${item.id }">修改</a><a
href="/day46/DeleteServlet?id=${item.id }">删除</a></td>
<!-- 修改和删除一定要记得带上id操作 -->
</tr>
</c:forEach>
</table>
</body>
</html>
toUpdateServlet:跳转到jsp页面并且回显数据:
package com.test.servlet;
import java.io.IOException;
import java.sql.SQLException;
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 com.sun.accessibility.internal.resources.accessibility;
import com.test.pojo.User;
import com.test.userdao.UserDao;
@WebServlet("/ToUpdateServlet")
public class ToUpdateServlet extends HttpServlet {
UserDao userDao = new UserDao();
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
// 跳转到修改页面的
// 回显数据,根据页面请求的id查询回显数据
String id = request.getParameter("id");
// 通过userdao查询数据库的信息
User user = userDao.selectById(Integer.parseInt(id));
// 查询到的结果用请求作用域返回到页面显示
request.setAttribute("user", user);
// 这里要使用到转发,而不是重定向,因为要回显数据到新页面上
request.getRequestDispatcher("update.jsp").forward(request, response);
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
update.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
新增页面
<form action="/day46/UpdateServlet">
<input type="hidden" name="id" value="${user.id }"><!-- 必须写上一个隐藏的id -->
姓名:<input type="text" name="name" value="${user.name }"><br>
年龄:<input type="text" name="age" value="${user.age }"><br>
性别:<input type="radio" name="sex" value="男"
${("男"==user.sex)?'checked':'' } checked="">男 <input type="radio"
name="sex" value="女" ${("女"==user.sex)?'checked':'' }>女<br> 生日:<input type="date"
name="birth" value="${user.birth }"><br> <input
type="submit" value="提交"><br>
</form>
</body>
</html>
updateServlet:修改操作的servlet
package com.test.servlet;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
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 com.test.pojo.User;
import com.test.userdao.UserDao;
@WebServlet("/UpdateServlet")
public class UpdateServlet extends HttpServlet {
UserDao userdao = new UserDao();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
// 修改数据信息
// 根据表单来获取修改的数据内容
String id = req.getParameter("id");
String name = req.getParameter("name");
String age = req.getParameter("age");
String sex = req.getParameter("sex");
String birth = req.getParameter("birth");
User user = new User();
user.setAge(Integer.parseInt(age));
SimpleDateFormat dateFormat = new SimpleDateFormat("yy-MM-dd");
user.setBirth(dateFormat.parse(birth));
user.setId(Integer.parseInt(id));
user.setName(name);
user.setSex(sex);
String msg = null;
if (userdao.updateById(user)) {
msg = "修改成功";
} else {
msg = "修改失败";
}
// 跳转列表,重定向
resp.sendRedirect("/day46/SelectServlet?msg=" + URLEncoder.encode(msg, "UTF-8"));
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}