当前位置:网站首页>Realize simple database query (incomplete)
Realize simple database query (incomplete)
2022-07-29 05:33:00 【Xiao Hong is working hard】
List of articles
- Realize simple database query
- 1. establish Project (Module)
- 2. establish lib file
- 3. Create a static resource package (static), Put in the required static resources
- Write code :
- 1. establish pojo package , Put in Student class :
- 2. For easy connection , Will be part of JDBC Operation encapsulation is JDBCUtil class :
- 3.index.jsp quote layui style ( Only use the student management part )
- 3. rewrite service Method , Set up the server (tomcat) Put our code in tomcat Execute share to browser .
- 4. To write student_list.jsp
Realize simple database query
JS The main points of :
- JS: Explanatory language .( The code is interpreted and executed by the browser , No precompiling .)
- JS Don't differentiate between single and double quotes .
- Direct embedding HTML page .
Direct measurement ( Constant ) : Also known as “ Literal ”, Just see something , It's what it is .
- for example :alert(886) and alert(“886”) The results are the same ;//886 It's a number, so you don't need quotation marks ,"886" Is string .
Variable :( All use var Definition ) example :var a=100; var b=“abc”;
Variable names are case sensitive , Allow letters 、 Numbers 、 Dollar symbol ($) And the underline , But the first character is not allowed to be a number , Spaces and other punctuation marks are not allowed .
DOM Introduce :
dom Technology in JS Internal function :JS Language and Html/Xml A bridge between labels .
For convenience javascript Language passing dom operation html It's more convenient ,
hold html The content of the tag is divided into various nodes :
- Document nodes (document)
- Element nodes It's also called a label getElementsByTagName
- Text node
- Attribute node type=”text” name=”username”
- Comment node
documnet: Is the built-in object in the page , The built-in object is simply understood as already new A good object , The name of the object is document.
- Acquisition of element nodes :
document.getElementById( id Property value );- document.getElementsByTagName(“ Tag name ”);
Relational operator :
- Congruence :===
- Incongruence :!==
toggle case
- str.toLowerCase();
- str.toUpperCase();
Query the index of the specified string
- str.indexOf(findstr, index);
- str.indexOf(findstr)
- str.indexOf(findstr,index)
- str.lastIndexOf(findstr, index);
- split() Method is used to split a string into an array of strings .
- innerText Show it directly as a string ;innerHtml Think of content as html Parsing
JSP Script for :( A script is a piece of code )
- grammar :<%java Code %>
- effect : perform java Code
JSP expression :
- grammar :<%= Variable or expression %>
- effect : Output the value of a variable or the result of an expression calculation to the browser
1. establish Project (Module)
After creation :
2. establish lib file
Pictured : Put in mysql drive
3. Create a static resource package (static), Put in the required static resources
Put the file below , Self taking :
link :https://pan.baidu.com/s/1v6W11ZOcYOtjwf6f_gZN0g
Extraction code :call
Write code :
1. establish pojo package , Put in Student class :
package com.situ.web.pojo;
public class Student {
private Integer id;
private String name;
private Integer age;
private String gender;
public Student(Integer id, String name, Integer age, String gender) {
this.id = id;
this.name = name;
this.age = age;
this.gender = gender;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
'}';
}
}
2. For easy connection , Will be part of JDBC Operation encapsulation is JDBCUtil class :
package com.situ.web.util;
import java.sql.*;
public class JDBCUtil {
private final static String URL = "jdbc:mysql://localhost:3306/java2207?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
private final static String USER = "root";
private final static String PASSWORD = "root";
// Private constructors prevent instantiation
private JDBCUtil() {
}
// The load driver (static Execute once when the class is loaded )
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
// Establishing a connection
public static Connection getConnection() throws SQLException {
Connection connection = DriverManager.getConnection(URL,USER,PASSWORD);
return connection;
}
// encapsulation close Method , According to the principle of establishing before closing ( Similar to stack , The order of creation is connection,preparedStatement,resultSet, So the order of closing is as follows )
public static void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet){
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
3.index.jsp quote layui style ( Only use the student management part )
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <title> Home page </title> <link rel="stylesheet" type="text/css" href="static/layui/css/layui.css"/> </head> <body class="layui-layout-body"> <div class="layui-layout layui-layout-admin"> <div class="layui-header"> <div class="layui-logo">JAVA-0000</div> <ul class="layui-nav layui-layout-left"> </ul> <ul class="layui-nav layui-layout-right"> <li class="layui-nav-item"> <a href="javascript:;"> <%-- <img src="<%=path%>/img/fei.png" --%> <!-- class="layui-nav-img"/> --> user ${
user.name}
<%-- [${
user.name}] --%>
</a>
<dl class="layui-nav-child">
<dd>
<a href="javascript:openUser()"> Basic information </a>
</dd>
<dd>
<a href="javascript:openPass()"> Change Password </a>
</dd>
<dd>
<a href="javascript:openPic()"> Modify the head image </a>
</dd>
</dl>
</li>
<li class="layui-nav-item">
<a href="javascript:logout()"> Cancellation </a>
</li>
</ul>
</div>
<div class="layui-side layui-bg-black">
<div class="layui-side-scroll">
<!-- Left navigation area ( Compatible layui Existing vertical navigation ) -->
<ul class="layui-nav layui-nav-tree" >
<li class="layui-nav-item layui-nav-itemed">
<a href="javascript:;"> Information maintenance </a>
<dl class="layui-nav-child">
<dd>
<a href="javascript:;"
data-url="${pageContext.request.contextPath}/user"
class="site-demo-active"> Administrator management </a>
</dd>
<dd>
<a href="javascript:;"
data-url="<%=request.getContextPath()%>/student"
class="site-demo-active"> Student management </a>
</dd>
<dd>
<a href="javascript:;"
data-url="<%=request.getContextPath()%>/teacher"
class="site-demo-active"> Teacher management </a>
</dd>
<dd>
<a href="javascript:;"
data-url="${path}/echarts.jsp"
class="site-demo-active"> Statistical charts </a>
</dd>
</dl>
</li>
<li class="layui-nav-item">
<a href="javascript:;"> Basic configuration </a>
<dl class="layui-nav-child">
<dd>
<a href="javascript:;"
class="site-demo-active"
data-url="/web/page/dict/dictlist.jsp">
Basic data maintenance </a>
</dd>
<dd>
<a href="javascript:;" class="site-demo-active"
data-url="/web/404.jsp">404-1</a>
</dd>
</dl>
</li>
</ul>
</div>
</div>
<div class="layui-body"><!-- Content subject area -->
<iframe name="rightframe" width="99%" height="97%" src="/echarts/getEChartsPage"></iframe>
</div>
<div class="layui-footer"> JAVA - Bottom fixed area </div>
</div>
<script src="static/layui/layui.js"></script>
<script type="text/javascript">
var $ = layui.jquery;
var layer = layui.layer;
var element = layui.element;
$('.site-demo-active').click(function() {
window.open($(this).data('url'), "rightframe");
});
element.render();// element.init();
function openURL(url){
window.open(url, "rightframe");
}
function logout() {
layer.confirm( ' Are you sure you want to exit ',
{
icon:3}, function() {
location.href = '${
path}/user?method=logout'
}
);
}
</script>
</body>
</html>
3. rewrite service Method , Set up the server (tomcat) Put our code in tomcat Execute share to browser .
What is? Servlet?
servlet yes java Write a server-side program , Running on the web Server
effect :
- Receive the request from the client
- Call other java Program to process requests Will deal with the result , Return to the server
@WebServlet("/student")
public class StudentServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//request Request unified coding .
req.setCharacterEncoding("utf-8");
String method = req.getParameter("method");
if(method == null || method.equals("")){
method = "selectAll";
}
switch(method){
case "selectAll":
selectAll(req,resp);
break;
case "deleteById":
delete(req,resp);
break;
case "add":
add(req,resp);
break;
case "update":
update(req,resp);
break;
case "getStudentUpdatePage":
getStudentById(req,resp);
break;
}
}
private void getStudentById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String id = req.getParameter("id");
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
Student student = null;
List<Student> list = new ArrayList<>();
try {
connection = JDBCUtil.getConnection();
String sql = "select name,age,gender from student where id=?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,Integer.parseInt(id));
resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
String gender = resultSet.getString("gender");
student = new Student(Integer.parseInt(id),name,age,gender);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JDBCUtil.close(connection,preparedStatement,resultSet);
}
req.setAttribute("student",student);
req.getRequestDispatcher("student_update.jsp").forward(req,resp);
}
private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
System.out.println("StudentServlet.update");
Connection connection = null;
PreparedStatement preparedStatement = null;
Integer id = Integer.parseInt(req.getParameter("id"));
String name = req.getParameter("name");
Integer age = Integer.parseInt(req.getParameter("age"));
String gender = req.getParameter("gender");
try {
connection = JDBCUtil.getConnection();
String sql = "update student set name=?,age=?,gender=? where id=?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,name);
preparedStatement.setInt(2,age);
preparedStatement.setString(3,gender);
preparedStatement.setInt(4,id);
System.out.println(preparedStatement);
int count = preparedStatement.executeUpdate();
System.out.println(count);
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JDBCUtil.close(connection,preparedStatement,null);
}
resp.sendRedirect(req.getContextPath() + "/student?method=selectAll");
}
private void add(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String name = req.getParameter("name");
String age = req.getParameter("age");
String gender = req.getParameter("gender");
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = JDBCUtil.getConnection();
String sql = "insert into student(name,age,gender) values (?,?,?)";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,name);
preparedStatement.setInt(2, Integer.parseInt(age));
preparedStatement.setString(3,gender);
System.out.println(preparedStatement);
int count = preparedStatement.executeUpdate();
System.out.println(count);
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JDBCUtil.close(connection,preparedStatement,null);
}
resp.sendRedirect(req.getContextPath() + "/student?method=selectAll");
}
private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String id = req.getParameter("id");
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = JDBCUtil.getConnection();
String sql = "delete from student where id=?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,Integer.parseInt(id));
System.out.println(preparedStatement);
int count = preparedStatement.executeUpdate();
System.out.println(count);
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JDBCUtil.close(connection,preparedStatement,null);
}
// Redirect
resp.sendRedirect(req.getContextPath() + "/student");
}
private void selectAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
List<Student> list = new ArrayList<>();
try {
connection = JDBCUtil.getConnection();
String sql = "select id,name,age,gender from student";
preparedStatement = connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
String gender = resultSet.getString("gender");
Student student = new Student(id,name,age,gender);
list.add(student);
}
for (Student student : list) {
System.out.println(student);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JDBCUtil.close(connection,preparedStatement,resultSet);
}
resp.setContentType("text/html;charset=utf-8");
req.setAttribute("list",list);
req.getRequestDispatcher("student_list.jsp").forward(req,resp);
}
}
4. To write student_list.jsp
JSP:
Servlet The role of : be used for java Language development technology of dynamic resources !!
JSP The role of : use java Language + html Language , Technology for developing dynamic resources !!
JSP Namely servlet!!!
JSP Script for :( A script is a piece of code )
grammar :<%java Code %>
effect : perform java Code
JSP expression :
grammar :<%= Variable or expression %>
effect : Output the value of a variable or the result of an expression calculation to the browser
%@ page import="java.util.List" %>
<%@ page import="com.situ.web.pojo.Student" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<link rel="stylesheet" type="text/css" href="static/bootstrap-3.4.1-dist/css/bootstrap.css"/>
</head>
<body>
${
list}
<%
List<Student> list = (List<Student>) request.getAttribute("list");
%>
<table class="table table-striped table-bordered table-hover table-condensed">
<tr>
<th>ID</th>
<th> full name </th>
<th> Age </th>
<th> Gender </th>
</tr>
<%
for (Student student:list) {
%>
<tr>
<td><%=student.getId()%></td>
<td><%=student.getName()%></td>
<td><%=student.getAge()%></td>
<td><%=student.getGender()%></td>
<td><a href=""> Delete </a></td>
</tr>
<%
}
%>
</table>
</body>
</html>
边栏推荐
- QT learning: qdropevent drag event
- Day 3
- The function of using wechat applet to scan code to log in to the PC web of the system
- Day 1
- More than 200 ISVs have settled in! The first anniversary of Alibaba cloud computing nest
- VIM editor use
- Occt learning 003 - MFC single document project
- With cloud simulation platform, Shichuang technology supports the upgrading of "China smart manufacturing"
- R & D efficiency | analysis of kubernetes' core technology and Devops' landing experience
- MySQL的详细安装使用教程(保姆式安装图文讲解)
猜你喜欢
随机推荐
【剑指offer】— 详解库函数atoi以及模拟实现atoi函数
关于局部变量
【C语言系列】—深度解剖数据在内存中的存储(二)-浮点型
ClickHouse学习(十一)clickhouseAPI操作
Longest string without duplicate characters
微信小程序视频上传组件直接上传至阿里云OSS
365 day challenge leetcode 1000 questions - day 039 full binary tree inserter + find peak II + snapshot array
全局components组件注册
使用微信小程序扫码登录系统PC端web的功能
浅谈范式
paddle.fluild常量计算报错‘NoneType‘ object has no attribute ‘get_fetch_list‘
Preemptive appointment | Alibaba cloud shadowless cloud application online conference appointment opens
省市区三级联动(简单又完美)
R & D efficiency | analysis of kubernetes' core technology and Devops' landing experience
Dynamic sorting of DOM object element blocks in applets
JD cloud golden autumn cloud special offer is in progress! Code scanning participation activities
Basic principle of recursion
About local variables
Camunda 1、Camunda工作流-介绍
Cmu15-213 malloc lab experiment record