使用idea开发javaWeb应用程序的思路(实现用户的增删改查)

网友投稿 404 2022-11-06


使用idea开发javaWeb应用程序的思路(实现用户的增删改查)

在2.7 节基础上,这一节实现了用户的增删改查操作。

完整工程代码:

链接: https://pan.baidu.com/s/1zSGMvSQa-ihwEN5pP4vW6w 提取码: dpw8

工程目录结构如下:

1、添加/修改用户页面

在webapp下新建目录user,用于存放用户相关的页面。

添加和修改使用的是同一个页面,通过url中的参数控制是否是修改操作。

后台通过是否传递了id进行判断新增还是修改。

新建:add.html,代码如下:

天将降大任于斯人也,必先苦其心志,劳其筋骨,饿其体肤,空乏其身,行拂乱其所为,所以动心忍性,曾益其所不能。——孟子

登录账号:

真实姓名:

选择性别:

登录密码:

确认密码:

2、查询用户页面

在user目录下新建list.jsp,代码如下:

<%@page import="java.util.ArrayList"%>

<%@page import="com.my.site.UserEntity"%>

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<%

ArrayList all = ( ArrayList)session.getAttribute("all");

%>

天将降大任于斯人也,必先苦其心志,劳其筋骨,饿其体肤,空乏其身,行拂乱其所为,所以动心忍性,曾益其所不能。——孟子

<%

for(UserEntity user:all)

{%>

修改

<%}

%>

当前时间: <%= (new java.util.Date()).toLocaleString()%>

3、编写后台逻辑-添加/修改

新建:UserAdd类

package com.my.site;

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;

@WebServlet("/user/addUser")

public class UserAdd extends HttpServlet {

/** req 携带了请求相关信息,包括各种配置和请求参数; resp:携带返回相关信息 */

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//从请求对象中获取请求参数:是从前端 usr/add.html页面的 userAddForm 表单提交过来的

String uname = new String(req.getParameter("uname").getBytes("ISO-8859-1"),"utf-8");

String pwd = new String(req.getParameter("pwd").getBytes("ISO-8859-1"),"utf-8");

String realName = new String(req.getParameter("realName").getBytes("ISO-8859-1"),"utf-8");

String sex = new String(req.getParameter("sex").getBytes("ISO-8859-1"),"utf-8");

String pwdRepeat = new String(req.getParameter("pwdRepeat").getBytes("ISO-8859-1"),"utf-8");

String id_str = req.getParameter("id");

boolean bool = false;

//如果有id,就执行更新操作,没有id则执行新增操作

if(null != id_str && !"".equals(id_str)){

int id = Integer.parseInt(req.getParameter("id"));

bool = mysqlOperator.updateUser(id,uname, pwd, realName, sex);

}else {

bool = MySqlOperator.addUser(uname, pwd, realName, sex);

}

resp.setContentType("text/html;charset=UTF-8");

if(bool){

//跳转到主页面,并携带请求体,返回体对象。

resp.sendRedirect("add.html?operation=addUser&success=true");

}else{

//校验失败则跳转到登录页面

resp.sendRedirect("add.html?operation=addUser&success=false");

}

}

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

doPost(req, resp);

}

}

4、编写后台逻辑-查询

新建 UserList 类

package com.my.site;

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 javax.servlet.http.HttpSession;

import java.io.IOException;

import java.util.List;

@WebServlet("/user/list")

public class UserList extends HttpServlet {

/** req 携带了请求相关信息,包括各种配置和请求参数; resp:携带返回相关信息 */

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

List all = MySqlOperator.listAllUser();

HttpSession session = req.getSession();

session.setAttribute("all",all);

resp.setContentType("text/html;charset=UTF-8");

resp.sendRedirect("list.jsp");

}

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

doPost(req, resp);

}

}

5、编写后台逻辑-删除

新建UserDel

package com.my.site;

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;

@WebServlet("/user/del")

