Javaweb addition, deletion, modification and query


A few days ago, I was learning Java web login from the up owner of station B. Suddenly, I felt that it was really good to learn C++ in the past few years. Not only was it not contradictory to read Java, but I also found it not difficult. The additions, deletions, modifications and checks this time were slowly made by myself. I’m awesome.

For some details, such as where to put the jar package and how to build the package, you can read the previous blog
. Reference for ideas in this article: [1]
Complete code: https://github.com/wangwyForNewTime/javaWeb-FindFromMySQL
The database is different from the one used in the previous article Repeatedly
Insert image description here

1. Front-end page

First of all, the difference from the previous login is that the query needs to read all the data in the database and present it, so it needs to use the JSLT library . You can refer to this for
knowledge points , but the version given above is very low. Then I worked for a long time and kept reporting 500. Then I checked and found out from this blogger that tomcat 10 and above uses version 2.0.0 or above, so I downloaded to 2.0.0 from this blogger and put the jar package into lib in

Insert image description here

<%--
  Created by IntelliJ IDEA.
  User: 大喵喵
  Date: 2023/2/28
  Time: 17:55
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
  <meta charset="UTF-8">
  <title>管理员</title>
  <link rel="stylesheet" href="css/bootstrap.min.css">
  <link rel="stylesheet" href="css/index.css">
</head>
  <body>
  <div class="mainbac">
    <h1>Maybe Something System </h1>
    <div class="lii">欢迎你,管理员</div>
    <div class="duzii">


      <form class="form-inline"  action="index">
        <div class="form-group has-success has-feedback">
          <label class="control-label">ID:</label>
          <input  class="form-control" style="margin-left: 20px;" name="test">
          <button type="submit" class="btn btn-default">&nbsp;&nbsp;&nbsp;&nbsp;</button>
         <button type="button" class="btn btn-link">返回首页</button>
        </div>
      </form>

      <table class="table table-striped" style="margin-top: 50px;">
        <thead>
        <tr >
          <th>ID</th>
          <th>密码</th>
          <th>身份</th>
          <th>操作</th>
        </tr>
        </thead>

        <tbody>
        <tr>
          <td>Wen</td>
          <td>123456</td>
          <td>管理员</td>
          <td><a href="#">设置</a> | <a href="#">删除</a></td>
        </tr>

        <c:forEach var="e" items="${list}">
          <tr>

            <td>${
    
    e.username}</td>
            <td>${
    
    e.password}</td>
            <td>管理员</td>
            <td><a href="#">设置</a> | <a href="#">删除</a></td>

          </tr>
        </c:forEach>


<%--        <tr>--%>
<%--          <td>Te</td>--%>
<%--          <td>12</td>--%>
<%--          <td>普通用户</td>--%>
<%--          <td><a href="#">设置</a> | <a href="#">删除</a></td>--%>
<%--        </tr>--%>
        </tbody>

      </table>

    </div>
  </div>
  </body>
</html>

2.java linked database - integrated mybatis

If you want to test the connection to the database, you can directly refer to 3 in the previous article for all operations
. The function here is to enable java code to operate the database.

2.1 Establishing layers

There is nothing magical about layered thinking. It is just the function you want to implement. You have to be willing to write it all in one java file. But if you separate different classes into independent files, it will look clear and clear. This is layered thinking.

This is the directory where various files are finally created
Insert image description here

2.2 Entity layer entity

Just create the user class

package entity;

public class User {
    
    
    private  Integer userId;
    private  String username;
    private  String password;

    public Integer getUserId() {
    
    
        return userId;
    }

    public void setUserId(Integer userId) {
    
    
        this.userId = userId;
    }

    public String getUsername() {
    
    
        return username;
    }

    public void setUsername(String username) {
    
    
        this.username = username;
    }

    public String getPassword() {
    
    
        return password;
    }

    public void setPassword(String password) {
    
    
        this.password = password;
    }
}

