当前位置:首页 » 《随便一记》 » 正文

实现简单的数据库查询(不完整)

1 人参与  2022年07月25日 12:07  分类 : 《随便一记》  评论

点击全文阅读


文章目录

实现简单的数据库查询JS要点:直接量(常量) :也称为“字面量”,就是看见什么,它就是什么。变量:(全用var定义)例:var a=100; var b="abc";DOM介绍: 1.创建Project (Module)2.创建lib文件3.建立静态资源包(static),放入所需要的静态资源写代码:1.建立pojo包,放入Student类:2.为了方便连接,将部分JDBC操作封装为JDBCUtil类:3.index.jsp引用layui样式(只使用学生管理部分)3.重写service方法,建立服务器(tomcat)将我们的代码以tomcat执行共享给浏览器。4.编写student_list.jsp

实现简单的数据库查询

JS要点:

JS:解释型语言。(由浏览器解释执行代码,不进行预编译。)JS不区分单引号和双引号。直接嵌入HTML页面。
直接量(常量) :也称为“字面量”,就是看见什么,它就是什么。
例如:alert(886)和alert(“886”)执行结果一样;//886是数字所以不需要加引号,"886"是字符串。
在这里插入图片描述
变量:(全用var定义)例:var a=100; var b=“abc”;

变量名区分大小写,允许包含字母、数字、美元符号($)和下划线,但第一个字符不允许是数字,不允许包含空格和其他标点符号。

DOM介绍:

dom技术在JS里面作用:JS语言和Html/Xml标签之间沟通的一个桥梁。

为了方便javascript语言通过dom操作html比较方便,
把html标签的内容划分为各种节点:

文档节点(document)元素节点 也叫标签 getElementsByTagName文本节点属性节点 type=”text” name=”username”注释节点

documnet:是页面中的内置对象,内置对象简单理解就是已经new好的一个对象,对象的名字就叫document。

元素节点的获取:
document.getElementById( id属性值);document.getElementsByTagName(“标签名”);

关系运算符:

全等:===不全等:!==

大小写转换

str.toLowerCase();str.toUpperCase();

查询指定字符串出现索引

str.indexOf(findstr, index);str.indexOf(findstr)str.indexOf(findstr,index)str.lastIndexOf(findstr, index);
split() 方法用于把一个字符串分割成字符串数组。
innerText 直接当成一个字符串展示;innerHtml 将内容当成html来解析

JSP的脚本:(脚本就是一段代码)

语法:<%java代码 %>作用: 执行java代码

JSP表达式:

语法:<%=变量或表达式%>作用: 向浏览器输出变量的值或表达式计算的结果

1.创建Project (Module)

创建完之后:
在这里插入图片描述

在这里插入图片描述

2.创建lib文件

在这里插入图片描述

如图:放入mysql驱动
在这里插入图片描述

3.建立静态资源包(static),放入所需要的静态资源

在这里插入图片描述
文件放下方,自取:

链接:https://pan.baidu.com/s/1v6W11ZOcYOtjwf6f_gZN0g
提取码:call

写代码:

1.建立pojo包,放入Student类:

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.为了方便连接,将部分JDBC操作封装为JDBCUtil类:

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 JDBCUtil() {    }    //加载驱动(static在类加载时执行一次)    static {        try {            Class.forName("com.mysql.jdbc.Driver");        } catch (ClassNotFoundException e) {            e.printStackTrace();        }    }    //建立连接    public static Connection getConnection() throws SQLException {        Connection connection = DriverManager.getConnection(URL,USER,PASSWORD);        return connection;    }    //封装close方法,按照先建立的后关闭原则(与栈类似,创建顺序为connection,preparedStatement,resultSet,所以关闭时顺序如下)    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引用layui样式(只使用学生管理部分)

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html><html><head>  <title>主页</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.name}          <%--         [${user.name}] --%>        </a>        <dl class="layui-nav-child">          <dd>            <a href="javascript:openUser()">基本资料</a>          </dd>          <dd>            <a href="javascript:openPass()">修改密码</a>          </dd>          <dd>            <a href="javascript:openPic()">修改头像</a>          </dd>        </dl>      </li>      <li class="layui-nav-item">        <a href="javascript:logout()">注销</a>      </li>    </ul>  </div>  <div class="layui-side layui-bg-black">    <div class="layui-side-scroll">      <!-- 左侧导航区域(可配合layui已有的垂直导航) -->      <ul class="layui-nav layui-nav-tree" >        <li class="layui-nav-item layui-nav-itemed">          <a href="javascript:;">信息维护</a>          <dl class="layui-nav-child">            <dd>              <a href="javascript:;"                 data-url="${pageContext.request.contextPath}/user"                 class="site-demo-active">管理员管理</a>            </dd>            <dd>              <a href="javascript:;"                 data-url="<%=request.getContextPath()%>/student"                 class="site-demo-active">学生管理</a>            </dd>            <dd>              <a href="javascript:;"                 data-url="<%=request.getContextPath()%>/teacher"                 class="site-demo-active">教师管理</a>            </dd>            <dd>              <a href="javascript:;"                 data-url="${path}/echarts.jsp"                 class="site-demo-active">统计图表</a>            </dd>          </dl>        </li>        <li class="layui-nav-item">          <a href="javascript:;">基础配置</a>          <dl class="layui-nav-child">            <dd>              <a href="javascript:;"                 class="site-demo-active"                 data-url="/web/page/dict/dictlist.jsp">                基础数据维护</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"><!-- 内容主体区域 -->    <iframe name="rightframe" width="99%" height="97%" src="/echarts/getEChartsPage"></iframe>  </div>  <div class="layui-footer">© JAVA - 底部固定区域</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(            '您确认要退出么',            {icon:3},            function() {              location.href = '${path}/user?method=logout'            }    );  }</script></body></html>

3.重写service方法,建立服务器(tomcat)将我们的代码以tomcat执行共享给浏览器。

什么是Servlet?

servlet是java编写的服务器端的程序,运行在web服务器中
作用:

接收用户端发来的请求调用其他java程序来处理请求 将处理结果,返回到服务器中
@WebServlet("/student")public class StudentServlet extends HttpServlet {    @Override    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        //request请求编码统一。        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);        }        //重定向        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.编写student_list.jsp

JSP:
Servlet的作用:用于java语言开发动态资源的技术!!
JSP的作用:用java语言 + html语言,开发动态资源的技术!!
JSP就是servlet!!!

JSP的脚本:(脚本就是一段代码)
语法:<%java代码 %>
作用: 执行java代码

JSP表达式:
语法:<%=变量或表达式%>
作用: 向浏览器输出变量的值或表达式计算的结果

%@ 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>姓名</th>        <th>年龄</th>        <th>性别</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="">删除</a></td>        </tr>    <%        }    %></table></body></html>

点击全文阅读


本文链接:http://zhangshiyu.com/post/43781.html

<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1