商品信息&学生信息查询 KQC

导读:本篇文章讲解 商品信息&学生信息查询 KQC,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

1.商品查询 0730 KQC

1.1要求:

创建商品表:商品编号,名字,价格,日期,产地。使用servlet+dao查询数据显示到页面

1.2 实现效果:

在这里插入图片描述

1.3 思路:

参考思路:
在这里插入图片描述

1.4实现代码目录结构:

在这里插入图片描述

1. 5 导jar包/关联/配置(略)

1.6 代码部分:

mySQL部分:

创建数据库:

#创建数据库
create database 70730_db
default character set utf8mb4 #设置字符集
default collate utf8mb4_general_ci #设置排序规则 

创建表:

#创建商品表:商品编号,名字,价格,日期,产地
#使用servlet+dao查询数据显示到页面
create table goods
(
	goodId int primary key auto_increment,
	goodName varchar(200),
	price decimal(5,2),
	pubDate date,
	address varchar(20)
);

insert into goods
(goodName,price,pubDate,address)
select '商品1',1.1,'2001-01-01','河南' union 
select '商品2',2.2,'2002-02-02','河北';
#只显示图书数据用拼接,如果有添加等功能时,不能用拼接

select * from goods;

idea部分:

BaseDAO:

package com.util;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BaseDAO {

	//四大金刚
	//驱动类
	private static final String DRIVER="com.mysql.cj.jdbc.Driver";
	//连接地址
	private static final String URL="jdbc:mysql://localhost:3306/70730_db?useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai";
	//用户名
	private static final String USER="root";
	//密码
	private static final String PASSWORD="123456";

	//获取连接
	public static Connection getConnection(){

		Connection con = null;

		try{
			//加载驱动类
			Class.forName(DRIVER);
			//获取连接
			con = DriverManager.getConnection(URL,USER,PASSWORD);
			
		}catch(Exception ex){
			ex.printStackTrace();
		}

		return con;
	}

	//关闭数据库对象
	public static void closeAll(Connection con,Statement st,ResultSet rs){
		
		if(rs!=null){
			try{
				rs.close();
			}catch(Exception ex){
				ex.printStackTrace();
			}
			
		}

		if(st!=null){

			try{
				st.close();
			}catch(Exception ex){
				ex.printStackTrace();
			}
			
		}

		if(con!=null){
			try{
				con.close();
			}catch(Exception ex){
				ex.printStackTrace();
			}
			
		}

	}


	//通用设置参数方法
	public static void setParams(PreparedStatement pst,Object[] params){

		if(params==null){
			return;
		}

		for(int i=0;i<params.length;i++){
			try{
				pst.setObject(i+1,params[i]);
			}catch(Exception ex){
				ex.printStackTrace();
			}
		}
	}


	//通用增删改
	public static int executeUpdate(String sql,Object[] params){

		Connection con = null;
		PreparedStatement pst = null;
		
		int res = -1;
		
		try{

			//获取连接
			con = getConnection();
			//创建预编译命令执行对象
			pst = con.prepareStatement(sql);
			//设置参数
			setParams(pst,params);
			//执行
			res = pst.executeUpdate();

		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			closeAll(con,pst,null);
		}
		
		return res;
	}


	//通用查询
	public static List<Map<String,Object>> executeQuery(String sql,Object[] params) {

		List<Map<String,Object>> rows = new ArrayList<>();

		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs = null;

		try{
			//获取连接	
			con = getConnection();			
			//获取命令对象
			pst = con.prepareStatement(sql);
			//设置参数
			setParams(pst,params);
			//执行查询
			rs = pst.executeQuery();

			//通过rs获取结果集的结构信息
			ResultSetMetaData rsmd =  rs.getMetaData();
			//获取结果集的列数
			int colCount = rsmd.getColumnCount();

			//遍历查询结果,并封装到List<Map>中
			while(rs.next()){
				//用Map存储当前行的各个列数据
				Map<String,Object> map = new HashMap<>();
				//循环获取每一列的信息
				for(int i=1;i<=colCount;i++){
					//获取列名(使用rsmd)
					String colName = rsmd.getColumnLabel(i);
					//获取列值(使用rs)
					Object colVal = rs.getObject(i);
					//将当前列存储到map中
					map.put(colName,colVal);								
				}
				
				//将遍历的当前行的数据存储到List中
				rows.add(map);
							
			}


		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			closeAll(con,pst,rs);
		}
		
		return rows;

	}

}

Goods:

