当前位置 : 主页 > 编程语言 > java >

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

来源:互联网 收集:自由互联 发布时间:2021-04-03
在2.7 节基础上,这一节实现了用户的增删改查操作。 完整工程代码: 链接: https://pan.baidu.com/s/1zSGMvSQa-ihwEN5pP4vW6w 提取码: dpw8 工程目录结构如下: 1、添加/修改用户页面 在webapp下新建目

在2.7 节基础上,这一节实现了用户的增删改查操作。
完整工程代码:
链接: https://pan.baidu.com/s/1zSGMvSQa-ihwEN5pP4vW6w 提取码: dpw8


工程目录结构如下:

在这里插入图片描述

1、添加/修改用户页面

在webapp下新建目录user,用于存放用户相关的页面。
添加和修改使用的是同一个页面,通过url中的参数控制是否是修改操作。
后台通过是否传递了id进行判断新增还是修改。
新建:add.html,代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>登录页面</title>
 <link rel="stylesheet" type="text/css" href="../css/my.css" rel="external nofollow" rel="external nofollow" >
 <script type="text/javascript" src="../js/my.js"></script>
</head>

<body>
<div id="main-container" >
 <div id="div-header" >
  <h3 style="margin-bottom:0;">欢迎进入我的网站</h3>
  </hr>
  <p>
   天将降大任于斯人也,必先苦其心志,劳其筋骨,饿其体肤,空乏其身,行拂乱其所为,所以动心忍性,曾益其所不能。——孟子
  </p>
 </div>
 <div id="div-content" >
  <h3 style="margin-bottom:0;">添加用户</h3>
  <form id="userAddForm" class="userAddForm" action="addUser" method="post">
   <input id="id" type="hidden" name="id" />
   <p>登录账号: <input id="uname" type="text" name="uname" /></p>
   <p>真实姓名: <input id="realName" type="text" name="realName" /></p>
   <p>选择性别: <select id="sex" name="sex" style="width:170px">
    <option id="option_m" value ="男">男</option>
    <option id="option_w" value ="女">女</option>
   </select></p>
   <p>登录密码: <input id="pwd" type="password" name="pwd" /></p>
   <p>确认密码: <input id="pwdRepeat" type="password" name="pwdRepeat" /></p>
   <input type="button" value="提交" onclick="submitAddUser()"/>
  </form>
 </div>


</div>
<script type="text/javascript">

//检查输入是否为非空
function submitAddUser()
{
 var uname = document.getElementById("uname").value;//获取输入的用户名的值
 var pwd = document.getElementById("pwd").value;//获取输入的密码值
 var pwdRepeat = document.getElementById("pwdRepeat").value;//获取输入确认密码值
 var realName = document.getElementById("realName").value;//获取输入的姓名值
 var sex = document.getElementById("sex").value;//获取输入的性别值
 if(uname == "" || pwd == "" || pwdRepeat == "" || realName == "" || sex == "" ){
  alert("请将信息填写完整后再提交。");
  return;
 }
 if( pwd != pwdRepeat){
  alert("两次密码输入不一致,请重新输入。");
 }
 document.getElementById("userAddForm").submit(); //输入不为空则跳转到主页面

}
//从url中获取参数
function getQueryVariable(variable)
{
  var query = window.location.search.substring(1);
  console.log(query);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if(pair[0] == variable){return decodeURI(pair[1]);}
  }
  return(false);
}
//判断参数是否为true,不为true则弹窗提示密码错误。
var bool = getQueryVariable("success");
var operation = getQueryVariable("operation");
if(bool == "false" && operation=="addUser"){
 alert("操作失败。");
}else if(bool == "true" && operation=="addUser"){
 alert("操作成功。");
}
showOld();
//从url中获取参数,回显
function showOld()
{
  var uname = getQueryVariable("uname");
  var realName = getQueryVariable("realName");
  var id = getQueryVariable("id");
  var sex = getQueryVariable("sex");
  var pwd = getQueryVariable("pwd");
  if(id != "" && id != null){
  document.getElementById("uname").value=uname;
  document.getElementById("pwd").value=pwd;
  document.getElementById("pwdRepeat").value = pwd;
  document.getElementById("realName").value = realName;
  document.getElementById("id").value = id;
  if(sex == "男"){
   document.getElementById("option_m").selected = true;
  }else{
   document.getElementById("option_w").selected = true;
  }
  }
}
</script>
</body>
</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"%>
<!DOCTYPE html>
<html>
<head>
 <title>我的网站</title>
 <meta charset="utf-8">
 <link rel="stylesheet" type="text/css" href="../css/my.css" rel="external nofollow" rel="external nofollow" >
</head>
<body>
<!-- jsp 页面可以内嵌 java代码-->
<%
 ArrayList<UserEntity> all = ( ArrayList<UserEntity>)session.getAttribute("all");

%>
<div id="main-container" >
 <div id="div-header" >
  <h3 style="margin-bottom:0;">用户查询</h3>
  </hr>
  <p>
   天将降大任于斯人也,必先苦其心志,劳其筋骨,饿其体肤,空乏其身,行拂乱其所为,所以动心忍性,曾益其所不能。——孟子
  </p>
 </div>
 <div id="div-content" >
  <table border="1" class="table" >
  <tr>
   <td>编号</td>
   <td>用户名</td>
   <td>密码</td>
   <td>真实姓名</td>
   <td>性别</td>
   <td>注册时间</td>
   <td>操作</td>
  </tr>
  <%
   for(UserEntity user:all)
   {%>
   <tr>
    <td ><%=user.getId() %></td>
    <td><%=user.getUname() %></td>
    <td><%=user.getPwd() %></td>
    <td><%= user.getRealName() %></td>
    <td><%= user.getSex() %></td>
    <td><%= user.getAdd_time() %></td>
    <td><a href="del?id=<%=user.getId()%> " rel="external nofollow" >删除</a>
    <a href="add.html?id=<%=user.getId()%>&uname=<%=user.getUname()%>&pwd=<%=user.getPwd()%>&realName=<%=user.getRealName()%>&sex=<%=user.getSex()%>" rel="external nofollow" >修改</a>
    </td>
   </tr>
   <%}
  %>
 </table>
  <p>
   当前时间: <%= (new java.util.Date()).toLocaleString()%>
  </p>
 </div>
</div>
<script type="text/javascript">
//点击按钮跳转到登录页面
function toAddUser()
{
 window.location.href="user/add.html" rel="external nofollow" ;
}
function toSearchUser()
{
 window.location.href="user/list" rel="external nofollow" ;
}
</script>
</body>
</html>

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<UserEntity> 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<UserEntity> listAllUser(){
  String sql = "select * from user";

  ResultSet rs = null;
  ArrayList<UserEntity> 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_URL,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、 运行效果

在这里插入图片描述
在这里插入图片描述

到此这篇关于使用idea开发javaWeb应用程序的思路(实现用户的增删改查)的文章就介绍到这了,更多相关idea 开发javaweb应用程序内容请搜索易盾网络以前的文章或继续浏览下面的相关文章希望大家以后多多支持易盾网络!

网友评论