提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
目录
前言
一个简单的JavaWeb增删改查。
提示:以下是本篇文章正文内容,下面案例可供参考
一、pandas是什么?
Java Web,是用Java技术来解决相关web互联网领域的技术栈。web包括:web服务端和web客户端两部分。Java在客户端的应用有Java Applet,不过使用得很少,Java在服务器端的应用非常的丰富,比如Servlet,JSP、第三方框架等等。Java技术对Web领域的发展注入了强大的动力。
二、使用步骤
1.引入js
将可能用到的js和jar包咔咔一顿复制到路径下:
2.读入数据
代码如下(示例):
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
三、完整项目实现案列
1.先上效果
2.建一个项目
项目结构为下图,我这里用的三层架构思想来搭建项目。
3.后端代码及解析
1.utils层
DBUtil:用于连接数据库
package com.hqyj.gyq.utils;
import java.sql.*;
public class DBUtil {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
Connection con = null;
try {
con = DriverManager.getConnection("jdbc:mysql:///j220301?useUnicode=true&characterEncoding=UTF-8", "root", "root");
return con;
} catch (SQLException throwables) {
throwables.printStackTrace();
return null;
}
}
public static void closeAll(ResultSet rs, PreparedStatement pre,Connection con){
if(rs!=null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(pre!=null){
try {
pre.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(con!=null){
try {
con.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
2.entity层
User:实例化对象类
package com.hqyj.gyq.entity;
public class User {
private Integer id;
private String userName;
private String userAge;
private String userSex;
private String userTel;
public User() {
}
public User(Integer id, String userName, String userAge, String userSex, String userTel) {
this.id = id;
this.userName = userName;
this.userAge = userAge;
this.userSex = userSex;
this.userTel = userTel;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserAge() {
return userAge;
}
public void setUserAge(String userAge) {
this.userAge = userAge;
}
public String getUserSex() {
return userSex;
}
public void setUserSex(String userSex) {
this.userSex = userSex;
}
public String getUserTel() {
return userTel;
}
public void setUserTel(String userTel) {
this.userTel = userTel;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
", userAge='" + userAge + '\'' +
", userSex='" + userSex + '\'' +
", userTel='" + userTel + '\'' +
'}';
}
}
3.dao层
UserDao:定义接口
package com.hqyj.gyq.dao;
import com.hqyj.gyq.entity.User;
import java.util.List;
public interface UserDao {
List<User> queryUserAll();
int deleteUserById(int id);
User queryUserById(int id);
int updateUserById(User user);
int addUser(User user);
List<User> queryUser(User user);
List<User> queryUserPage(int pageNum,int pageSize);
int countUserAll();
}
UserDaoImpl:实现接口
package com.hqyj.gyq.dao.impl;
import com.hqyj.gyq.dao.UserDao;
import com.hqyj.gyq.entity.User;
import com.hqyj.gyq.utils.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class UserDaoImpl implements UserDao {
private Connection con = null;
private PreparedStatement pre = null;
private ResultSet rs = null;
@Override
public List<User> queryUserAll() {
try {
con = DBUtil.getConnection();
String sql = "select * from user";
pre = con.prepareStatement(sql);
rs = pre.executeQuery();
List<User> users = new ArrayList<>();
while (rs.next()){
User u = new User();
u.setId(rs.getInt("id"));
u.setUserName(rs.getString("user_name"));
u.setUserSex(rs.getString("user_sex"));
u.setUserAge(rs.getString("user_age"));
u.setUserTel(rs.getString("user_tel"));
users.add(u);
}
return users;
} catch (SQLException throwables) {
throwables.printStackTrace();
return null;
}finally {
DBUtil.closeAll(rs,pre,con);
}
}
@Override
public int deleteUserById(int id) {
try{
con = DBUtil.getConnection();
String sql = "delete from user where id = ?";
pre = con.prepareStatement(sql);
pre.setInt(1,id);
int num = pre.executeUpdate();
return num;
}catch (Exception e){
return 0;
}finally {
DBUtil.closeAll(rs,pre,con);
}
}
@Override
public User queryUserById(int id) {
try {
con = DBUtil.getConnection();
String sql = "select * from user where id = ?";
pre = con.prepareStatement(sql);
pre.setInt(1,id);
rs = pre.executeQuery();
if (rs.next()){
User u = new User();
u.setId(rs.getInt("id"));
u.setUserName(rs.getString("user_name"));
u.setUserSex(rs.getString("user_sex"));
u.setUserAge(rs.getString("user_age"));
u.setUserTel(rs.getString("user_tel"));
return u;
}
} catch (SQLException throwables) {
throwables.printStackTrace();
return null;
}finally {
DBUtil.closeAll(rs,pre,con);
}
return null;
}
@Override
public int updateUserById(User user) {
try{
con = DBUtil.getConnection();
String sql = "UPDATE user set user_name = ?,user_age = ?,user_sex = ?,user_tel = ? where id = ?";
pre = con.prepareStatement(sql);
pre.setString(1,user.getUserName());
pre.setString(2,user.getUserAge());
pre.setString(3,user.getUserSex());
pre.setString(4,user.getUserTel());
pre.setInt(5,user.getId());
int num = pre.executeUpdate();
return num;
}catch (Exception e){
return 0;
}finally {
DBUtil.closeAll(rs,pre,con);
}
}
@Override
public int addUser(User user) {
try{
con = DBUtil.getConnection();
String sql = "insert into user values (null,?,?,?,?)";
pre = con.prepareStatement(sql);
pre.setString(1,user.getUserName());
pre.setString(2,user.getUserAge());
pre.setString(3,user.getUserSex());
pre.setString(4,user.getUserTel());
int num = pre.executeUpdate();
return num;
}catch (Exception e){
return 0;
}finally {
DBUtil.closeAll(rs,pre,con);
}
}
@Override
public List<User> queryUser(User user) {
try {
con = DBUtil.getConnection();
String sql = "select * from user where 1=1 ";
List<Object> params = new ArrayList<>();
if(!(user.getUserName().equals("")||user.getUserName()==null)){
sql+="and user_name = ?";
params.add(user.getUserName());
}
if(!(user.getUserTel().equals("")||user.getUserTel()==null)){
sql+="and user_tel = ?";
params.add(user.getUserTel());
}
pre = con.prepareStatement(sql);
for (int i = 0; i <params.size() ; i++) {
pre.setObject(i+1,params.get(i));
}
rs = pre.executeQuery();
List<User> users = new ArrayList<>();
while (rs.next()){
User u = new User();
u.setId(rs.getInt("id"));
u.setUserName(rs.getString("user_name"));
u.setUserSex(rs.getString("user_sex"));
u.setUserAge(rs.getString("user_age"));
u.setUserTel(rs.getString("user_tel"));
users.add(u);
}
return users;
} catch (SQLException throwables) {
throwables.printStackTrace();
return null;
}finally {
DBUtil.closeAll(rs,pre,con);
}
}
@Override
public List<User> queryUserPage(int pageNum, int pageSize) {
try {
con = DBUtil.getConnection();
String sql = "select * from user limit ?,?";
pre = con.prepareStatement(sql);
pre.setInt(1,(pageNum-1)*pageSize);
pre.setInt(2,pageSize);
rs = pre.executeQuery();
List<User> users = new ArrayList<>();
while (rs.next()){
User u = new User();
u.setId(rs.getInt("id"));
u.setUserName(rs.getString("user_name"));
u.setUserSex(rs.getString("user_sex"));
u.setUserAge(rs.getString("user_age"));
u.setUserTel(rs.getString("user_tel"));
users.add(u);
}
return users;
} catch (SQLException throwables) {
throwables.printStackTrace();
return null;
}finally {
DBUtil.closeAll(rs,pre,con);
}
}
/**
* 统计总条数
* @return
*/
@Override
public int countUserAll() {
try {
con = DBUtil.getConnection();
String sql = "select count(*) as countAll from user";
pre = con.prepareStatement(sql);
rs = pre.executeQuery();
if(rs.next()){
int count = rs.getInt("countAll");
return count;
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return 0;
}
}
4.service层
UserService:定义接口
package com.hqyj.gyq.service;
import com.hqyj.gyq.entity.User;
import com.hqyj.gyq.utils.PageUtil;
import java.util.List;
public interface UserService {
List<User> findUsers();
String removeUserByID(int id);
User findUserById(int id);
String updateUser(User user);
String addUser(User user);
List<User> selectUsers(User user);
PageUtil<User> queryUserPage(int pageNum,int pageSize);
}
UserServiceImpl:实现接口
package com.hqyj.gyq.service.impl;
import com.hqyj.gyq.dao.UserDao;
import com.hqyj.gyq.dao.impl.UserDaoImpl;
import com.hqyj.gyq.entity.User;
import com.hqyj.gyq.service.UserService;
import com.hqyj.gyq.utils.PageUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
public class UserServiceImpl implements UserService {
private UserDao ud = new UserDaoImpl();
@Override
public List<User> findUsers() {
return ud.queryUserAll();
}
@Override
public String removeUserByID(int id) {
int num = ud.deleteUserById(id);
if(num>0){
return "success";
}else {
return "fail";
}
}
@Override
public User findUserById(int id) {
return ud.queryUserById(id);
}
@Override
public String updateUser(User user) {
int num = ud.updateUserById(user);
if(num>0){
return "success";
}else {
return "fail";
}
}
@Override
public String addUser(User user) {
int num = ud.addUser(user);
if(num>0){
return "success";
}else {
return "fail";
}
}
@Override
public List<User> selectUsers(User user) {
List<User> users = ud.queryUser(user);
if(users==null){
List<User> ls = new ArrayList<>();
return ls;
}else {
return users;
}
}
@Override
public PageUtil<User> queryUserPage(int pageNum, int pageSize) {
PageUtil<User> pageUtil = new PageUtil<>();
pageUtil.setPageNum(pageNum);
pageUtil.setPageSize(pageSize);
pageUtil.setTotalCount(ud.countUserAll());
pageUtil.setPageInfo(ud.queryUserPage(pageNum,pageSize));
return pageUtil;
}
}
5.controller层
UserController:离前端最近
package com.hqyj.gyq.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hqyj.gyq.entity.User;
import com.hqyj.gyq.service.UserService;
import com.hqyj.gyq.service.impl.UserServiceImpl;
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 java.io.IOException;
import java.util.List;
@WebServlet("/user")
public class UserController extends HttpServlet {
private UserService us = new UserServiceImpl();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
String method = req.getParameter("method");
if(method.equals("queryUserAll")){
queryUserAll(req,resp);
}else if(method.equals("deleteUserById")){
deleteUserById(req,resp);
}else if(method.equals("queryUserByID")){
queryUserById(req,resp);
}else if(method.equals("updataUserById")){
updataUserById(req,resp);
}else if(method.equals("addUser")){
addUser(req,resp);
}else if(method.equals("searchUser")){
searchUser(req,resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
public void queryUserAll(HttpServletRequest req, HttpServletResponse resp) throws IOException {
List<User> users = us.findUsers();
resp.setContentType("text/html;charset=UTF-8");
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(users);
resp.getWriter().write(json);
}
public void deleteUserById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String id = req.getParameter("id");
int id1 = Integer.parseInt(id);
String s = us.removeUserByID(id1);
resp.setContentType("text/html;charset=UTF-8");
// ObjectMapper mapper = new ObjectMapper();
// String json = mapper.writeValueAsString(s);
resp.getWriter().write(s);
}
public void queryUserById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String id = req.getParameter("id");
int id1 = Integer.parseInt(id);
User user = us.findUserById(id1);
resp.setContentType("text/html;charset=UTF-8");
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(user);
resp.getWriter().write(json);
}
public void updataUserById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String id = req.getParameter("id");
int id1 = Integer.parseInt(id);
String userName = req.getParameter("userName");
String userAge = req.getParameter("userAge");
String userSex = req.getParameter("userSex");
String userTel = req.getParameter("userTel");
User u = new User(id1,userName,userAge,userSex,userTel);
System.out.println(u);
String s = us.updateUser(u);
resp.setContentType("text/html;charset=UTF-8");
resp.getWriter().write(s);
}
public void addUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String userName = req.getParameter("userName");
String userAge = req.getParameter("userAge");
String userSex = req.getParameter("userSex");
String userTel = req.getParameter("userTel");
User u = new User(null,userName,userAge,userSex,userTel);
System.out.println(u);
String s = us.addUser(u);
resp.setContentType("text/html;charset=UTF-8");
resp.getWriter().write(s);
}
public void searchUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String userName = req.getParameter("userName");
String userTel = req.getParameter("userTel");
User u = new User();
u.setUserTel(userTel);
u.setUserName(userName);
List<User> users = us.selectUsers(u);
resp.setContentType("text/html;charset=UTF-8");
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(users);
resp.getWriter().write(json);
}
}
后端的代码完成,现在开始写前端的代码
4.前端代码及解析
user_ajax.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>用户列表</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="static/js/jquery-1.11.3.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="row">
<div class="col-md-2">
<button type="button" data-toggle='modal' data-target='#myModal1' class="btn btn-primary">添加</button>
</div>
<div class="col-md-10">
<form class="form-inline">
<div class="form-group">
<label for="username">用户名</label>
<input type="text" class="form-control" id="username" placeholder="用户名">
</div>
<div class="form-group">
<label for="usertel">电话</label>
<input type="tel" class="form-control" id="usertel" placeholder="电话">
</div>
<button type="button" class="btn btn-default" onclick="searchUser()">搜索</button>
</form>
</div>
</div>
<table class="table table-bordered">
<tr>
<%-- <th>序号</th>--%>
<th>用户名</th>
<th>年龄</th>
<th>性别</th>
<th>电话</th>
<th>操作</th>
</tr>
<tbody id="tab"></tbody>
</table>
<!-- Modal(修改) -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">用户修改</h4>
</div>
<div class="modal-body">
<form class="form-horizontal">
<input id="userId" type="hidden" name="user_id">
<div class="form-group">
<label for="inputUserName" class="col-sm-2 control-label">用户名</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputUserName" placeholder="用户名">
</div>
</div>
<div class="form-group">
<label for="inputUserAge" class="col-sm-2 control-label">年龄</label>
<div class="col-sm-10">
<input type="number" class="form-control" id="inputUserAge" placeholder="年龄">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">性别</label>
<div class="col-sm-10">
<label class="radio-inline">
<input type="radio" name="sex" id="inlineRadio1" value="男"> 男
</label>
<label class="radio-inline">
<input type="radio" name="sex" id="inlineRadio2" value="女"> 女
</label>
</div>
</div>
<div class="form-group">
<label for="inputUserTel" class="col-sm-2 control-label">电话</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputUserTel" placeholder="电话">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" onclick="updateUser()" class="btn btn-primary">确认</button>
</div>
</div>
</div>
</div>
<%--用户添加--%>
<div class="modal fade" id="myModal1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel1">用户添加</h4>
</div>
<div class="modal-body">
<form class="form-horizontal">
<div class="form-group">
<label for="inputUserName" class="col-sm-2 control-label">用户名</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputUserName1" placeholder="用户名">
</div>
</div>
<div class="form-group">
<label for="inputUserAge" class="col-sm-2 control-label">年龄</label>
<div class="col-sm-10">
<input type="number" class="form-control" id="inputUserAge1" placeholder="年龄">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">性别</label>
<div class="col-sm-10">
<label class="radio-inline">
<input type="radio" name="gender" id="inlineRadio11" value="男"> 男
</label>
<label class="radio-inline">
<input type="radio" name="gender" id="inlineRadio21" value="女"> 女
</label>
</div>
</div>
<div class="form-group">
<label for="inputUserTel" class="col-sm-2 control-label">电话</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputUserTel1" placeholder="电话">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" onclick="addUser()" class="btn btn-primary">确认</button>
</div>
</div>
</div>
</div>
</body>
<script>
$(function () {
$.ajax({
url:"user",
type:"GET",
dataType:"json",
data:{"method":"queryUserAll"},
success:function (data) {
console.log(data);
var str="";
for(var i=0;i<data.length;i++){
str+="<tr id='t_"+data[i].id+"'><td>"+data[i].userName+"</td><td>"+data[i].userAge+""
+"</td><td>"+data[i].userSex+"</td><td>"+data[i].userTel+""
+"</td><td><button type='button' onclick='deleteUser("+data[i].id+")'>删除</button>"+""
+"<button type='button' data-toggle='modal' data-target='#myModal' onclick='findUser("+data[i].id+")'>修改</button></td></tr>";
}
$("#tab").html(str);
}
});
});
function deleteUser(id) {
$.ajax({
url:"user",
type:"GET",
data:{"method":"deleteUserById","id":id},
dataType:"text",
success:function (data) {
console.log(data);
if(data=="success"){
//删除成功刷新页面
// window.location.reload();
$("#t_"+id).remove();
}
}
});
}
/**
* 点击修改按钮,弹出模态框,根据id查询出数据放入模态框中的表单做数据回显
* @param id
*/
function findUser(id) {
$.ajax({
url:"user",
type:"GET",
data:{"method":"queryUserByID","id":id},
dataType:"json",
success:function (data) {
$("#userId").val(data.id);
$("#inputUserName").val(data.userName);
$("#inputUserAge").val(data.userAge);
if(data.userSex=="男"){
$("#inlineRadio1").prop("checked",true);
}else{
$("#inlineRadio2").prop("checked",true);
}
$("#inputUserTel").val(data.userTel);
}
});
}
/**
* 修改完毕后保存
*/
function updateUser() {
var id = $("#userId").val();
var userName = $("#inputUserName").val();
var userAge = $("#inputUserAge").val();
var userSex = $('input[name="sex"]:checked').val();
var userTel = $("#inputUserTel").val();
var user = {"id":id,"userName":userName,"userAge":userAge,"userSex":userSex,"userTel":userTel,"method":"updataUserById"};
console.log(userSex);
$.ajax({
url:"user",
type:"POST",
data:user,
dataType:"text",
success:function (data) {
if(data=="success"){
window.location.reload();
}
}
});
}
/**
* 用户添加
*/
function addUser() {
var userName = $("#inputUserName1").val();
var userAge = $("#inputUserAge1").val();
var userSex = $('input[name="gender"]:checked').val();
var userTel = $("#inputUserTel1").val();
var user = {"userName":userName,"userAge":userAge,"userSex":userSex,"userTel":userTel,"method":"addUser"};
$.ajax({
url:"user",
type:"POST",
data:user,
dataType:"text",
success:function (data) {
if(data=="success"){
window.location.reload();
}
}
});
}
/**
* 查询用户
*/
function searchUser() {
var username = $("#username").val();
var usertel = $("#usertel").val();
var queryUser = {
"userName":username,
"userTel":usertel,
"method":"searchUser"
};
$.ajax({
url:"user",
type:"GET",
dataType:"json",
data:queryUser,
success:function (data) {
console.log(data);
$("#tab").html("");
var str="";
for(var i=0;i<data.length;i++){
str+="<tr id='t_"+data[i].id+"'><td>"+data[i].userName+"</td><td>"+data[i].userAge+""
+"</td><td>"+data[i].userSex+"</td><td>"+data[i].userTel+""
+"</td><td><button type='button' onclick='deleteUser("+data[i].id+")'>删除</button>"+""
+"<button type='button' data-toggle='modal' data-target='#myModal' onclick='findUser("+data[i].id+")'>修改</button></td></tr>";
}
$("#tab").html(str);
}
});
}
</script>
</html>