package com.entity;

import java.util.Date;

public class Goods {
    private Integer goodId;
    private String goodName;
    private Double price;
    private Date pubDate;
    private String address;

    public Goods() {
    }

    public Goods(Integer goodId, String goodName, Double price, Date pubDate, String address) {
        this.goodId = goodId;
        this.goodName = goodName;
        this.price = price;
        this.pubDate = pubDate;
        this.address = address;
    }

    public Integer getGoodId() {
        return goodId;
    }

    public void setGoodId(Integer goodId) {
        this.goodId = goodId;
    }

    public String getGoodName() {
        return goodName;
    }

    public void setGoodName(String goodName) {
        this.goodName = goodName;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public Date getPubDate() {
        return pubDate;
    }

    public void setPubDate(Date pubDate) {
        this.pubDate = pubDate;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Goods{" +
                "goodId=" + goodId +
                ", goodName='" + goodName + '\'' +
                ", price=" + price +
                ", pubDate=" + pubDate +
                ", address='" + address + '\'' +
                '}';
    }
}

IGoodsBAO:

package com.dao;

import java.util.List;
import java.util.Map;

public interface IGoodsBAO {
    List<Map<String,Object>> listAll();
}

GoodsBAOImpl:

package com.dao.impl;

import com.dao.IGoodsBAO;
import com.util.BaseDAO;

import java.util.List;
import java.util.Map;

public class GoodsBAOImpl implements IGoodsBAO {
    @Override
    public List<Map<String, Object>> listAll() {
        String sql="select * from goods";
        return BaseDAO.executeQuery(sql,null);
    }
}

IGoodsService:

package com.service;

import java.util.List;
import java.util.Map;

public interface IGoodsService {
    List<Map<String,Object>> listAll();
}

GoodsServiceImpl:

package com.service.impl;

import com.dao.IGoodsBAO;
import com.dao.impl.GoodsBAOImpl;
import com.service.IGoodsService;

import java.util.List;
import java.util.Map;

public class GoodsServiceImpl implements IGoodsService {
    IGoodsBAO goodsBAO=new GoodsBAOImpl();
    @Override
    public List<Map<String, Object>> listAll() {
        return goodsBAO.listAll();
    }
}

TestServlet:

package com.servlet;

import com.service.IGoodsService;
import com.service.impl.GoodsServiceImpl;

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;
import java.util.List;
import java.util.Map;

@WebServlet(urlPatterns = "/TestServlet/*")
public class TestServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri=req.getRequestURI();
        String process=uri.substring(uri.lastIndexOf("/")+1);
        System.out.println("截取字段:"+process);
        //设置编码
        req.setCharacterEncoding("utf-8");

        switch(process){
            case "query":
                this.query(req,resp);
                break;
        }

    }

    IGoodsService goodsService=new GoodsServiceImpl();

    private void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Map<String, Object>> goodList=goodsService.listAll();
        req.setAttribute("goodList",goodList);
        req.getRequestDispatcher("/goodList.jsp").forward(req,resp);
    }
}

goodList.jsp:

<%@ page import="java.util.Map" %>
<%@ page import="java.util.List" %><%--
  Created by IntelliJ IDEA.
  User: 33154
  Date: 2022/8/1
  Time: 17:48
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <%=request.getAttribute("goodList")%>
</head>
<body>
    <%
        List<Map<String, Object>> goodsList= (List<Map<String, Object>>) request.getAttribute("goodList");
        for(Map<String, Object> goods:goodsList){
            out.print("<p>");
            out.print(goods.get("goodId")+" "+goods.get("goodName")+" "
                    +goods.get("price")+" "+goods.get("pubDate")+" "+goods.get("address"));
            out.print("</p>");
        }
    %>


</body>
</html>

2.学生信息查询 0801 KQC

2.1要求:

**学生表:学号,姓名,性别,生日,身高。使用jstl+servle+dao实现查询 **

2.2 实现效果:

在这里插入图片描述

2.3 思路:

参考思路:
在这里插入图片描述

2.4实现代码目录结构:

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

2.6 代码部分:

创建数据库:

#创建数据库
create database 70730_db
default character set utf8mb4 #设置字符集
default collate utf8mb4_general_ci #设置排序规则 

创建表:

create table student
(
	stuId int primary key auto_increment,
	stuName varchar(20),
	stuSex varchar(2),
	stuBirthday date,
	stuTall int
);

select * from student;