2.3 mapper (dao layer)

It is to create a matchmaking interface for Java to operate MySQL.
This time we want to obtain all the data, so the required command is select * from pa(数据库名)
UserMapper.java

package mapper;

import entity.User;

import java.util.List;

public interface UserMapper {
    
    
    public User queryUserByName(String username);

    public List<User> findAll();
}

UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!-- 引入dtd -->
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!-- namespace就是接口的包名加类名 -->
<mapper namespace="mapper.UserMapper">
    <select id="queryUserByName" resultType="entity.User" parameterType="String">
        <!-- 写SQL语句 -->
        select * from pa where username = #{
    
    username}
    </select>
    <select id="findAll" resultType="entity.User" parameterType="String">
        <!-- 写SQL语句 -->
        select * from pa
    </select>

</mapper>

2.4 mybatis configuration file

Without this, don’t even think about connecting to the database
Insert image description here
mysql.properties. Note that test1 is the name of the database. Change it as needed. The password is the MySQL password:

driver = com.mysql.cj.jdbc.Driver
url = jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=UTF-8
username = root
password = 1234

mybatis-config.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <properties resource="mysql.properties"/>
    <!-- 默认使用的环境 ID(比如:default="development")
    也就是说我们可以配置多套<environment>环境-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <!--                JDBC 驱动-->
                <property name="driver" value="${driver}"/>
                <!--                url数据库的 JDBC URL地址。-->
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <package name="com.xxxx.mapper"/>
    </mappers>

</configuration>


2.5 Tool layer util

A layer that stores utility functions. Here you need a function that creates a session.
Insert image description here

/**
 *
 */
package com.xxxx.util;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


public class GetSqlSession {
    
    
   public static SqlSession createSqlSession(){
    
    
       SqlSessionFactory sqlSessionFactory = null;
       InputStream input = null;
       SqlSession session = null;

       try{
    
    
           //获取mybatis的环境配置文件
           String resource ="mybatis-config.xml";
           //以流的方式获取resourse
           input = Resources.getResourceAsStream(resource);
           //创建会话工厂
           sqlSessionFactory=new SqlSessionFactoryBuilder().build(input);
           //通过工厂得到SqlSession
           session=sqlSessionFactory.openSession();
           return session;
       } catch (IOException e) {
    
    
           e.printStackTrace();
           return null;
       }
   }

   public static void main(String[] args){
    
    
       System.out.println(createSqlSession());
   }


}



You can write a function to test whether some of them can connect to the database. For details, see the previous blog 3.7

3.Backend functions

3.1 the servlet

If jsp wants to transfer things to the background, and if the background wants to transfer values ​​to jsp, servlets are needed. If the implemented function is complex, the code to implement the function can be placed in the service layer. But the code here is simple, so I didn’t separate it and wrote it directly in the servlet layer.

package servlet;
import entity.User;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import mapper.UserMapper;
import org.apache.ibatis.session.SqlSession;
import service.Userservice;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import util.GetSqlSession;

import java.io.IOException;
import java.util.List;

@WebServlet("/index")//这个/很重要
public class Userservlet extends HttpServlet {
    
    
   // private Userservice userService =new Userservice();

    @Override
    protected  void  service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    
    
        String uTestValue =request.getParameter("test");
        System.out.println(uTestValue);

        SqlSession session = GetSqlSession.createSqlSession();
        UserMapper userMapper = session.getMapper(UserMapper.class);
        List<User> list=userMapper.findAll();
        System.out.println(list);
        request.setAttribute("list", list);
        request.getRequestDispatcher("index.jsp").forward(request, response);
    }
}

4. Complete additions, deletions, modifications and checks

I really didn’t want to study it myself, so I adjusted this blogger ’s code and used it directly.
Entire code: https://github.com/wangwyForNewTime/JavaWeb-Add-delete-correct-and-check

Guess you like

Origin blog.csdn.net/Cream_Cicilian/article/details/129271624