Javaweb Maven构建最简单的增删改查
一、项目结构
二、运行截图
三、maven所需依赖
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
四、数据表sql文件(Navicat导入就行)
/*
Navicat Premium Data Transfer
Source Server : tttt
Source Server Type : MySQL
Source Server Version : 50528
Source Host : localhost:3306
Source Schema : mydb
Target Server Type : MySQL
Target Server Version : 50528
File Encoding : 65001
Date: 20/07/2020 15:37:03
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for stu
-- ----------------------------
DROP TABLE IF EXISTS `stu`;
CREATE TABLE `stu` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`sex` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`age` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`phone_numb` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
-- ----------------------------
-- Table structure for users
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`uname` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名',
`upwd` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '密码',
PRIMARY KEY (`uname`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;
SET FOREIGN_KEY_CHECKS = 1;
五、项目构建
1、Dao 目录下
构建数据连接(BaseDao.java)
写UserDao.java、StuDao.java
public class BaseDao {
//数据库参数
private static final String driver = "com.mysql.jdbc.Driver";
private static final String url = "jdbc:mysql://localhost:3306/mydb";
//用户名、密码要是自己的
private static final String user = "root";
private static final String password = "root";
//加载驱动
static {
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//1.获取连接
public Connection getConn() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
//2.释放资源
public void close(Connection conn, Statement st, ResultSet rs){
try {
if(conn != null)
conn.close();
if (st != null)
st.close();
if (rs != null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//关闭连接
public void close(Connection conn, Statement st){
try {
if(conn != null)
conn.close();
if (st != null)
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public class StuDao {
BaseDao baseDao = new BaseDao();
public List<Stu> queryStus(String sex) {
if (sex == null){
sex = "";
}
Connection conn = null;
//1.预编译
PreparedStatement pst = null;
//2.结果集
ResultSet rs = null;
List<Stu> stuList = new ArrayList<>();
try {
conn = baseDao.getConn();
//3.sql
String sql = "select * from Stu where sex like ?";
//4.预编译sql
pst = conn.prepareStatement(sql);
pst.setString(1, "%"+sex+"%");
rs = pst.executeQuery();
//6.遍历结果集
while (rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");//用户名
String sex1 = rs.getString("sex");//密码
String age = rs.getString("age");//密码
String phone_numb = rs.getString("phone_numb");//密码
stuList.add(new Stu(id,name, sex1, age,phone_numb));
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
//最后记得关闭资源
baseDao.close(conn, pst, rs);
}
return stuList;
}
// public static void main(String[] args) {
// StuDao stuDao = new StuDao();
// System.out.println("stuDao.queryStus() = " + stuDao.queryStus());
// }
public Boolean deleteStu(int id) {
//1.获取连接
Connection conn = null;
//2.预编译
PreparedStatement pst = null;
//3.sql
String sql = "delete from stu where id = ?";
try {
conn = baseDao.getConn();
//预编译sql
pst = conn.prepareStatement(sql);
//注入参数
pst.setInt(1,id);
//执行sql
return pst.executeUpdate() > 0;
} catch (SQLException e) {
e.printStackTrace();
} finally {
baseDao.close(conn, pst);
}
return false;
}
}
package com.zking.dao;
import com.zking.entity.User;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* @author Tanglei
* @date 2020/7/19 - 16:17
*/
public class UserDao {
BaseDao baseDao = new BaseDao();
public User checkUser(User user) {
User user1 = null;
Connection conn = null;
//1.预编译
PreparedStatement pst = null;
//2.结果集
ResultSet rs = null;
try {
conn = baseDao.getConn();
//3.sql
String sql = "select * from users where uname = ? and upwd = ?";
//4.预编译sql
pst = conn.prepareStatement(sql);
//5.注入参数
Object[] params = {user.getUname(), user.getUpwd()};
for (int i = 0; i < params.length; i++) {
pst.setObject(i+1, params[i]);
}
rs = pst.executeQuery();
//6.遍历结果集
while (rs.next()){
String uname = rs.getString("uname");//用户名
String upwd = rs.getString("upwd");//密码
user1 = new User(uname, upwd);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
//最后记得关闭资源
baseDao.close(conn, pst, rs);
}
return user1;
}
public List<User> queryUsers() {
Connection conn = null;
//1.预编译
PreparedStatement pst = null;
//2.结果集
ResultSet rs = null;
List<User> userList = new ArrayList<>();
try {
conn = baseDao.getConn();
//3.sql
String sql = "select * from users";
//4.预编译sql
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
//6.遍历结果集
while (rs.next()){
String uname = rs.getString("uname");//用户名
String upwd = rs.getString("upwd");//密码
userList.add(new User(uname, upwd));
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
//最后记得关闭资源
baseDao.close(conn, pst, rs);
}
return userList;
}
}
2、实体类
User.java,Stu.java ( !getter set 和构造方法自己快捷键生成 ! )
public class Stu {
private int id;//id
private String name;//姓名
private String sex;//性别
private String age;//年龄
private String phone_numb;//手机号
}
public class User {
private String uname;//用户名
private String upwd;//用户密码
}
3、jsp页面
login.jsp、showStu.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<form action="login?method=login" method="post">
<table cellpadding="0" border="1" align="center">
<tbody>
<tr>
<td colspan="2" align="center">登 陆</td>
</tr>
<tr>
<td>
<label>用户名:</label>
</td>
<td>
<input type="text" name="username">
</td>
</tr>
<tr>
<td>
<label>密 码:</label>
</td>
<td>
<input type="text" name="password">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<button type="submit">登 陆</button>
<button id="reSet">重置</button>
</td>
</tr>
</tbody>
</table>
</form>
</body>
<script>
document.getElementById("#reSet").click(function () {
document.getElementByName("username").val = "";
document.getElementByName("password").val = "";
});
</script>
</html>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>显示所有学生数据</title>
</head>
<script>
function buttonClick() {
var sex = document.getElementById("sex").value;
window.location.href = "stu?method=queryStusBySex&sex="+sex;
}
</script>
<body>
<thead>
<label>性别:</label>
<input type="text" value="" id="sex" name="sex">
<input id="button" type="button" value="查询" οnclick="buttonClick();">
<table align="center" border="1" cellpadding="10">
<tr>
<td colspan="6" align="center">学 生 列 表</td>
</tr>
<tr>
<td>编号</td>
<td>姓名</td>
<td>性别</td>
<td>年龄</td>
<td>电话</td>
<td>操作</td>
</tr>
</thead>
<tbody>
<c:forEach items="${stuList}" var="stu">
<tr>
<td>${stu.id}</td>
<td>${stu.name}</td>
<td>${stu.sex}</td>
<td>${stu.age}</td>
<td>${stu.phone_numb}</td>
<td>
<a href="stu?method=deleteStu&id=${stu.id}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</body>
</html>
4、最后的Servlet
LoginServlet、StuServlet
@WebServlet(urlPatterns = {"/login"})
public class LoginServlet extends HttpServlet {
UserDao userDao = new UserDao();
StuDao stuDao = new StuDao();
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String method = request.getParameter("method");
System.out.println("method = " + method);
if("login".equals(method)){
login(request,response);
}
}
//登陆方法
private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userName = request.getParameter("username");//获取表单提交的用户名
String passWord = request.getParameter("password");//密码
User loginUser = new User(userName, passWord);
User checkUser = userDao.checkUser(loginUser);//验证
if (checkUser != null){//验证通过
List<Stu> stuList = stuDao.queryStus("");
System.out.println("stuList = " + stuList);
request.setAttribute("stuList", stuList);
request.getRequestDispatcher("/WEB-INF/views/showStus.jsp").forward(request, response);
}else {
response.sendRedirect("login.jsp");
}
}
}
@WebServlet(urlPatterns = {"/stu"})
public class StuServlet extends HttpServlet {
StuDao stuDao = new StuDao();
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String method = request.getParameter("method");
System.out.println("method = " + method);
if ("showStus".equals(method)){
showStus(request,response);
}else if("deleteStu".equals(method)){
deleteStu(request,response);
}else if("queryStusBySex".equals(method)){
queryStusBySex(request,response);
}
}
//通过性别查询所有学生信息
private void queryStusBySex(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String sex = request.getParameter("sex");
List<Stu> stuList = stuDao.queryStus(sex);
request.setAttribute("stuList", stuList);
request.getRequestDispatcher("/WEB-INF/views/showStus.jsp").forward(request, response);
}
//删除
private void deleteStu(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
Boolean flag = stuDao.deleteStu(id);
if (flag){
response.sendRedirect("stu?method=showStus");
}
}
//查询所有学生
private void showStus(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Stu> stuList = stuDao.queryStus("");
request.setAttribute("stuList", stuList);
request.getRequestDispatcher("/WEB-INF/views/showStus.jsp").forward(request, response);
}
}
if (flag){
response.sendRedirect("stu?method=showStus");
}
}
//查询所有学生
private void showStus(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Stu> stuList = stuDao.queryStus("");
request.setAttribute("stuList", stuList);
request.getRequestDispatcher("/WEB-INF/views/showStus.jsp").forward(request, response);
}
}