public class UserDel extends HttpServlet {

/** req 携带了请求相关信息,包括各种配置和请求参数; resp:携带返回相关信息 */

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//从请求对象中获取请求参数:是从前端 usr/add.html页面的 userAddForm 表单提交过来的

int id = Integer.parseInt(req.getParameter("id").trim());

MySqlOperator.delUser(id);

resp.setContentType("text/html;charset=UTF-8");

resp.sendRedirect("list");

}

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

doPost(req, resp);

}

}

6、 编写数据库操作

package com.my.site;

import java.sql.*;

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Date;

import java.util.List;

public class MySqlOperator {

private static final String MYSQL_URL = "jdbc:mysql://localhost:3309/ztest?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC";

private static final String MYSQL_NAME = "root";

private static final String MYSQL_PASSWORD = "MySql@8022";

private static Connection conn = null;

private static Statement stt = null;

static {

try {

Class.forName("com.mysql.cj.jdbc.Driver");

conn = DriverManager.getConnection(MYSQL_URL,MYSQL_NAME,MYSQL_PASSWORD);

stt = conn.createStatement();

} catch (ClassNotFoundException | SQLException e) {

e.printStackTrace();

}

}

/**

* 根据用户名和密码检查是否合法用户,

* @param uname

* @param pwd

* @return

*/

public static boolean loginChecked(String uname,String pwd){

try {

Statement stt = conn.createStatement();

String sql = "select * from user where account='"+uname+"' and password = '"+pwd+"'";//这样写是有sql注入漏洞的,后面会用到

System.out.println(sql);

ResultSet rs = stt.executeQuery(sql);

while (rs.next()){

return true;

}

} catch ( SQLException e) {

e.printStackTrace();

}

return false;

}

/**

* 添加用户

*/

public static boolean addUser(String uname,String pwd,String realName,String sex){

Date date = new Date();

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:sss");

String data_str = sdf.format(date);

String sql = "insert into user(account,name,password,sex,add_time) values" +

" ('"+uname+"','"+realName+"','"+pwd+"','"+sex+"','"+data_str+"')";

System.out.println(sql);

try {

if(conn.isValid(2)){

initConn();

}

stt.execute(sql);

return true;

} catch (SQLException throwable) {

throwable.printStackTrace();

return false;

}

}

/**查询所有用户*/

public static List listAllUser(){

String sql = "select * from user";

ResultSet rs = null;

ArrayList all = new ArrayList<>();

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:sss");

try {

rs = stt.executeQuery(sql);

while (rs.next()){

UserEntity user = new UserEntity();

user.setUname(rs.getString("account"));

user.setPwd(rs.getString("password"));

user.setRealName(rs.getString("name"));

user.setSex(rs.getString("sex"));

user.setAdd_time(sdf.format(rs.getDate("add_time")));

user.setId(rs.getInt("id"));

all.add(user);

}

System.out.println(sql);

System.out.println("查询条数:"+all.size());

return all;

} catch (SQLException throwable) {

throwable.printStackTrace();

}

return all;

}

/**删除用户*/

public static boolean delUser(int id) {

String sql = "delete from user where id="+id;

try {

stt.execute(sql);

return true;

} catch (SQLException throwable) {

throwable.printStackTrace();

return false;

}

}

/**用于 mysql 连接断开后重连*/

public static void initConn(){

try {

Class.forName("com.mysql.cj.jdbc.Driver");

conn = DriverManager.getConnection(MYSQL_SwflfURL,MYSQL_NAME,MYSQL_PASSWORD);

stt = conn.createStatement();

} catch (ClassNotFoundException | SQLException e) {

e.printStackTrace();

}

}

/**更新用户信息*/

public static boolean updateUser(int id, String uname, String pwd, String realName, String sex) {

Date date = new Date();

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:sss");

String data_str = sdf.format(date);

String sql = "update user set account='"+uname+"',password='"+pwd+"',name='"+realName+"',sex='"+sex+"',add_time='"+data_str+"' where id="+id;

System.out.println(sql);

try {

if(conn.isValid(2)){

initConn();

}

stt.execute(sql);

return true;

} catch (SQLException throwable) {

throwable.printStackTrace();

return false;

}

}

}

7、 运行效果


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:接口设计说明书(接口规格说明书)
下一篇:腾讯api开放平台(腾讯云 API)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~