首页
归档
分类
标签
更多
留言板
说说
关于
Search
1
饥荒联机版控制台代码大全
1,024 阅读
2
编译安装带 Brotli 压缩的 Nginx
930 阅读
3
Obsidian多端快速同步插件
901 阅读
4
树莓派+EC20模块实现连接蜂窝网和短信收发
887 阅读
5
EC20通过gammu接收短信再转发优化
865 阅读
软件
CSS
Python
MySql
Java
typecho自定义
Vue
学习笔记
Linux
Shell脚本
Nginx
树莓派
邮件
拍照
热点
ec20
云盘
系统烧录
好玩
饥荒
硬件
工具
笔记
随心记
登录
Search
标签搜索
树莓派
Linux
Java
CSS
饥荒
小妙招
个人热点
nextcloud
云盘
DHT11
学习笔记
树莓派拍照
Nginx
MySql
ESP
娱乐
ec20模块
文件共享
git
图床
Mango
累计撰写
51
篇文章
累计收到
7
条评论
首页
栏目
软件
CSS
Python
MySql
Java
typecho自定义
Vue
学习笔记
Linux
Shell脚本
Nginx
树莓派
邮件
拍照
热点
ec20
云盘
系统烧录
好玩
饥荒
硬件
工具
笔记
随心记
页面
归档
分类
标签
留言板
说说
关于
搜索到
4
篇与
的结果
2024-12-24
Java使用SXSSFWorkbook导出Excel工具类
列 1col2 (列2)col3 前引在项目中经常有导出Excel的需求,为了方便就封装了一个导出Excel到前端的工具类,使用下来还比较好用使用JDK版本:1.8spring boot版本:2.6.15前端请求:axiosJava代码Excel所需Maven依赖 <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.0.1</version> </dependency>完整代码如下:public class excelUtils { public static CellStyle headStyle(Workbook workbook) { // 创建单元格样式 CellStyle headerStyle = workbook.createCellStyle(); // 设置字体样式 Font headerFont = workbook.createFont(); headerFont.setBold(true); // 加粗 headerFont.setFontHeightInPoints((short) 12); // 字体大小 headerStyle.setFont(headerFont); // 可选:设置其他样式属性 headerStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中 headerStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中 return headerStyle; } public static CellStyle tableStyle(Workbook workbook) { CellStyle tableStyle = workbook.createCellStyle(); tableStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中 tableStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中 return tableStyle; } /** * @author Mango * * 获取对象的字段值 * @param object 对象 * @param key 字段名 * @return 字段值 */ public static String getFieldString(Object object, String key) { if(object instanceof Map){ return String.valueOf(((Map<?, ?>) object).get(key)); } Field field = null; String value = ""; try { field = object.getClass().getDeclaredField(key); field.setAccessible(true); String orgStr = String.valueOf(field.get(object)); if (orgStr != null) { value = orgStr; // 处理数组类型 if (orgStr.startsWith("[") && orgStr.endsWith("]")) { value = orgStr .replace("[", "") .replace("]", "") .replace("\"", ""); } } } catch (NoSuchFieldException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } return value; } /** * @author Mango * 导出Excel * @param response HttpServletResponse * @param srcList 数据源 * @param keys 数据源对应字段列表 * @param titles 表头 * @param excelName 文件名 */ public static void exportExcel(HttpServletResponse response, List<?> srcList, List<String> keys, List<String> titles, String excelName) { // 创建workbook // 使用 SXSSFWorkbook 比 XSSFWorkbook 内存占用少 SXSSFWorkbook workbook = new SXSSFWorkbook(); // 根据workbook创建sheet Sheet sheet = workbook.createSheet(excelName); //设置表头 Row titleRoe = sheet.createRow(0); // 设置表头样式 CellStyle headStyle = headStyle(workbook); // 向单元格中添加表头数据 for (int i = 0; i < titles.size(); i++) { Cell cell = titleRoe.createCell(i); cell.setCellValue(titles.get(i)); cell.setCellStyle(headStyle); } // 定义数据样式 CellStyle tableStyle = tableStyle(workbook); // 处理表格数据 for (int i = 0; i < srcList.size(); i++) { // 获取一组数据 Object object = srcList.get(i); // 生成行 Row rowData = sheet.createRow(i + 1); // 设置行高 rowData.setHeight((short) 400); // 向每一行中的单元格添加数据 // keys 为对象字段列表 for (int j = 0; j < keys.size(); j++) { String key = keys.get(j); Cell cell = rowData.createCell(j); cell.setCellStyle(tableStyle); String value = getFieldString(object, key); cell.setCellValue(value); } // 每100行就写一次磁盘,减少内存消耗 if (i % 100 == 0) { try { ((SXSSFSheet) sheet).flushRows(100); // 将缓存中的数据写入磁盘 } catch (IOException e) { throw new RuntimeException(e); } } } // 获取当前时间作为文件名 LocalDateTime localDateTime = LocalDateTime.now(); String fileName = excelName + localDateTime.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + ".xlsx"; // 设置响应头 try { response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); } catch (UnsupportedEncodingException e) { // 发生异常不处理中文文件名 response.setHeader("Content-Disposition", "attachment;filename=" + fileName); throw new RuntimeException(e); } response.setContentType("application/vnd.ms-excel;charset=utf-8"); response.setHeader("Accept-Ranges", "bytes"); // 返回数据 返回进度条 try (ByteArrayOutputStream fileOutputStream = new ByteArrayOutputStream(); ServletOutputStream out = response.getOutputStream()) { // 这里假设 workbook 是生成的 Excel 文件对象 workbook.write(fileOutputStream); // 获取文件的总大小,并设置响应头 byte[] fileBytes = fileOutputStream.toByteArray(); response.setHeader("Content-Length", String.valueOf(fileBytes.length)); // 分块传输文件内容 int chunkSize = 256; // 每次写入数据字节 int totalSize = fileBytes.length; int currentPosition = 0; while (currentPosition < totalSize) { int remaining = totalSize - currentPosition; int chunk = Math.min(chunkSize, remaining); // 写入一块数据 out.write(fileBytes, currentPosition, chunk); out.flush(); // 刷新输出流,确保数据传送给客户端 // 更新当前下载位置 currentPosition += chunk; } out.close(); workbook.close(); // 关闭工作簿 } catch (IOException e) { // 处理异常 response.reset(); response.setContentType("application/json"); response.setCharacterEncoding("utf-8"); Map<String, String> map = new HashMap<>(); map.put("message", "下载文件失败: " + e.getMessage()); try { response.getWriter().println(JSON.toJSONString(map)); } catch (IOException ee) { ee.printStackTrace(); } e.printStackTrace(); } } }前端请求示例请求接口export const outExcel = async ( data: any, downloadProgress: Function, ) => { return await request({ url: "/test/outExcel", method: "post", data, responseType: "blob", onDownloadProgress: (event: any) => { downloadProgress(event); }, }); }注:这里的代码是已经封装过的统一封装的axiosresponseType: “blob” 指定文件为二进制onDownloadProgress利用回调函数返回下载进度下载示例const exportExcel = async () => { isProcessing.value = true; let response = null; try { response = await props.downloadMethod(props.searchForm, (event: any) => { progress.value = (event.loaded / event.total) * 100; if (progress.value > 0) { isProcessing.value = false; } }); } catch (e: any) { isProcessing.value = false; //出错时结束处理状态 isError.value = true; //下载失败 } if (response == null) return; // 没有返回数据 if (!response.status) { isError.value = true; //接口返回错误设置为下载失败 } const fileName = "教师参与情况" + formatDate(new Date(), "yy-MM-dd hh:mm:ss") + ".xlsx"; const blob = new Blob([response.data], { type: "application/vnd.ms-excel" }); // 创建一个链接来下载 Blob 对象 const downloadLink = document.createElement("a"); downloadLink.href = URL.createObjectURL(blob); downloadLink.download = decodeURI(fileName); downloadLink.style.display = "none"; document.body.appendChild(downloadLink); // 触发点击事件以下载文件 downloadLink.click(); // 清理创建的链接对象 document.body.removeChild(downloadLink); };将props.downloadMethod替换为下载接口props.searchFormt替换为筛选数据
2024年12月24日
779 阅读
2 评论
0 点赞
2023-04-30
SSM开发环境搭建(小白自用)
前言将SSM作为后端的的一个项目即将完工,在开发过程中踩了很多坑,与此同时也学习到了新知识,有了不小收获。在遇到麻烦和解决麻烦的路上,受到了很多分享教程博主的帮助。为了将帮助延续下去,我也将自己SSM环境配置的过程做了简单的纪录、分享。系统软件版本Windows 10 专业版 22H2IntelliJ IDEA 2022.3.3MySQL 8.0.32Java 19.0.2Spring 6.0.6MyBatis 3.5.13Tomcat 11.0.0(软件系统版本不用完全一致,不同版本之间可能会出现一定程度的兼容性问题,可在有问题时在寻找对应版本的解决办法)新建项目及项目配置新建项目使用IDEA新建一个空的默认Maven项目,并新建Java包完善SSM项目架构。在新建controller包(表现层)、dao包(持久层)、service包(业务层)在resources下新建db(存放数据库相关配置文件)、log(存放日志相关配置文件)、spring(存放与spring与其他整合相关配置文件)修改Maven配置文件使用默认Maven配置文件,在下载包时会比较慢,我们可以修改配置文件使用国内镜像来加速下载IDEA内修改路径为File->Settings->Builde,Execution,Deployment->Maven可以修改默认的文件,也可以重新使用一个自定义的配置文件,笔者这里使用了重新新建一个配置文件的方法。其中settings.xml文件中内容如下:<?xml version="1.0" encoding="UTF-8"?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <!-- | This is the configuration file for Maven. It can be specified at two levels: | | 1. User Level. This settings.xml file provides configuration for a single user, | and is normally provided in ${user.home}/.m2/settings.xml. | | NOTE: This location can be overridden with the CLI option: | | -s /path/to/user/settings.xml | | 2. Global Level. This settings.xml file provides configuration for all Maven | users on a machine (assuming they're all using the same Maven | installation). It's normally provided in | ${maven.conf}/settings.xml. | | NOTE: This location can be overridden with the CLI option: | | -gs /path/to/global/settings.xml | | The sections in this sample file are intended to give you a running start at | getting the most out of your Maven installation. Where appropriate, the default | values (values used when the setting is not specified) are provided. | |--> <settings xmlns="http://maven.apache.org/SETTINGS/1.2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.2.0 http://maven.apache.org/xsd/settings-1.2.0.xsd"> <!-- localRepository | The path to the local repository maven will use to store artifacts. | | Default: ${user.home}/.m2/repository <localRepository>/path/to/local/repo</localRepository> --> <!-- interactiveMode | This will determine whether maven prompts you when it needs input. If set to false, | maven will use a sensible default value, perhaps based on some other setting, for | the parameter in question. | | Default: true <interactiveMode>true</interactiveMode> --> <!-- offline | Determines whether maven should attempt to connect to the network when executing a build. | This will have an effect on artifact downloads, artifact deployment, and others. | | Default: false <offline>false</offline> --> <!-- pluginGroups | This is a list of additional group identifiers that will be searched when resolving plugins by their prefix, i.e. | when invoking a command line like "mvn prefix:goal". Maven will automatically add the group identifiers | "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not already contained in the list. |--> <pluginGroups> <!-- pluginGroup | Specifies a further group identifier to use for plugin lookup. <pluginGroup>com.your.plugins</pluginGroup> --> </pluginGroups> <!-- proxies | This is a list of proxies which can be used on this machine to connect to the network. | Unless otherwise specified (by system property or command-line switch), the first proxy | specification in this list marked as active will be used. |--> <proxies> <!-- proxy | Specification for one proxy, to be used in connecting to the network. | <proxy> <id>optional</id> <active>true</active> <protocol>http</protocol> <username>proxyuser</username> <password>proxypass</password> <host>proxy.host.net</host> <port>80</port> <nonProxyHosts>local.net|some.host.com</nonProxyHosts> </proxy> --> </proxies> <!-- servers | This is a list of authentication profiles, keyed by the server-id used within the system. | Authentication profiles can be used whenever maven must make a connection to a remote server. |--> <servers> <!-- server | Specifies the authentication information to use when connecting to a particular server, identified by | a unique name within the system (referred to by the 'id' attribute below). | | NOTE: You should either specify username/password OR privateKey/passphrase, since these pairings are | used together. | <server> <id>deploymentRepo</id> <username>repouser</username> <password>repopwd</password> </server> --> <!-- Another sample, using keys to authenticate. <server> <id>siteServer</id> <privateKey>/path/to/private/key</privateKey> <passphrase>optional; leave empty if not used.</passphrase> </server> --> </servers> <!-- mirrors | This is a list of mirrors to be used in downloading artifacts from remote repositories. | | It works like this: a POM may declare a repository to use in resolving certain artifacts. | However, this repository may have problems with heavy traffic at times, so people have mirrored | it to several places. | | That repository definition will have a unique id, so we can create a mirror reference for that | repository, to be used as an alternate download site. The mirror site will be the preferred | server for that repository. |--> <mirrors> <!-- mirror | Specifies a repository mirror site to use instead of a given repository. The repository that | this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used | for inheritance and direct lookup purposes, and must be unique across the set of mirrors. | <mirror> <id>mirrorId</id> <mirrorOf>repositoryId</mirrorOf> <name>Human Readable Name for this Mirror.</name> <url>http://my.repository.com/repo/path</url> </mirror> --> <mirror> <id>aliment</id> <name>aliyah maven</name> <url>https://maven.aliyun.com/nexus/content/groups/public/</url> <mirrorOf>central</mirrorOf> </mirror> <mirror> <id>uk</id> <mirrorOf>central</mirrorOf> <name>Human Readable Name for this Mirror.</name> <url>https://uk.maven.org/maven2/</url> </mirror> <mirror> <id>CN</id> <name>OSChina Central</name> <url>https://maven.oschina.net/content/groups/public/</url> <mirrorOf>central</mirrorOf> </mirror> <mirror> <id>nexus</id> <name>internal nexus repository</name> <!-- <url>http://192.168.1.100:8081/nexus/content/groups/public/</url>--> <url>https://repo.maven.apache.org/maven2</url> <mirrorOf>central</mirrorOf> </mirror> </mirrors> <!-- profiles | This is a list of profiles which can be activated in a variety of ways, and which can modify | the build process. Profiles provided in the settings.xml are intended to provide local machine- | specific paths and repository locations which allow the build to work in the local environment. | | For example, if you have an integration testing plugin - like cactus - that needs to know where | your Tomcat instance is installed, you can provide a variable here such that the variable is | dereferenced during the build process to configure the cactus plugin. | | As noted above, profiles can be activated in a variety of ways. One way - the activeProfiles | section of this document (settings.xml) - will be discussed later. Another way essentially | relies on the detection of a system property, either matching a particular value for the property, | or merely testing its existence. Profiles can also be activated by JDK version prefix, where a | value of '1.4' might activate a profile when the build is executed on a JDK version of '1.4.2_07'. | Finally, the list of active profiles can be specified directly from the command line. | | NOTE: For profiles defined in the settings.xml, you are restricted to specifying only artifact | repositories, plugin repositories, and free-form properties to be used as configuration | variables for plugins in the POM. | |--> <profiles> <!-- profile | Specifies a set of introductions to the build process, to be activated using one or more of the | mechanisms described above. For inheritance purposes, and to activate profiles via <activatedProfiles/> | or the command line, profiles have to have an ID that is unique. | | An encouraged best practice for profile identification is to use a consistent naming convention | for profiles, such as 'env-dev', 'env-test', 'env-production', 'user-jdcasey', 'user-brett', etc. | This will make it more intuitive to understand what the set of introduced profiles is attempting | to accomplish, particularly when you only have a list of profile id's for debug. | | This profile example uses the JDK version to trigger activation, and provides a JDK-specific repo. <profile> <id>jdk-1.4</id> <activation> <jdk>1.4</jdk> </activation> <repositories> <repository> <id>jdk14</id> <name>Repository for JDK 1.4 builds</name> <url>http://www.myhost.com/maven/jdk14</url> <layout>default</layout> <snapshotPolicy>always</snapshotPolicy> </repository> </repositories> </profile> --> <!-- | Here is another profile, activated by the system property 'target-env' with a value of 'dev', | which provides a specific path to the Tomcat instance. To use this, your plugin configuration | might hypothetically look like: | | ... | <plugin> | <groupId>org.myco.myplugins</groupId> | <artifactId>myplugin</artifactId> | | <configuration> | <tomcatLocation>${tomcatPath}</tomcatLocation> | </configuration> | </plugin> | ... | | NOTE: If you just wanted to inject this configuration whenever someone set 'target-env' to | anything, you could just leave off the <value/> inside the activation-property. | <profile> <id>env-dev</id> <activation> <property> <name>target-env</name> <value>dev</value> </property> </activation> <properties> <tomcatPath>/path/to/tomcat/instance</tomcatPath> </properties> </profile> --> </profiles> <!-- activeProfiles | List of profiles that are active for all builds. | <activeProfiles> <activeProfile>alwaysActiveProfile</activeProfile> <activeProfile>anotherAlwaysActiveProfile</activeProfile> </activeProfiles> --> </settings> 只是修改了mirrors部分,使用了阿里云镜像加速国内下载速度。设置项目所需包修改pom.xml文件,以下内容为本人使用成功的配置文件内容,仅作参考<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.mango</groupId> <artifactId>ssmTest</artifactId> <version>1.0-SNAPSHOT</version> <properties> <!-- 工程编译版本,一般与安装的JDK版本一致--> <maven.compiler.source>19</maven.compiler.source> <maven.compiler.target>19</maven.compiler.target> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <!--统一的版本管理--> <spring.version>6.0.6</spring.version> <slf4j.version>2.0.5</slf4j.version> <mysql.version>8.0.32</mysql.version> <mybatis.version>3.5.13</mybatis.version> </properties> <dependencies> <!-- spring --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.19</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <!--Junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>compile</scope> </dependency> <!--数据库驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!-- 数据库连接池 --> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> <type>jar</type> <scope>compile</scope> </dependency> <!--Servlet - JSP --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- @Resource注解依赖包--> <dependency> <groupId>javax.annotation</groupId> <artifactId>javax.annotation-api</artifactId> <version>1.3.2</version> </dependency> <!--Mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- Spring整合ORM --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>6.0.6</version> </dependency> <!-- spring整合mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>3.0.1</version> </dependency> <!-- log --> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j</artifactId> <version>2.20.0</version> <type>pom</type> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!--加入对json转换--> <!-- JSON: jackson --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.14.2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.14.2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.14.2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.jr</groupId> <artifactId>jackson-jr-all</artifactId> <version>2.14.2</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>2.0.25</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.16</version> </dependency> <!-- http请求--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> <version>3.0.4</version> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> </resource> </resources> </build> </project>添加Web模块File->Project Structure->Modules如图操作添加后内容保持默认,确认后即可导入web模块安装Tomcat可以参考以下教程{% link Wxy1122.,[IntelliJ IDEA中配置Tomcat(超详细)_idea配置tomcat_Wxy1122.的博客-CSDN博客,https://blog.csdn.net/Wxy971122/article/details/123508532 %}SSM配置文件jdbc配置文件在resources->db下新建jdbc.properties文件,其中内容参考如下jdbc.driver = com.mysql.cj.jdbc.Driver jdbc.url = jdbc:mysql://localhost:3306/xxx?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT jdbc.username = root jdbc.password = root由于使用的MySQL版本为8,所以驱动才使用为com.mysql.cj.jdbc.Driver,由于没有在MySQL中做过测试,不能确定在MySQL 5中也能正常使用jdbc.url中的xxx用自己数据库名称替换新建mybatis控制文件在db下新建mybatis.xml文件由于大部分和MyBatis相关配置文件都会和Spring的配置文件整合到一起,这里的Mybatis控制文件只起到辅助作用,参考代码如下:<?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> <!-- 开启延迟加载 该项默认为false,即所有关联属性都会在初始化时加载 true表示延迟按需加载 --> <settings> <setting name="lazyLoadingEnabled" value="true"/> <!-- 开启二级缓存 --> <setting name="cacheEnabled" value="true"/> </settings> </configuration> Spring整合MyBatis在resources->spring下新建applicationContext.xml文件,将Spring和MyBatis配置文件整合在一起,参考代码如下:<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 开启注解扫描,要扫描的是service和dao层的注解,要忽略web层注解,因为web层让SpringMVC框架去管理 --> <context:component-scan base-package="com.mango"> <!-- 配置要忽略的注解 --> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 引入配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:db/jdbc.properties" /> </bean> <!--Spring整合Mybatisl框架--> <!-- 配置C3P0的连接池对象 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!-- 配置SessionFactory的Bean --> <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 注入数据源 --> <property name="dataSource" ref="dataSource"/> <!-- 指定MyBatis配置文件的位置 --> <property name="configLocation" value="classpath:db/mybatis.xml"/> <!-- 给实体类起别名 --> <property name="typeAliasesPackage" value="com.mango.entity"/> </bean> <!-- 配置mapper接口的扫描器,将Mapper接口的实现类自动注入到IoC容器中 实现类Bean的名称默认为接口类名的首字母小写 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- basePackage属性指定自动扫描mapper接口所在的包 --> <property name="basePackage" value="com.mango.dao"/> </bean> <!--SqlMapConfig.xml和jdbcConfig.properties可以删除了--> <!--配置Spring框架声明式事务管理--> <!--配置事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 配置事务的通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="find*" propagation="SUPPORTS" read-only="true"/> <tx:method name="*" isolation="DEFAULT"/> </tx:attributes> </tx:advice> <!-- 配置AOP增强 --> <aop:config> <!-- <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.mango.service.impl.*.*(..))"/>--> <!-- 配置切入点表达式 --> <aop:pointcut expression="execution(* com.mango.service.impl.*.*(..))" id="pt1"/> <!-- 建立通知和切入点表达式的关系 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/> </aop:config> </beans> Springmvc配置文件在resources->spring下新建springmvc.xml文件<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 配置@controller扫描包 --> <context:component-scan base-package="com.mango.controller" /> <!--使用Annotation自动注册Bean,扫描@Controller和@ControllerAdvice--> <context:component-scan base-package="com.mango" use-default-filters="false"> <!-- base-package 如果多个,用“,”分隔 --> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> <!--控制器增强,使一个Controller成为全局的异常处理类,类中用@ExceptionHandler方法注解的方法可以处理所有Controller发生的异常--> <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" /> </context:component-scan> <!-- 配置注解驱动,相当于同时使用最新处理器映射跟处理器适配器,对json数据响应提供支持 --> <mvc:annotation-driven /> <!-- 输出对象转JSON支持 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <value>text/plain;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> </bean> </list> </property> </bean> <!-- 配置视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> </beans> web模块控制文件编辑web->WEB-INF->web.xml文件,内容如下<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <!-- 配置前端控制器 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 指定配置文件位置和名称 如果不设置,默认找/WEB-INF/<servlet-name>-servlet.xml --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 配置 spring 提供的监听器,用于启动服务时加载容器 。 该监听器只能加载 WEB-INF 目录中名称为 applicationContext.xml 的配置文件 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 手动指定 spring 配置文件位置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/applicationContext.xml</param-value> </context-param> </web-app> 日志配置在resources->log下新建log4j.propertieslog4j.rootLogger=DEBUG, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p %d %C: %m%n log4j.logger.java.sql.ResultSet=INFO log4j.logger.org.apache=INFO log4j.logger.java.sql.Connection=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG测试在test->java下更具需求新建测试类新建测试数据库test,其中有表student(id,name,age)在之前新建的entity包中新建Student的实现类(getter、setter方法以省略)package com.mango.entity; public class Student { private int id; private String name; private String age; @Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + '\'' + ", age='" + age + '\'' + '}'; } } 对Spring和MyBatis整合配置测试在包dao中新建学生接口StudentDao.javapackage com.mango.dao; import com.mango.entity.Student; import java.util.List; public interface StudentDao { public List<Student> findAll(); }在同样位置新建同名mapper文件StudentDao.xml<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--命名空间为StudentDao接口--> <mapper namespace="com.mango.dao.StudentDao"> <!-- id为接口中的方法名--> <select id="findAll">SELECT * FROM Student</select> </mapper>在service包中新建service接口和实现类学生业务层接口StudentService.javapackage com.mango.service; import com.mango.entity.Student; import org.springframework.stereotype.Service; import java.util.List; //千万不要忘记添加Service注解 @Service public interface StudentService { public List<Student> findAll(); }实现类StudentServiceImpl.javapackage com.mango.service.impl; import com.mango.dao.StudentDao; import com.mango.entity.Student; import com.mango.service.StudentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class StudentServiceImpl implements StudentService { @Autowired private StudentDao studentDao; public List<Student> findAll(){ return studentDao.findAll(); } }在test中新建Spring和MyBatis整合测试代码SpringMyBatis.javaimport com.mango.entity.Student; import com.mango.service.StudentService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations="classpath:spring/applicationContext.xml") public class SpringMyBatis { @Autowired private StudentService studentService; @Test public void test(){ List<Student> studentList=studentService.findAll(); for (Student student:studentList){ System.out.println(student.toString()); } } } 测试成功Spring整合SpringMVC测试在Controller包中新建StudentController.javapackage com.mango.controller; import com.mango.service.StudentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; //千万不要忘记@Controller @Controller @RequestMapping public class StudentController { @Autowired private StudentService studentService; @RequestMapping(value = "/test" ,method = RequestMethod.GET) @ResponseBody public Object test(){ return studentService.findAll(); } } 将项目打包File->Project Structure->Artifacts如果有出现部分包不完全可以下图操作修改Tomcat配置(已正确安装Tomcat的情况下)启动Tomcat后在浏览器中访问localhost:8080/test 不报错有返回值,说明Spring整合SpringMVC配置成功。
2023年04月30日
474 阅读
0 评论
0 点赞
2022-10-12
Java改变控制台输出文字样式
Java在控制台上的输出字体样式其实是可以自己定义的代码如果结尾处没有加 \033[m 这次输出后的全部输出都会变成相同样式 System.out.println("\033[30m"+"Hello World 设置m为:30"+"\033[m"); System.out.println("\033[31m"+"Hello World 设置m为:31"+"\033[m"); System.out.println("\033[32m"+"Hello World 设置m为:32"+"\033[m"); System.out.println("\033[33m"+"Hello World 设置m为:33"+"\033[m"); System.out.println("\033[34m"+"Hello World 设置m为:34"+"\033[m"); System.out.println("\033[35m"+"Hello World 设置m为:35"+"\033[m"); System.out.println("\033[36m"+"Hello World 设置m为:36"+"\033[m"); System.out.println("\033[37m"+"Hello World 设置m为:37"+"\033[m"); System.out.println("\033[38m"+"Hello World 设置m为:38"+"\033[m"); System.out.println("\033[39m"+"Hello World 设置m为:39"+"\033[m"); System.out.println("\033[40m"+"Hello World 设置m为:40"+"\033[m"); System.out.println("\033[41m"+"Hello World 设置m为:41"+"\033[m"); System.out.println("\033[42m"+"Hello World 设置m为:42"+"\033[m"); System.out.println("\033[43m"+"Hello World 设置m为:43"+"\033[m"); System.out.println("\033[44m"+"Hello World 设置m为:44"+"\033[m"); System.out.println("\033[45m"+"Hello World 设置m为:45"+"\033[m"); System.out.println("\033[46m"+"Hello World 设置m为:46"+"\033[m"); System.out.println("\033[47m"+"Hello World 设置m为:47"+"\033[m");样式其实,并不用特别的去记什么数字代表什么样式,用一个for循环输出看看就可以知道了for(int i=0;i<99;i++) { System.out.println("\033["+i+"m" + "Hello World 设置m为:"+i+ "\033[m"); }
2022年10月12日
348 阅读
0 评论
0 点赞
2022-04-03
Java面向对象
Java是一种相对比较成熟的面向对象编程语言。面向对象是一种较为符合人类思维习惯的编程思想。在Java中一切皆可有对象,我们把具有相同性质、特点的事物抽象成一个类,而每一个具有这些性质、特点的事物就是这个类的一个对象。面向对象与面向过程面向过程:面向过程就是分析出解决问题的一个个步骤,在程序中的提现就是写好的一个个执行不同目的的函数,在解决问题的时候,就再一个一个的调用这些步骤(函数)。就比如说洗衣服这件事,在面向过程的时候,就会被拆分成:放入衣服、加入洗衣液、加入适量水、启动洗衣、排水、甩干、晾衣服。这一些列的过程,最终达到洗衣服的目的。面向对象:面向对象是把构成问题事务分解成各个对象,建立对象的目的不是为了完成一个步骤,而是为了描叙某个事物在整个解决问题的步骤中的行为。再以洗衣服这件事为例,在面向对象的时候洗衣粉主要就被分为了两类对象,第一类对象——人,主要有放入衣服、加入水、晾衣服等属性;第二类对象——洗衣机,主要有洗衣服、甩干衣服等属性。面向对象主要是划分了问题而不是步骤。面向对象与面向过程的优缺点面向过程:优点:流程化使得编程任务明确,在开发之前基本考虑了实现方式和最终结果,具体步骤清楚,便于节点分析。效率高,面向过程强调代码的短小精悍,善于结合数据结构来开发高效率的程序。比如单片机、嵌入式开发、Linux/Unix等一般采用面向过程开发,性能是最重要的因素。缺点:代码重用性低,扩展能力差,后期维护难度比较大。面向对象优点:结构清晰,程序是模块化和结构化,更加符合人类的思维方式;易扩展,代码重用率高,可继承,可覆盖,可以设计出低耦合的系统;由于面向对象有封装、继承、多态性的特性,可以设计出低耦合的系统,使系统更加灵活、更加易于维护缺点:开销大,当要修改对象内部时,对象的属性不允许外部直接存取,所以要增加许多没有其他意义、只负责读或写的行为。这会为编程工作增加负担,增加运行开销,并且使程序显得臃肿。性能低,由于面向更高的逻辑抽象层,使得面向对象在实现的时候,不得不做出性能上面的牺牲,计算时间和空间存储大小都开销很大。面向对象的基本特性封装:是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法。封装可以被认为是一个保护屏障,防止该类的代码和数据被外部类定义的代码随机访问。良好的封装能够使程序更高效安全。继承:继承是Java程序设计中的一项核心技术。继承的基本思想是使用已经存在类中的属性和方法去创建新的类,在新类中可以添加心得属性和方法,让新的类能够适应心得情况而不用重写已经存在的属性方法。多态:多态性是面向对象编程的又一个重要特征,它是指在父类中定义的属性和方法被子类继承之后,可以具有不同的数据类型或表现出不同的行为,这使得同一个属性或方法在父类及其各个子类中具有不同的含义。对面向对象来说,多态分为编译时多态和运行时多态。其中编译时多态是静态的,主要是指方法的重载,它是根据参数列表的不同来区分不同的方法。通过编译之后会变成两个不同的方法,在运行时谈不上多态。而运行时多态是动态的,它是通过动态绑定来实现的,也就是大家通常所说的多态性。(解释来自C语言中文网](http://c.biancheng.net/view/1001.html)))面向对象的五大基本原则单一职责原则(Single Responsibility Principle)没一个类应该专注于做一件事。指类的功能要单一,不要包罗万象;像人一样不要一心二用。开放封闭原则OCP(Open-Close Principle)一个模块在扩展性方面应该是开放的而在更改性方面应该是封闭的里氏替换原则(Liskov Substitution Principle)子类应当可以替换父类并出现在父类能够出现的任何地方依赖倒置原则(Dependence Inversion Principle)具体依赖抽象,上层依赖下层。接口隔离原则(Interface Segregation Principle)模块间要通过抽象接口隔离开,而不是通过具体的类强耦合起来
2022年04月03日
334 阅读
0 评论
0 点赞