insert into student
(stuName,stuSex,stuBirthday,stuTall)
values
('张三','男','1998-09-09',170),
('李四','女','2008-08-08',180);

BaseDAO:

package util;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BaseDAO {

	//四大金刚
	//驱动类
	private static final String DRIVER="com.mysql.cj.jdbc.Driver";
	//连接地址
	private static final String URL="jdbc:mysql://localhost:3306/70730_db?useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai";
	//用户名
	private static final String USER="root";
	//密码
	private static final String PASSWORD="123456";

	//获取连接
	public static Connection getConnection(){

		Connection con = null;

		try{
			//加载驱动类
			Class.forName(DRIVER);
			//获取连接
			con = DriverManager.getConnection(URL,USER,PASSWORD);
			
		}catch(Exception ex){
			ex.printStackTrace();
		}

		return con;
	}

	//关闭数据库对象
	public static void closeAll(Connection con,Statement st,ResultSet rs){
		
		if(rs!=null){
			try{
				rs.close();
			}catch(Exception ex){
				ex.printStackTrace();
			}
			
		}

		if(st!=null){

			try{
				st.close();
			}catch(Exception ex){
				ex.printStackTrace();
			}
			
		}

		if(con!=null){
			try{
				con.close();
			}catch(Exception ex){
				ex.printStackTrace();
			}
			
		}

	}


	//通用设置参数方法
	public static void setParams(PreparedStatement pst,Object[] params){

		if(params==null){
			return;
		}

		for(int i=0;i<params.length;i++){
			try{
				pst.setObject(i+1,params[i]);
			}catch(Exception ex){
				ex.printStackTrace();
			}
		}
	}


	//通用增删改
	public static int executeUpdate(String sql,Object[] params){

		Connection con = null;
		PreparedStatement pst = null;
		
		int res = -1;
		
		try{

			//获取连接
			con = getConnection();
			//创建预编译命令执行对象
			pst = con.prepareStatement(sql);
			//设置参数
			setParams(pst,params);
			//执行
			res = pst.executeUpdate();

		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			closeAll(con,pst,null);
		}
		
		return res;
	}


	//通用查询
	public static List<Map<String,Object>> executeQuery(String sql,Object[] params) {

		List<Map<String,Object>> rows = new ArrayList<>();

		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs = null;

		try{
			//获取连接	
			con = getConnection();			
			//获取命令对象
			pst = con.prepareStatement(sql);
			//设置参数
			setParams(pst,params);
			//执行查询
			rs = pst.executeQuery();

			//通过rs获取结果集的结构信息
			ResultSetMetaData rsmd =  rs.getMetaData();
			//获取结果集的列数
			int colCount = rsmd.getColumnCount();

			//遍历查询结果,并封装到List<Map>中
			while(rs.next()){
				//用Map存储当前行的各个列数据
				Map<String,Object> map = new HashMap<>();
				//循环获取每一列的信息
				for(int i=1;i<=colCount;i++){
					//获取列名(使用rsmd)
					String colName = rsmd.getColumnLabel(i);
					//获取列值(使用rs)
					Object colVal = rs.getObject(i);
					//将当前列存储到map中
					map.put(colName,colVal);								
				}
				
				//将遍历的当前行的数据存储到List中
				rows.add(map);
							
			}


		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			closeAll(con,pst,rs);
		}
		
		return rows;

	}

}

Student:

package entity;

import java.net.Inet4Address;
import java.util.Date;

public class Student {
    private Integer stuId;
    private String stuName;
    private String stuSex;
    private Date stuBirthday;
    private Integer stuTall;

    public Student() {
    }

    public Student(Integer stuId, String stuName, String stuSex, Date stuBirthday, Integer stuTall) {
        this.stuId = stuId;
        this.stuName = stuName;
        this.stuSex = stuSex;
        this.stuBirthday = stuBirthday;
        this.stuTall = stuTall;
    }

    public Integer getStuId() {
        return stuId;
    }

    public void setStuId(Integer stuId) {
        this.stuId = stuId;
    }

    public String getStuName() {
        return stuName;
    }

    public void setStuName(String stuName) {
        this.stuName = stuName;
    }

    public String getStuSex() {
        return stuSex;
    }

    public void setStuSex(String stuSex) {
        this.stuSex = stuSex;
    }

    public Date getStuBirthday() {
        return stuBirthday;
    }

    public void setStuBirthday(Date stuBirthday) {
        this.stuBirthday = stuBirthday;
    }

    public Integer getStuTall() {
        return stuTall;
    }

