首页 > 数据库 >案例_分析&环境搭建与案例_实现_查询数据库

案例_分析&环境搭建与案例_实现_查询数据库

时间:2023-02-25 17:35:43浏览次数:38  
标签:itcast cn List 案例 json 查询数据库 import public 搭建

案例_分析&环境搭建

          案例需求:

            1. 提供index.html页面,页面中有一个省份 下拉列表
            2. 当 页面加载完成后 发送ajax请求,加载所有省份

 

 

案例_实现_查询数据库

package cn.itcast.dao.impl;

import cn.itcast.dao.ProvinceDao;
import cn.itcast.domain.Province;
import cn.itcast.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class ProvinceDaoImpl implements ProvinceDao {

    //1.声明成员变量 jdbctemplement
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    @Override
    public List<Province> findAll() {
        //1.定义sql
        String sql = "select * from province ";
        //2.执行sql
        List<Province> list = template.query(sql, new BeanPropertyRowMapper<Province>(Province.class));
        return list;
    }
}

 

 

package cn.itcast.dao;

import cn.itcast.domain.Province;

import java.util.List;

public interface ProvinceDao {

    public List<Province> findAll();
}

 

package cn.itcast.domain;

public class Province {

    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

 

package cn.itcast.service.impl;

import cn.itcast.dao.ProvinceDao;
import cn.itcast.dao.impl.ProvinceDaoImpl;
import cn.itcast.domain.Province;
import cn.itcast.jedis.util.JedisPoolUtils;
import cn.itcast.service.ProvinceService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import redis.clients.jedis.Jedis;

import java.util.List;

public class ProvinceServiceImpl implements ProvinceService {
    //声明dao
    private ProvinceDao dao = new ProvinceDaoImpl();

    @Override
    public List<Province> findAll() {
        return dao.findAll();
    }

    /**
        使用redis缓存
     */

    @Override
    public String findAllJson() {
        //1.先从redis中查询数据
        //1.1获取redis客户端连接
        Jedis jedis = JedisPoolUtils.getJedis();
        String province_json = jedis.get("province");

        //2判断 province_json 数据是否为null
        if(province_json == null || province_json.length() == 0){
            //redis中没有数据
            System.out.println("redis中没数据,查询数据库...");
            //2.1从数据中查询
            List<Province> ps = dao.findAll();
            //2.2将list序列化为json
            ObjectMapper mapper = new ObjectMapper();
            try {
                province_json = mapper.writeValueAsString(ps);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }

            //2.3 将json数据存入redis
            jedis.set("province",province_json);
            //归还连接
            jedis.close();

        }else{
            System.out.println("redis中有数据,查询缓存...");
        }


        return province_json;
    }
}

 

package cn.itcast.service;

import cn.itcast.domain.Province;

import java.util.List;

public interface ProvinceService {

    public List<Province> findAll();

    public String findAllJson();
}

 

package cn.itcast.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * JDBC工具类 使用Durid连接池
 */
public class JDBCUtils {

    private static DataSource ds ;

    static {

        try {
            //1.加载配置文件
            Properties pro = new Properties();
            //使用ClassLoader加载配置文件,获取字节输入流
            InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            pro.load(is);

            //2.初始化连接池对象
            ds = DruidDataSourceFactory.createDataSource(pro);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接池对象
     */
    public static DataSource getDataSource(){
        return ds;
    }


    /**
     * 获取连接Connection对象
     */
    public static Connection getConnection() throws SQLException {
        return  ds.getConnection();
    }
}

 

package cn.itcast.web.servlet;

import cn.itcast.service.ProvinceService;
import cn.itcast.service.impl.ProvinceServiceImpl;

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("/provinceServlet")
public class ProvinceServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       /* //1.调用service查询
        ProvinceService service = new ProvinceServiceImpl();
        List<Province> list = service.findAll();
        //2.序列化list为json
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(list);*/

        //1.调用service查询
        ProvinceService service = new ProvinceServiceImpl();
        String json = service.findAllJson();


        System.out.println(json);
        //3.响应结果
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(json);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

 

 

标签:itcast,cn,List,案例,json,查询数据库,import,public,搭建
From: https://www.cnblogs.com/x3449/p/17154812.html

相关文章

  • [专题总结]Gridea快速免费搭建个人博客
    介绍或许你很想把你所知道的问题写出来,或许你文思泉涌,想给大家分享。我相信,你一定能写好博客,只要坚持,就可以了。或许大家会不理解,为什么不用大平台的博客呢?或许你稍微了......
  • K8S污点容忍案例
    [root@lecode-pre74~]#setenforce0setenforce:SELinuxisdisabled[root@lecode-pre74~]#sed-i's/SELINUX=enforcing/SELINUX=disabled/'/etc/selinux/config[......
  • shell脚本多重判断案例
    cpu=$1mem=$2if[$cpu==4];thenvcores=4if["$mem"=="15G"];thenmb=12288elif["$mem"=="7.3G"];thenmb=6200fielif[$cpu......
  • shell脚本修改配置文件案例
    [root@bigdata01~/install]#vimchange-yarn-site.sh#!bin/bash#此脚本对大数据集群所有节点的yarn-site.xml文件根据集群配置自动更改对应配置。HOST_LIST=`grep'bi......
  • 《黑马旅游网》综合案例八 分页数据展示-代码展示
    RouteDaopackagecn.itcast.travel.dao;importcn.itcast.travel.domain.Route;importjava.util.List;publicinterfaceRouteDao{/***根据id查询......
  • ubuntu20.04 用vim+ctags+cscope搭建符合sourceinsight习惯的IDE
    1.安装vimsudoaptinstallvim按自己习惯配置vim~/.vimrcsetnocompatiblesetnufiletypeonsethistory=1000setbackground=darksyntaxonsetautoindentse......
  • 889~891 分析,环境搭建,实现查询数据库,redis缓存优化
    案例:案例需求:1.提供index.html页面,页面中有一个省份,下拉列表2.当页面加载完成后,发送ajax请求,加载说有省份   CREATEDATABASEday23;--......
  • Hadoop3 Yarn ha搭建及测试排错
    1.YarnHa原理ResourceManager记录着当前集群的资源分配和Job运行状态,YarnHa利用Zookeeper等共享存储平台来存储这些信息以达到高可用。利用Zookeeper实现ResourceManag......
  • Linux下Python搭建
    VMware14下载:https://blog.csdn.net/qq_31362105/article/details/80706096ctrol+d#退出python执行界面rpm-qa|grepchupinxiu#列出包含厨品秀字段的软件信息“ONBO......
  • Flutter 环境搭建
    Flutter环境搭建Flutter所需环境包括:Java环境Flutter安装AndroidSDK(自带Dart)AndroidStudio安装Android证书安装模拟器配置Java安装JDK8下载Flutte......