    public void setStuTall(Integer stuTall) {
        this.stuTall = stuTall;
    }

    @Override
    public String toString() {
        return "Student{" +
                "stuId=" + stuId +
                ", stuName='" + stuName + '\'' +
                ", stuSex='" + stuSex + '\'' +
                ", stuBirthday=" + stuBirthday +
                ", stuTall=" + stuTall +
                '}';
    }
}

IStudentsBAO:

package dao;

import java.util.List;
import java.util.Map;

public interface IStudentsBAO {
    List<Map<String,Object>> listAll();

}

StudentsBAOImpl :

package dao.impl;

import dao.IStudentsBAO;
import util.BaseDAO;

import java.util.List;
import java.util.Map;

public class StudentsBAOImpl implements IStudentsBAO {
    @Override
    public List<Map<String, Object>> listAll() {
        String sql="select stuId,stuName,stuSex,stuBirthday,stuTall from student";
        return BaseDAO.executeQuery(sql,null);
    }
}

IStudentsService:

package service;

import java.util.List;
import java.util.Map;

public interface IStudentsService {
    List<Map<String,Object>> listAll();
}

StudentsServiceImpl :

package service.impl;

import dao.IStudentsBAO;
import dao.impl.StudentsBAOImpl;
import service.IStudentsService;
import util.BaseDAO;

import javax.servlet.annotation.WebServlet;
import java.util.List;
import java.util.Map;

public class StudentsServiceImpl implements IStudentsService {
    IStudentsBAO studentsBAO=new StudentsBAOImpl();

    @Override
    public List<Map<String, Object>> listAll() {
        return studentsBAO.listAll();
    }
}

TestServlet:

package servlet;

import service.IStudentsService;
import service.impl.StudentsServiceImpl;

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;
import java.util.List;
import java.util.Map;

@WebServlet(urlPatterns = "/TestServlet/*")
public class TestServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri=req.getRequestURI();
        String process=uri.substring(uri.lastIndexOf("/")+1);
        System.out.println("截取后: "+process);
        req.setCharacterEncoding("utf-8");

        switch (process){
            case "query":
                this.query(req,resp);
                break;
            case "toAdd":
                this.toAdd(req,resp);
                break;
            case "add":
                this.add(req,resp);
                break;
            case "toUpdate":
                this.toUpdate(req,resp);
                break;
            case "update":
                this.update(req,resp);
                break;
            case "delete":
                this.delete(req,resp);
                break;
        }
    }

    IStudentsService studentsService=new StudentsServiceImpl();

    private void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Map<String, Object>> studentList=studentsService.listAll();
        req.setAttribute("studentList",studentList);
        System.out.println("+++++++++");
        req.getRequestDispatcher("/studentList.jsp").forward(req,resp);
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) {
    }

    private void toUpdate(HttpServletRequest req, HttpServletResponse resp) {
    }

    private void toAdd(HttpServletRequest req, HttpServletResponse resp) {
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) {
    }



    private void delete(HttpServletRequest req, HttpServletResponse resp) {
    }


}

studentList.jsp:

<%@ page import="java.util.Map" %>
<%@ page import="java.util.List" %><%--
  Created by IntelliJ IDEA.
  User: 33154
  Date: 2022/8/1
  Time: 16:11
  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>
    <title>Title</title>
    <%=request.getAttribute("studentList")%>>
</head>
<body>
     <% List<Map<String, Object>> stuList=(List<Map<String, Object>>) request.getAttribute("studentList");
        for(Map<String,Object> stu:stuList){
            out.print("<p>");
            out.print(stu.get("stuId")+" "+stu.get("stuName")+" "+stu.get("stuBirthday")+" "+stu.get("stuTall"));
            out.print("</p>");
        }
     %>

    ${studentList}
     <table border="1">
        <tr>
            <th>编号</th>
            <th>姓名</th>
            <th>性别</th>
            <th>生日</th>
            <th>身高</th>

        </tr>
         <c:forEach items="${studentList}" var="stu" >
             <tr>
                 <td>${stu.stuId}</td>
                 <td>${stu.stuName}</td>
                 <td>${stu.stuSex}</td>
                 <td>${stu.stuBirthday}</td>
                 <td>${stu.stuTall}</td>

             </tr>
         </c:forEach>

     </table>

</body>
</html>

// A code block
var foo = 'bar';
// A code block
var foo = 'bar';

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/118081.html

(0)
seven_的头像seven_bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!