Mkyong 中文博客翻译(十五)

原文:Mkyong

协议:CC BY-NC-SA 4.0

如何用 jQuery 检测复制、粘贴和剪切行为

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/how-to-detect-copy-paste-and-cut-behavior-with-jquery/

要检测复制、粘贴和剪切行为,只需要绑定相应的事件类型。

 $("#textA").bind('copy', function() {
    
    
    $('span').text('copy behaviour detected!')
});	
$("#textA").bind('paste', function() {
    
    
    $('span').text('paste behaviour detected!')
});	
$("#textA").bind('cut', function() {
    
    
    $('span').text('cut behaviour detected!')
}); 

如果您使用的是 jQuery 1.4x,它支持如下的多事件声明:

 $("#textA").bind({
    
    
	copy : function(){
    
    
		$('span').text('copy behaviour detected!');
	},
	paste : function(){
    
    
		$('span').text('paste behaviour detected!');
	},
	cut : function(){
    
    
		$('span').text('cut behaviour detected!');
	}
}); 

你自己试试

 <html>
<head>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>

<style type="text/css">
	span{
    
    
		color:blue;
	}
</style>

</head>
<body>
  <h1>jQuery copy, paste and cut example</h1>
  <form action="#">
  	<label>TextBox : </label>
	<input id="textA" type="text" size="50" 
          value="Copy, paste or cut message here" />
  </form>

  <span></span>

<script type="text/javascript">

$(document).ready(function() {
    
    

	$("#textA").bind({
    
    
		copy : function(){
    
    
			$('span').text('copy behaviour detected!');
		},
		paste : function(){
    
    
			$('span').text('paste behaviour detected!');
		},
		cut : function(){
    
    
			$('span').text('cut behaviour detected!');
		}
	});

});	
</script>
</body>
</html> 

http://web.archive.org/web/20190304001155if_/http://www.mkyong.com/wp-content/uploads/jQuery/jQuery-copy-paste-cut-textbox.html

Try Demojquery keyboard event外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传 (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById®;if(e=null){ var t = d.createElement(o); t.src = g; t.id = r; t.setAttribute(m, s);t.async = 1;var n=d.getElementsByTagName(o)[0];n.parentNode.insertBefore(t, n); var dt=new Date().getTime(); try{i[l]w+y;}catch(er){i[h]=dt;} } else if(typeof i[c]!‘undefined’){i[c]++} else{i[c]=1;} })(window, document, ‘InContent’, ‘script’, ‘mediaType’, ‘carambola_proxy’,‘Cbola_IC’,‘localStorage’,‘set’,‘get’,‘Item’,‘cbolaDt’,‘//web.archive.org/web/20190304001155/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0’)

jQuery–如何禁用点击后的提交按钮

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/how-to-disable-submit-button-after-clicked-with-jquery/

通常,用户喜欢在提交按钮上按几次以确保按钮被点击,这导致了双重表单提交问题。常见的解决方案是在用户点击提交按钮后禁用它。

1.启用/禁用提交按钮

1.1 要禁用一个提交按钮,你只需要给提交按钮添加一个disabled属性。

 $("#btnSubmit").attr("disabled", true); 

1.2 要启用禁用的按钮,请将disabled属性设置为 false,或者移除disabled属性。

 $('#btnSubmit').attr("disabled", false);	
or
$('#btnSubmit').removeAttr("disabled"); 

2.jQuery 完整示例

 <!DOCTYPE html>
<html lang="en">

<body>
<h1>jQuery - How to disabled submit button after clicked</h1>

<form id="formABC" action="#" method="POST">
    <input type="submit" id="btnSubmit" value="Submit"></input>
</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<input type="button" value="i am normal abc" id="btnTest"></input>

<script>
    $(document).ready(function () {
    
    

        $("#formABC").submit(function (e) {
    
    

            //stop submitting the form to see the disabled button effect
            e.preventDefault();

            //disable the submit button
            $("#btnSubmit").attr("disabled", true);

            //disable a normal button
            $("#btnTest").attr("disabled", true);

            return true;

        });
    });
</script>

</body>
</html> 

参考

  1. jQuery 提交 API

如何显示 Spring Boot 加载的所有 beans

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/spring-boot/how-to-display-all-beans-loaded-by-spring-boot/

在 Spring Boot,您可以使用appContext.getBeanDefinitionNames()来获取 Spring 容器装载的所有 beans。

1.CommandLineRunner 作为接口

Application.java

 package com.mkyong;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

import java.util.Arrays;

@SpringBootApplication
public class Application implements CommandLineRunner {
    
    

    @Autowired
    private ApplicationContext appContext;

    public static void main(String[] args) throws Exception {
    
    
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
    
    

        String[] beans = appContext.getBeanDefinitionNames();
        Arrays.sort(beans);
        for (String bean : beans) {
    
    
            System.out.println(bean);
        }

    }

} 

输出

Console.java

 application
customerRepository
customerRepositoryImpl
dataSource
dataSourceInitializedPublisher
dataSourceInitializer
dataSourceInitializerPostProcessor
emBeanDefinitionRegistrarPostProcessor
entityManagerFactory
entityManagerFactoryBuilder
hikariPoolDataSourceMetadataProvider
jdbcTemplate
jpaContext
//... 

2.作为 Bean 的 CommandLineRunner

只是打印加载的 beans 的方式不同。

Application.java

 package com.mkyong;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;

import java.util.Arrays;

@SpringBootApplication
public class Application {
    
    

    public static void main(String[] args) throws Exception {
    
    
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public CommandLineRunner run(ApplicationContext appContext) {
    
    
        return args -> {
    
    

            String[] beans = appContext.getBeanDefinitionNames();
            Arrays.stream(beans).sorted().forEach(System.out::println);

        };
    }

} 

参考

  1. 命令行运行程序 JavaDoc
  2. Spring Boot 非 web 应用实例

application context spring boot

如何在 JSF 显示数据表的行号

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jsf2/how-to-display-datatable-row-numbers-in-jsf/

JSF 数据表不包含任何显示当前选定行号的方法。但是,您可以使用javax . faces . model . data model类来破解它,该类有一个 getRowIndex() 方法来返回当前选择的行号。

JSF +数据模型

下面是一个 JSF 2.0 的例子,展示了如何使用 DataModel 返回当前选中的行号。

freestar.config.enabled_slots.push({ placementName: “mkyong_incontent_1”, slotId: “mkyong_incontent_1” });

1.受管 Bean

一个名为“person”的托管 bean,并展示了如何使用 DataModel 来保存 person 对象的列表。

 package com.mkyong;

import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.model.ArrayDataModel;
import javax.faces.model.DataModel;

@ManagedBean(name="person")
@SessionScoped
public class PersonBean implements Serializable{
    
    

	private static final long serialVersionUID = 1L;

	private static final Person[] personList = new Person[]{
    
    

		new Person("Person", "A", 10),
		new Person("Person", "B", 20),
		new Person("Person", "C", 30),
		new Person("Person", "D", 40),
		new Person("Person", "E", 50)

	};

	/* To get the row numbers, use dataModel instead
	public Person[] getPersonList() {

		return personList;

	}
	*/

	private DataModel<Person> person = new ArrayDataModel<Person>(personList);

	public DataModel<Person> getPersonList() {
    
    

		return person;

	}

	public static class Person{
    
    

		String firstName;
		String lastName;
		int age;

		public Person(String firstName, String lastName, int age) {
    
    
			super();
			this.firstName = firstName;
			this.lastName = lastName;
			this.age = age;
		}

		//getter and setter methods 
	}
} 

2.JSF·佩奇

显示使用 DataModel " rowIndex "返回当前选定行号的 0 索引的 JSP 页面。

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html    
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      >
    <h:head>
    	<h:outputStylesheet library="css" name="table-style.css"  />
    </h:head>
    <h:body>

    	<h1>Display dataTable row numbers in JSF</h1>

    	   <h:dataTable value="#{person.personList}" var="p"
    		styleClass="person-table"
    		headerClass="person-table-header"
    		rowClasses="person-table-odd-row,person-table-even-row"
    	   >

		<h:column>

    			<!-- display currently selected row number -->
    			<f:facet name="header">No</f:facet>
    			#{
    
    person.personList.rowIndex + 1}

    		</h:column>

    		<h:column>

    			<f:facet name="header">First Name</f:facet>
    			#{
    
    p.firstName}

    		</h:column>

    		<h:column>

    			<f:facet name="header">Last Name</f:facet>
    			#{
    
    p.lastName}

    		</h:column>

    		<h:column>

    			<f:facet name="header">Age</f:facet>
    			#{
    
    p.age}

    		</h:column>

    	   </h:dataTable>

    </h:body>
</html> 

3.演示

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

下载源代码

Download It – JSF-2-DataTable-RowNumbers-Example.zip (10KB)

参考

  1. JSF 数据模型 JavaDoc
  2. JSF 数组数据模型 JavaDoc

Tags : datatable jsf2freestar.config.enabled_slots.push({ placementName: “mkyong_leaderboard_btf”, slotId: “mkyong_leaderboard_btf” });

如何显示 hibernate sql 参数值–Log4j

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/hibernate/how-to-display-hibernate-sql-parameter-values-log4j/

问题

Hibernate 具有基本的日志记录特性,可以显示带有 show_sql 配置属性的 SQL 生成语句。

 Hibernate: INSERT INTO mkyong.stock_transaction (CHANGE, CLOSE, DATE, OPEN, STOCK_ID, VOLUME) 
VALUES (?, ?, ?, ?, ?, ?) 

然而,这对于调试来说还不够,Hibernate SQL 参数值丢失了。

解决方案–Log4j

显示真实的 Hibernate SQL 参数值需要 Log4J。

1.在休眠模式下配置 Log4j

按照本文来在 Hibernate 中配置 Log4j

2.更改日志级别

修改 Log4j 属性文件,在“Log4j . logger . org . hibernate . type”属性中将日志级别改为“调试”或“跟踪”。

文件:log4j.properties

 # Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{
    
    ABSOLUTE} %5p %c{
    
    1}:%L - %m%n

# Root logger option
log4j.rootLogger=INFO, stdout

# Hibernate logging options (INFO only shows startup messages)
log4j.logger.org.hibernate=INFO

# Log JDBC bind parameter runtime arguments
log4j.logger.org.hibernate.type=trace 

3.完成的

现在显示休眠真实参数值

输出…

 Hibernate: INSERT INTO mkyong.stock_transaction (CHANGE, CLOSE, DATE, OPEN, STOCK_ID, VOLUME) 
VALUES (?, ?, ?, ?, ?, ?)
13:33:07,253 DEBUG FloatType:133 - binding '10.0' to parameter: 1
13:33:07,253 DEBUG FloatType:133 - binding '1.1' to parameter: 2
13:33:07,253 DEBUG DateType:133 - binding '30 December 2009' to parameter: 3
13:33:07,269 DEBUG FloatType:133 - binding '1.2' to parameter: 4
13:33:07,269 DEBUG IntegerType:133 - binding '11' to parameter: 5
13:33:07,269 DEBUG LongType:133 - binding '1000000' to parameter: 6 

Note
If this logging is still not detail enough for you to debug the SQL problem, you can use the P6Spy library to log the exact SQL statement that send to database. Check this article – How to display hibernate sql parameter values with P6Spy

如何显示 hibernate sql 参数值–P6Spy

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/hibernate/how-to-display-hibernate-sql-parameter-values-solution/

问题

有很多开发人员询问关于 Hibernate SQL 参数值的问题。如何显示传递给数据库的 Hibernate SQL 参数值?Hibernate 只是将所有参数值显示为问号(?).利用 show_sql 属性,Hibernate 将显示所有生成的 sql 语句,但不显示 SQL 参数值。

例如

 Hibernate: insert into mkyong.stock_transaction (CHANGE, CLOSE, DATE, OPEN, STOCK_ID, VOLUME) 
values (?, ?, ?, ?, ?, ?) 

有办法记录或显示准确的 Hibernate SQL 参数值吗?

解决方案–P6Spy

嗯,有问题就有答案~

P6Spy 是一个有用的库,可以在将所有 SQL 语句和参数值发送到数据库之前记录它们。P6Spy 是免费的,它用于拦截和记录所有数据库 SQL 语句到一个日志文件中,它适用于任何使用 JDBC 驱动程序的应用程序。

1.下载 P6Spy 库

获取“ p6spy-install.jar ”,您可以从

  1. P6Spy 官网
  2. 在 Sourceforge.net 的间谍活动

2.提取它

提取 p6spy-install.jar 文件,查找 p6spy.jarspy.properties

3.添加库依赖项

p6spy.jar 添加到您的项目库依赖项中

4.修改 P6Spy 属性文件

修改您的数据库配置文件。您需要将您现有的 JDBC 驱动程序替换为 P6Spy JDBC 驱动程序-“T0”

原文是 MySQL JDBC 驱动——“com . MySQL . JDBC . driver”

 <session-factory>
  <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.password">password</property>
  <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mkyong</property>
  <property name="hibernate.connection.username">root</property>
  <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="show_sql">true</property>
</session-factory> 

改为 P6Spy JDBC 驱动——“com . P6Spy . engine . spy . p6spydriver”

 <session-factory>
  <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
  <property name="hibernate.connection.driver_class">com.p6spy.engine.spy.P6SpyDriver
  </property>
  <property name="hibernate.connection.password">password</property>
  <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mkyong</property>
  <property name="hibernate.connection.username">root</property>
  <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="show_sql">true</property>
</session-factory> 

5.修改 P6Spy 属性文件

修改 P6Spy 属性文件-“spy . properties

用现有的 MySQL JDBC 驱动程序替换“真正的驱动程序”

 realdriver=com.mysql.jdbc.Driver

#specifies another driver to use
realdriver2=
#specifies a third driver to use
realdriver3= 

更改日志文件位置
logfile 属性中更改日志文件位置,所有 SQL 语句都会记录到这个文件中。

窗户

 logfile     = c:/spy.log 

*nix

 logfile     = /srv/log/spy.log 

6.将“spy.properties”复制到项目类路径中

将“spy.properties”复制到您的项目根文件夹中,确保您的项目可以找到“spy.properties”,否则将提示“spy.properties”文件未找到异常。

7.完成的

运行您的应用程序并执行一些数据库事务,您会注意到从应用程序发送到数据库的所有 SQL 语句都将被记录到您在“spy.properties”中指定的文件中。

示例日志文件如下。

 insert into mkyong.stock_transaction (CHANGE, CLOSE, DATE, OPEN, STOCK_ID, VOLUME) 
values (?, ?, ?, ?, ?, ?)|
insert into mkyong.stock_transaction (CHANGE, CLOSE, DATE, OPEN, STOCK_ID, VOLUME) 
values (10.0, 1.1, '2009-12-30', 1.2, 11, 1000000) 

结论

坦率地说,P6Spy 在减少开发人员的调试时间方面非常有用。只要您的项目使用 JDBC 驱动程序进行连接,P6Sqp 就可以进入它并为您记录所有 SQL 语句和参数值。

对于 Maven 用户

您可以使用 Maven 将 P6Spy 依赖项下载到您的pom.xml

 <dependency>
		<groupId>p6spy</groupId>
		<artifactId>p6spy</artifactId>
		<version>1.3</version>
	</dependency> 

然而,“spy.properties”文件不在包中,你必须自己创建它。你可以在这里下载模板-spy . properties

参考

  1. P6Spy 配置

Tags : hibernate parameter

相关文章

在 Wicket 中向 HTML 标签动态添加属性

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/wicket/how-to-dynamic-add-attribute-to-a-html-tag-in-wicket/

在 Wicket 中,您可以轻松地访问或操作 HTML 标记。比方说,您有一个 HTML 文本框组件,由一个 div 标记包装,如果文本框验证失败,div 标记应该以错误颜色突出显示。

在上面的例子中,你可以实现" AbstractBehavior "类,来动态地给 HTML 标签添加属性。请参见以下示例:

原始 HTML


    Hello ~ Wicket leaning curve is high, do you?

用 Wicket AbstractBehavior 修改

 WebMarkupContainerWithAssociatedMarkup divtest = 
        new WebMarkupContainerWithAssociatedMarkup("wicket_id_test");

    //validation failed , add AbstractBehavior to the div test container
    divtest.add(new AbstractBehavior() {
    
    

	    public void onComponentTag(Component component, ComponentTag tag) {
    
    
			tag.put("style", "background-color:red");
	    }
	}); 

结果如下:


    Hello ~ this is testing for adding attribute into above tag in Wicket ~

wicket外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传 (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById®;if(e=null){ var t = d.createElement(o); t.src = g; t.id = r; t.setAttribute(m, s);t.async = 1;var n=d.getElementsByTagName(o)[0];n.parentNode.insertBefore(t, n); var dt=new Date().getTime(); try{i[l]w+y;}catch(er){i[h]=dt;} } else if(typeof i[c]!‘undefined’){i[c]++} else{i[c]=1;} })(window, document, ‘InContent’, ‘script’, ‘mediaType’, ‘carambola_proxy’,‘Cbola_IC’,‘localStorage’,‘set’,‘get’,‘Item’,‘cbolaDt’,‘//web.archive.org/web/20190304031820/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0’)

如何在 Hibernate 查询中嵌入 Oracle 提示

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/hibernate/how-to-embed-oracle-hints-in-hibernate-query/

使用 Oracle 提示,您可以改变 Oracle 执行计划,以影响 Oracle 从数据库中检索数据的方式。请点击此处了解有关 Oracle 优化器提示的更多详细信息。

在 Hibernate 中,有可能将 Oracle 提示嵌入 Hibernate 查询中吗?

Hibernate setComment()?

能否用 Hibernate 自定义注释" setComment() "函数将 Oracle 提示嵌入到 HQL 中?让我们来看一个例子

1.原始 Hibernate 查询

这是一个简单的选择 HQL 检索股票代码的股票。

 String hql = "from Stock s where s.stockCode = :stockCode";
List result = session.createQuery(hql)
.setString("stockCode", "7277")
.list(); 

输出

 Hibernate: 
    select
        stock0_.STOCK_ID as STOCK1_0_,
        stock0_.STOCK_CODE as STOCK2_0_,
        stock0_.STOCK_NAME as STOCK3_0_ 
    from mkyong.stock stock0_ 
    where stock0_.STOCK_CODE=? 

2.尝试 Hibernate setComment()

在 hibernate 的配置文件(hibernate.cfg.xml)中启用Hibernate . use _ SQL _ comments,以便将自定义注释输出到日志文件或控制台。

 <!-- hibernate.cfg.xml -->
<?xml version="1.0" encoding="utf-8"?>
...
<hibernate-configuration>
 <session-factory>
    ...
    <property name="show_sql">true</property>
    <property name="format_sql">true</property>
    <property name="use_sql_comments">true</property>
    <mapping class="com.mkyong.common.Stock" />
  </session-factory>
</hibernate-configuration> 

使用 Hibernate setComment() 向查询中插入自定义注释。

 String hql = "from Stock s where s.stockCode = :stockCode";
List result = session.createQuery(hql)
.setString("stockCode", "7277")
.setComment("+ INDEX(stock idx_stock_code)")
.list(); 

输出

 Hibernate: 
    /* + INDEX(stock idx_stock_code) */ select
        stock0_.STOCK_ID as STOCK1_0_,
        stock0_.STOCK_CODE as STOCK2_0_,
        stock0_.STOCK_NAME as STOCK3_0_ 
    from mkyong.stock stock0_ 
    where stock0_.STOCK_CODE=? 

3.这是工作吗?

事实并非如此,Hibernate 自定义注释有两个问题。

1.Oracle 提示必须追加在“select”之后,而不是之前。

Hibernate 生成的查询

 /* + INDEX(stock idx_stock_code) */ select 

正确的做法应该是…

 select  /*+ INDEX(stock idx_stock_code) */ 

2.Hibernate 会自动在“/* +”之间添加一个额外的空格。

在 Hibernate 中,仍然没有官方方法将 Oracle 提示嵌入到 Hibernate 查询语言(HQL)中。

附注:感谢皮特对此的贡献。

工作液

唯一的解决方案是使用 Hibernate createSQLQuery 方法来执行原生 SQL 语句。

 String hql = "/*+ INDEX(stock idx_stock_code) */ 
    select * from stock s where s.stock_code = :stockCode";
List result = session.createQuery(hql)
.setString("stockCode", "7277")
.list(); 

输出

 Hibernate: 
    /*+ INDEX(stock idx_stock_code) */ select * 
    from stock s where s.stock_code = ? 

更多原生 SQL 查询示例

gson——如何实现漂亮的 JSON 输出

原文:http://web.archive.org/web/20230101150211/https://www.mkyong.com/java/how-to-enable-pretty-print-json-output-gson/

在本教程中,我们将向您展示如何在 Gson 框架中启用 JSON pretty print。

1.默认情况下,Gson 压缩打印 JSON 输出:

GsonExample1.java

 package com.mkyong;

import com.google.gson.Gson;

public class GsonExample1 {
    
    

    public static void main(String[] args) {
    
    

        Gson gson = new Gson();

        String[] lang = {
    
    "Java", "Node", "Kotlin", "JavaScript"};

        String json = gson.toJson(lang);

        System.out.println(json);

    }

} 

输出

 ["Java","Node","Kotlin","JavaScript"] 

2.要启用 JSON 漂亮打印,用GsonBuilder创建Gson对象

GsonExample2.java

 package com.mkyong;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GsonExample2 {
    
    

    public static void main(String[] args) {
    
    

        Gson gson = new GsonBuilder().setPrettyPrinting().create();

        String[] lang = {
    
    "Java", "Node", "Kotlin", "JavaScript"};

        String json = gson.toJson(lang);

        System.out.println(json);

    }

} 

输出

 [
  "Java",
  "Node",
  "Kotlin",
  "JavaScript"
] 

Note
Read more Gson examples

参考

Jackson——如何实现漂亮的 JSON 输出

原文:http://web.archive.org/web/20230101150211/https://www.mkyong.com/java/how-to-enable-pretty-print-json-output-jackson/

在 Jackson 中,我们可以使用writerWithDefaultPrettyPrinter()来打印 JSON 输出。

用杰克逊 2.9.8 测试

1.漂亮的打印 JSON

1.1 默认情况下,Jackson 以紧凑格式打印:

 ObjectMapper mapper = new ObjectMapper();
	Staff staff = createStaff();
	String json = mapper.writeValueAsString(staff);
	System.out.println(json); 

输出

 {
    
    "name":"mkyong","age":38,"skills":["java","python","node","kotlin"]} 

1.2 实现按需打印。

 ObjectMapper mapper = new ObjectMapper();
	Staff staff = createStaff();
	// pretty print
	String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(staff);
	System.out.println(json); 

输出

 {
    
    
  "name" : "mkyong",
  "age" : 38,
  "skills" : [ "java", "python", "node", "kotlin" ]
} 

1.3 全球启用 pretty print。

 import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

	// pretty print
	ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
	Staff staff = createStaff();
	String json = mapper.writeValueAsString(staff);
	System.out.println(json); 

输出

 {
    
    
  "name" : "mkyong",
  "age" : 38,
  "skills" : [ "java", "python", "node", "kotlin" ]
} 

Note
To display the pretty print JSON output on an HTML page, wraps it with pre tags.
<pre>${pretty-print-json-output}</pre>Note – 12/12/2013
The article is updated to use writerWithDefaultPrettyPrinter(), the old defaultPrettyPrintingWriter() is deprecated.

参考

如何在 Maven 中启用代理设置

原文:http://web.archive.org/web/20230101150211/https://www.mkyong.com/maven/how-to-enable-proxy-setting-in-maven/

要在 Maven 中启用代理访问,请在{MAVEN_HOME}/conf/settings.xml中定义代理服务器细节

Note
There is a high chance your company is set up an HTTP proxy server to stop user connecting to the Internet directly. If you are behind a proxy, Maven will fail to download the project dependencies.

PS 用 Maven 3.6 测试过

1.代理访问

1.打开 Maven settings.xml,找到proxies标签:

{MAVEN_HOME}/conf/settings.xml

 <!-- 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> 

1.2 定义了如下的代理服务器设置:

 <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>
    -->

	<proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>mkyong</username>
      <password>password</password>
      <host>proxy.mkyong.com</host>
      <port>8888</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>

  </proxies> 

1.3 完成后,Apache Maven 应该能够通过代理服务器连接到互联网。

参考

  1. 配置代理

如何用正则表达式提取 HTML 链接

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/regular-expressions/how-to-extract-html-links-with-regular-expression/

在本教程中,我们将向您展示如何从 HTML 页面中提取超链接。例如,从以下内容中获取链接:

 this is text1 <a href='mkyong.com' target='_blank'>hello</a> this is text2... 
  1. 首先从a标签获取“值”——结果:a href='mkyong.com' target='_blank'
  2. 稍后从上面提取的值中获取“链接”——结果:mkyong.com

1.正则表达式模式

提取标签正则表达式模式

 (?i)<a([^>]+)>(.+?)</a> 

从标签正则表达式模式中提取链接

 \s*(?i)href\s*=\s*(\"([^"]*\")|'[^']*'|([^'">\s]+)); 

描述

 (		#start of group #1
 ?i		#  all checking are case insensive
)		#end of group #1
<a              #start with "<a"
  (		#  start of group #2
    [^>]+	#     anything except (">"), at least one character
   )		#  end of group #2
  >		#     follow by ">"
    (.+?)	#	match anything 
         </a>	#	  end with "</a> 
 \s*			   #can start with whitespace
  (?i)			   # all checking are case insensive
     href		   #  follow by "href" word
        \s*=\s*		   #   allows spaces on either side of the equal sign,
              (		   #    start of group #1
               "([^"]*")   #      allow string with double quotes enclosed - "string"
               |	   #	  ..or
               '[^']*'	   #        allow string with single quotes enclosed - 'string'
               |           #	  ..or
               ([^'">]+)   #      can't contains one single quotes, double quotes ">"
	      )		   #    end of group #1 

2.Java 链接提取器示例

下面是一个简单的 Java 链接提取器示例,从第一个模式中提取a标记值,并使用第二个模式从第一个模式中提取链接。

HTMLLinkExtractor.java

 package com.mkyong.crawler.core;

import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HTMLLinkExtractor {
    
    

	private Pattern patternTag, patternLink;
	private Matcher matcherTag, matcherLink;

	private static final String HTML_A_TAG_PATTERN = "(?i)<a([^>]+)>(.+?)</a>";
	private static final String HTML_A_HREF_TAG_PATTERN = 
		"\\s*(?i)href\\s*=\\s*(\"([^\"]*\")|'[^']*'|([^'\">\\s]+))";

	public HTMLLinkExtractor() {
    
    
		patternTag = Pattern.compile(HTML_A_TAG_PATTERN);
		patternLink = Pattern.compile(HTML_A_HREF_TAG_PATTERN);
	}

	/**
	 * Validate html with regular expression
	 * 
	 * @param html
	 *            html content for validation
	 * @return Vector links and link text
	 */
	public Vector<HtmlLink> grabHTMLLinks(final String html) {
    
    

		Vector<HtmlLink> result = new Vector<HtmlLink>();

		matcherTag = patternTag.matcher(html);

		while (matcherTag.find()) {
    
    

			String href = matcherTag.group(1); // href
			String linkText = matcherTag.group(2); // link text

			matcherLink = patternLink.matcher(href);

			while (matcherLink.find()) {
    
    

				String link = matcherLink.group(1); // link
				HtmlLink obj = new HtmlLink();
				obj.setLink(link);
				obj.setLinkText(linkText);

				result.add(obj);

			}

		}

		return result;

	}

	class HtmlLink {
    
    

		String link;
		String linkText;

		HtmlLink(){
    
    };

		@Override
		public String toString() {
    
    
			return new StringBuffer("Link : ").append(this.link)
			.append(" Link Text : ").append(this.linkText).toString();
		}

		public String getLink() {
    
    
			return link;
		}

		public void setLink(String link) {
    
    
			this.link = replaceInvalidChar(link);
		}

		public String getLinkText() {
    
    
			return linkText;
		}

		public void setLinkText(String linkText) {
    
    
			this.linkText = linkText;
		}

		private String replaceInvalidChar(String link){
    
    
			link = link.replaceAll("'", "");
			link = link.replaceAll("\"", "");
			return link;
		}

	}
} 

3.单元测试

用 TestNG 进行单元测试。通过@DataProvider模拟 HTML 内容。

TestHTMLLinkExtractor.java

 package com.mkyong.crawler.core;

import java.util.Vector;

import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import com.mkyong.crawler.core.HTMLLinkExtractor.HtmlLink;

/**
 * HTML link extrator Testing
 * 
 * @author mkyong
 * 
 */
public class TestHTMLLinkExtractor {
    
    

	private HTMLLinkExtractor htmlLinkExtractor;
	String TEST_LINK = "http://www.google.com";

	@BeforeClass
	public void initData() {
    
    
		htmlLinkExtractor = new HTMLLinkExtractor();
	}

	@DataProvider
	public Object[][] HTMLContentProvider() {
    
    
	  return new Object[][] {
    
    
	    new Object[] {
    
     "abc hahaha <a href='" + TEST_LINK + "'>google</a>" },
	    new Object[] {
    
     "abc hahaha <a HREF='" + TEST_LINK + "'>google</a>" },

	    new Object[] {
    
     "abc hahaha <A HREF='" + TEST_LINK + "'>google</A> , "
		+ "abc hahaha <A HREF='" + TEST_LINK + "' target='_blank'>google</A>" },

	    new Object[] {
    
     "abc hahaha <A HREF='" + TEST_LINK + "' target='_blank'>google</A>" },
	    new Object[] {
    
     "abc hahaha <A target='_blank' HREF='" + TEST_LINK + "'>google</A>" },
	    new Object[] {
    
     "abc hahaha <A target='_blank' HREF=\"" + TEST_LINK + "\">google</A>" },
	    new Object[] {
    
     "abc hahaha <a HREF=" + TEST_LINK + ">google</a>" }, };
	}

	@Test(dataProvider = "HTMLContentProvider")
	public void ValidHTMLLinkTest(String html) {
    
    

		Vector<HtmlLink> links = htmlLinkExtractor.grabHTMLLinks(html);

		//there must have something
		Assert.assertTrue(links.size() != 0);

		for (int i = 0; i < links.size(); i++) {
    
    
			HtmlLink htmlLinks = links.get(i);
			//System.out.println(htmlLinks);
			Assert.assertEquals(htmlLinks.getLink(), TEST_LINK);
		}

	}
} 

结果

 [TestNG] Running:
  /private/var/folders/w8/jxyz5pf51lz7nmqm_hv5z5br0000gn/T/testng-eclipse--530204890/testng-customsuite.xml

PASSED: ValidHTMLLinkTest("abc hahaha <a href='http://www.google.com'>google</a>")
PASSED: ValidHTMLLinkTest("abc hahaha <a HREF='http://www.google.com'>google</a>")
PASSED: ValidHTMLLinkTest("abc hahaha <A HREF='http://www.google.com'>google</A> , abc hahaha <A HREF='http://www.google.com' target='_blank'>google</A>")
PASSED: ValidHTMLLinkTest("abc hahaha <A HREF='http://www.google.com' target='_blank'>google</A>")
PASSED: ValidHTMLLinkTest("abc hahaha <A target='_blank' HREF='http://www.google.com'>google</A>")
PASSED: ValidHTMLLinkTest("abc hahaha <A target='_blank' HREF="http://www.google.com">google</A>")
PASSED: ValidHTMLLinkTest("abc hahaha <a HREF=http://www.google.com>google</a>") 

参考

  1. 测试文档
  2. 维基中的超链接

Tags : html regex

相关文章

如何在 Java 中查找文件扩展名为的文件

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/java/how-to-find-files-with-certain-extension-only/

本文展示了如何用 Java 8 Files.walk遍历文件树和流操作filter来从文件夹及其子文件夹中查找与特定文件扩展名匹配的文件。

 // find files matched `png` file extension from folder C:\\test
  try (Stream<Path> walk = Files.walk(Paths.get("C:\\test"))) {
    
    
      result = walk
              .filter(p -> !Files.isDirectory(p))   // not a directory
              .map(p -> p.toString().toLowerCase()) // convert path to string
              .filter(f -> f.endsWith("png"))       // check end with
              .collect(Collectors.toList());        // collect all matched to a List
  } 

Files.walk方法中,第二个参数maxDepth定义了要访问的最大目录级别数。我们可以指定maxDepth = 1只从顶层文件夹中查找文件(排除它所有的子文件夹)

 try (Stream<Path> walk = Files.walk(Paths.get("C:\\test"), 1)) {
    
    
      //...
  } 

主题

  1. 查找指定文件扩展名的文件(Files.walk)
  2. 查找具有多个文件扩展名的文件(Files.walk)

1。查找具有指定文件扩展名

的文件

本示例查找与文件扩展名png匹配的文件。查找从顶层文件夹C:\\test开始,包括所有级别的子文件夹。

FindFileByExtension1.java

 package com.mkyong.io.howto;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class FindFileByExtension1 {
    
    

    public static void main(String[] args) {
    
    

        try {
    
    

            List<String> files = findFiles(Paths.get("C:\\test"), "png");
            files.forEach(x -> System.out.println(x));

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

    }

    public static List<String> findFiles(Path path, String fileExtension)
        throws IOException {
    
    

        if (!Files.isDirectory(path)) {
    
    
            throw new IllegalArgumentException("Path must be a directory!");
        }

        List<String> result;

        try (Stream<Path> walk = Files.walk(path)) {
    
    
            result = walk
                    .filter(p -> !Files.isDirectory(p))
                    // this is a path, not string,
                    // this only test if path end with a certain path
                    //.filter(p -> p.endsWith(fileExtension))
                    // convert path to string first
                    .map(p -> p.toString().toLowerCase())
                    .filter(f -> f.endsWith(fileExtension))
                    .collect(Collectors.toList());
        }

        return result;
    }

} 

输出

Terminal

 c:\test\bk\logo-new.png
c:\test\bk\resize-default.png
c:\test\google.png
c:\test\test1\test2\java.png
... 

2。查找具有多个文件扩展名的文件

本示例查找与多个文件扩展名(.png.jpg.gif)匹配的文件。

FindFileByExtension2.java

 package com.mkyong.io.howto;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class FindFileByExtension2 {
    
    

    public static void main(String[] args) {
    
    

        try {
    
    

            String[] extensions = {
    
    "png", "jpg", "gif"};
            List<String> files = findFiles(Paths.get("C:\\test"), extensions);
            files.forEach(x -> System.out.println(x));

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

    }

    public static List<String> findFiles(Path path, String[] fileExtensions) throws IOException {
    
    

        if (!Files.isDirectory(path)) {
    
    
            throw new IllegalArgumentException("Path must be a directory!");
        }

        List<String> result;
        try (Stream<Path> walk = Files.walk(path, 1)) {
    
    
            result = walk
                    .filter(p -> !Files.isDirectory(p))
                    // convert path to string
                    .map(p -> p.toString().toLowerCase())
                    .filter(f -> isEndWith(f, fileExtensions))
                    .collect(Collectors.toList());
        }
        return result;

    }

    private static boolean isEndWith(String file, String[] fileExtensions) {
    
    
        boolean result = false;
        for (String fileExtension : fileExtensions) {
    
    
            if (file.endsWith(fileExtension)) {
    
    
                result = true;
                break;
            }
        }
        return result;
    }

} 

输出

Terminal

 c:\test\bk\logo-new.png
c:\test\bk\resize-default.gif
c:\test\bk\resize-fast.gif
c:\test\bk\resize.png
c:\test\google.jpg
c:\test\google.png
c:\test\test1\test2\java.png
c:\test\test1\test2\java.jpg 

2.2 使用 Java 8 stream anyMatch可以缩短isEndWith()方法。

 private static boolean isEndWith(String file, String[] fileExtensions) {
    
    

    // Java 8, try this
    boolean result = Arrays.stream(fileExtensions).anyMatch(file::endsWith);
    return result;

    // old school style
    /*boolean result = false;
    for (String fileExtension : fileExtensions) {
        if (file.endsWith(fileExtension)) {
            result = true;
            break;
        }
    }
    return result;*/
} 

2.3 我们也可以去掉isEndWith()方法,直接将anyMatch放入filter中。

 public static List<String> findFiles(Path path, String[] fileExtensions)
      throws IOException {
    
    

      if (!Files.isDirectory(path)) {
    
    
          throw new IllegalArgumentException("Path must be a directory!");
      }

      List<String> result;
      try (Stream<Path> walk = Files.walk(path, 1)) {
    
    
          result = walk
                  .filter(p -> !Files.isDirectory(p))
                  // convert path to string
                  .map(p -> p.toString().toLowerCase())
                  //.filter(f -> isEndWith(f, fileExtensions))

                  // lambda
                  //.filter(f -> Arrays.stream(fileExtensions).anyMatch(ext -> f.endsWith(ext)))

                  // method reference
                  .filter(f -> Arrays.stream(fileExtensions).anyMatch(f::endsWith))     
                  .collect(Collectors.toList());
      }
      return result;

  } 

2.4 我们可以通过将不同的条件传递到流filter中来进一步增强程序;现在,该程序可以很容易地从文件夹中搜索或找到具有指定模式的文件。例如:

查找文件名以“abc”开头的文件。

 List<String> result;
  try (Stream<Path> walk = Files.walk(path)) {
    
    
      result = walk
              .filter(p -> !Files.isDirectory(p))
              // convert path to string
              .map(p -> p.toString())
              .filter(f -> f.startsWith("abc"))
              .collect(Collectors.toList());
  } 

查找文件名包含单词“mkyong”的文件。

 List<String> result;
  try (Stream<Path> walk = Files.walk(path)) {
    
    
      result = walk
              .filter(p -> !Files.isDirectory(p))
              // convert path to string
              .map(p -> p.toString())
              .filter(f -> f.contains("mkyong"))
              .collect(Collectors.toList());
  } 

下载源代码

$ git 克隆https://github.com/mkyong/core-java

$ cd java-io

参考文献

如何在 Java 中格式化 FileTime

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/java/how-to-format-filetime-in-java/

在 Java 中,我们可以使用DateTimeFormatterFileTime转换成其他自定义的日期格式。

 public static String formatDateTime(FileTime fileTime) {
    
    

        LocalDateTime localDateTime = fileTime
                .toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime();

        return localDateTime.format(
              DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss"));
} 

1.文件上次修改时间

此示例以自定义日期格式显示文件的上次修改时间。

GetLastModifiedTime.java

 package com.mkyong.io.howto;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

public class GetLastModifiedTime {
    
    

    private static final DateTimeFormatter DATE_FORMATTER =
            DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss");

    public static void main(String[] args) {
    
    

        String fileName = "/home/mkyong/test";

        try {
    
    

            Path file = Paths.get(fileName);
            BasicFileAttributes attr =
                    Files.readAttributes(file, BasicFileAttributes.class);

            // default YYYY-MM-DDThh:mm:ss[.s+]Z
            System.out.println("lastModifiedTime: " + attr.lastModifiedTime());

            FileTime fileTime = attr.lastModifiedTime();
            System.out.println("lastModifiedTime: " + formatDateTime(fileTime));

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

    }

    public static String formatDateTime(FileTime fileTime) {
    
    

        LocalDateTime localDateTime = fileTime
                .toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime();

        return localDateTime.format(DATE_FORMATTER);
    }

} 

输出

 lastModifiedTime: 2020-07-20T09:29:54.627222Z

lastModifiedTime: 07/20/2020 17:29:54 

下载源代码

$ git 克隆https://github.com/mkyong/core-java

$ cd java-io

参考

如何用 Hibernate 工具生成 Hibernate 映射文件和注释

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/hibernate/how-to-generate-code-with-hibernate-tools/

在本文中,我们将向您展示如何使用 Hibernate / JBoss Tools 从数据库自动生成 Hibernate 映射文件(hbm)和注释代码。

本文中的工具

  1. Eclipse v3.6 (Helios)
  2. JBoss / Hibernate 工具 3.2 版
  3. Oracle 11g
  4. JDK 1.6

Note
Before proceed, please Install Hibernate / JBoss Tools in Eclipse IDE.

1.Hibernate 透视图

打开你的休眠视角。在 Eclipse IDE 中,选择“Windows”>>打开透视图>>其他… ,选择“休眠”。

2.新的休眠配置

在 Hibernate 透视图中,右键选择“添加配置…

在“编辑配置”对话框中,

  1. 项目框中,点击【浏览…】按钮选择您的项目。
  2. 在“数据库连接框中,点击“新建…”按钮来创建数据库设置。
  3. 配置文件框中,点击【设置】按钮创建一个新的或者使用已有的【休眠配置文件】,hibernate.cfg.xml

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

在“ Hibernate 透视图”中查看您的表列表。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

hibernate.cfg.xml”示例,连接到 Oracle 11g 数据库。

 <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
  <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
  <property name="hibernate.connection.url">jdbc:oracle:thin:@127.0.0.1:1521:MKYONG</property>
  <property name="hibernate.connection.username">mkyong</property>
  <property name="hibernate.connection.password">password</property>
  <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
  <property name="hibernate.default_schema">MKYONG</property>
 </session-factory>
</hibernate-configuration> 

3.Hibernate 代码生成

现在,您已经准备好生成 Hibernate 映射文件和注释代码了。

–在“Hibernate 透视图”中,点击“ Hibernate 代码生成”图标(见下图),选择“Hibernate 代码生成配置”

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

–创建一个新配置,选择您的“控制台配置”(在步骤 2 中配置),放置您的“输出目录,选中选项“从 JDBC 连接反向工程”。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

–在“ Exporter 选项卡中,选择要生成的内容、模型、映射文件(hbm)、DAO、注释代码等。

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

看到结果

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传Note
The generated Hibernate mapping file and annotations code are very clean, standard and easy to modify. Try explore more features.

如何在 Java 中获得当前时间戳

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/java/how-to-get-current-timestamps-in-java/

本文展示了几个用 Java 获取当前日期时间或时间戳的 Java 示例。(Java 8 更新)。

代码片段

 // 2021-03-24 16:48:05.591
  Timestamp timestamp = new Timestamp(System.currentTimeMillis());

  // 2021-03-24 16:48:05.591
  Date date = new Date();
  Timestamp timestamp2 = new Timestamp(date.getTime());

  // convert Instant to Timestamp
  Timestamp ts = Timestamp.from(Instant.now())

  // convert ZonedDateTime to Instant to Timestamp
  Timestamp ts = Timestamp.from(ZonedDateTime.now().toInstant()));

  // convert Timestamp to Instant
  Instant instant = ts.toInstant(); 

目录

1。Java 时间戳示例

下面的程序使用java.sql.Timestamp获取当前时间戳,并用SimpleDateFormat格式化显示。

TimeStampExample.java

 package com.mkyong.app;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TimeStampExample {
    
    

    // 2021.03.24.16.34.26
    private static final SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");

    // 2021-03-24T16:44:39.083+08:00
    private static final SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");

    // 2021-03-24 16:48:05
    private static final SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static void main(String[] args) {
    
    

        // method 1
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        System.out.println(timestamp);                      // 2021-03-24 16:34:26.666

        // method 2 - via Date
        Date date = new Date();
        System.out.println(new Timestamp(date.getTime()));  // 2021-03-24 16:34:26.666
                                                            // number of milliseconds since January 1, 1970, 00:00:00 GMT
        System.out.println(timestamp.getTime());            // 1616574866666

        System.out.println(sdf1.format(timestamp));         // 2021.03.24.16.34.26

        System.out.println(sdf2.format(timestamp));         // 2021-03-24T16:48:05.591+08:00

        System.out.println(sdf3.format(timestamp));         // 2021-03-24 16:48:05

    }
} 

输出

Terminal

 2021-03-24 16:48:05.591
2021-03-24 16:48:05.591
1616575685591
2021.03.24.16.48.05
2021-03-24T16:48:05.591+08:00
2021-03-24 16:48:05 

2。将时间转换为时间戳/从时间戳转换为时间

这个例子展示了如何在新的 Java 8 java.time.Instant和旧的java.sql.Timestamp之间进行转换。

 // convert Instant to Timestamp
  Timestamp ts = Timestamp.from(Instant.now())

  // convert Timestamp to Instant
  Instant instant = ts.toInstant(); 

InstantExample.java

 package com.mkyong.app;

import java.sql.Timestamp;
import java.time.Instant;

public class InstantExample {
    
    

  public static void main(String[] args) {
    
    

      Timestamp timestamp = new Timestamp(System.currentTimeMillis());
      System.out.println(timestamp);                  // 2021-03-24 17:12:03.311
      System.out.println(timestamp.getTime());        // 1616577123311

      // Convert Timestamp to Instant
      Instant instant = timestamp.toInstant();
      System.out.println(instant);                    // 2021-03-24T09:12:03.311Z
      System.out.println(instant.toEpochMilli());     // 1616577123311

      // Convert Instant to Timestamp
      Timestamp tsFromInstant = Timestamp.from(instant);
      System.out.println(tsFromInstant.getTime());    // 1616577123311
  }
} 

输出

Terminal

 2021-03-24 17:12:03.311
1616577123311
2021-03-24T09:12:03.311Z
1616577123311
1616577123311 

3。将时间戳插入表中

java.sql.Timestamp在 JDBC 编程中仍被广泛使用。请参见下面的转换:

 // Java 8, java.time.*

  // convert LocalDateTime to Timestamp
  preparedStatement.setTimestamp(1, Timestamp.valueOf(LocalDateTime.now()));

  // convert Instant to Timestamp
  preparedStatement.setTimestamp(1, Timestamp.from(Instant.now()));

  // Convert ZonedDateTime to Instant to Timestamp
  preparedStatement.setTimestamp(3, Timestamp.from(ZonedDateTime.now().toInstant())); 

下面的例子是在表格中插入一个Timestamp的 JDBC 例子。

JdbcExample.java

 package com.mkyong.app;

import java.math.BigDecimal;
import java.sql.*;
import java.time.LocalDateTime;

public class JdbcExample {
    
    

  private static final String SQL_INSERT = "INSERT INTO EMPLOYEE (NAME, SALARY, CREATED_DATE) VALUES (?,?,?)";

  public static void main(String[] args) {
    
    

      try (Connection conn = DriverManager.getConnection(
              "jdbc:postgresql://127.0.0.1:5432/test", "postgres", "password");
           PreparedStatement preparedStatement = conn.prepareStatement(SQL_INSERT)) {
    
    

          preparedStatement.setString(1, "mkyong");
          preparedStatement.setBigDecimal(2, new BigDecimal("799.88"));
          preparedStatement.setTimestamp(3, Timestamp.valueOf(LocalDateTime.now()));

          // preparedStatement.setTimestamp(3, Timestamp.from(ZonedDateTime.now().toInstant()));
          // preparedStatement.setTimestamp(3, Timestamp.from(Instant.now()));

          int row = preparedStatement.executeUpdate();

          // rows affected
          System.out.println(row); //1

      } catch (SQLException e) {
    
    
          System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
      } catch (Exception e) {
    
    
          e.printStackTrace();
      }

  }
} 


更多例子为用 Java 获取当前日期时间或时间戳。

4。参考文献

如何用 jQuery 和 JSON 获得好吃的书签计数

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/how-to-get-delicious-bookmark-count-with-jquery-and-json/

最好的书签网站 Delicious ,提供了许多 API 让开发者处理书签的数据。下面是一个使用 jQuery 检索给定 URL 的书签总数的例子。

美味 API

要获得书签总数,请使用以下命令

 http://feeds.delicious.com/v2/json/urlinfo/data?url=xxx.com&callback=? 

jQuery Ajax

jQuery 附带了一个简单而强大的**。ajax()** 或简写**。getJSON()** 按需获取远程数据。

1.jQuery。ajax()示例

使用 jQuery 。ajax() 从 Delicious 获取 json 数据,并显示书签计数的总数。

 $.ajax({
    
     
 type: "GET",
 dataType: "json",
 url: "http://feeds.delicious.com/v2/json/urlinfo/data?url="+url+"&amp;callback=?",
 success: function(data){
    
    			
	var count = 0;
	if (data.length > 0) {
    
    
		count = data[0].total_posts;
	}
	$("#delicious_result").text(count + ' Saved');			
 }
 }); 
2.jQuery。getJSON()示例

以上的简写。ajax() 方法,两者都在做同样的任务。

 $.getJSON("
   http://feeds.delicious.com/v2/json/urlinfo/data?url="+url+"&callback=?",

   function(data) {
    
    

   var count = 0;
   if (data.length > 0) {
    
    
	count = data[0].total_posts;
   }
   $("#delicious_result").text(count + ' Saved');

}); 

你自己试试

在本例中,在文本框中输入 URL,然后点击按钮以获得 Delicious 中书签的总数。

 <html>
<head>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
</head>

<body>
<h1>Get Delicious bookmark count with jQuery</h1>

URL : <input type='text' id='url' size='50' value='http://www.google.com' />
<br/><br/>
<h2>Delicious count : <span id="delicious_result"></span></h2>

<button id="delicious">Get Delicious Count (.Ajax)</button>
<button id="delicious2">Get Delicious Count (.getJSON)</button>
<script type="text/javascript">

$('#delicious').click(function(){
    
    

 $("#delicious_result").text("Loading......");

 var url = $('#url').val();

 $.ajax({
    
     
 type: "GET",
 dataType: "json",
 url: "http://feeds.delicious.com/v2/json/urlinfo/data?url="+url+"&amp;callback=?",
 success: function(data){
    
    

	var count = 0;
	if (data.length > 0) {
    
    
		count = data[0].total_posts;
	}
	$("#delicious_result").text(count + ' Saved');

   }
  });
});

$('#delicious2').click(function(){
    
    

 $("#delicious_result").text("Loading......");

 var url = $('#url').val();

 $.getJSON("
    http://feeds.delicious.com/v2/json/urlinfo/data?url="+url+"&callback=?",

 function(data) {
    
    

	var count = 0;
	if (data.length > 0) {
    
    
		count = data[0].total_posts;
	}
	$("#delicious_result").text(count + ' Saved');

  });	
});
</script>

</body>
</html> 

http://web.archive.org/web/20220204001715if_/https://www.mkyong.com/wp-content/uploads/jQuery/jQuery-get-delicious-bookmark-count-example.html

Try Demo

参考

  1. http://delicious.com/help/feeds
  2. http://API . jquery . com/jquery . getjson/

如何在 Java 中获取文件扩展名

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/java/how-to-get-file-extension-in-java/

本文展示了如何在 Java 中获取文件的文件扩展名。

主题

  1. 获取文件扩展名正常
  2. 获取文件扩展名严格
  3. 获取文件扩展名硬编码
  4. Apache 通用 IO–filename utils
 Path: /path/foo.txt                  -> File Extension: txt
  Path: .                              -> File Extension:
  Path: ..                             -> File Extension:
  Path: /path/run.exe                  -> File Extension: exe
  Path: /path/makefile                 -> File Extension:
  Path: /path/.htaccess                -> File Extension: htaccess
  Path: /path/.tar.gz                  -> File Extension: gz
  Path: /path/../makefile              -> File Extension:
  Path: /path/dir.test/makefile        -> File Extension: 

查看上面从获取文件扩展名严格示例的输出。对于没有扩展名的文件,我们将显示为空。

1。获取文件扩展名,普通版本。

这个例子展示了如何使用 String#lastIndexOf 来获取文件的文件扩展名,它应该适合大多数情况。

 String extension = "";

  int index = fileName.lastIndexOf('.');
  if (index > 0) {
    
    
      extension = fileName.substring(index + 1);
  } 

但是,对于以下情况,上述方法将失败:目录名或文件路径包含一个点或双点,并且文件没有扩展名。

 Path: /path/../makefile              -> File Extension: /makefile
  Path: /path/dir.test/makefile        -> File Extension: test/makefile 

完整的例子。

GetFileExtension1.java

 package com.mkyong.io.howto;

public class GetFileExtension1 {
    
    

    private static final String OUTPUT_FORMAT = "Path: %-30s -> File Extension: %s";

    public static void main(String[] args) {
    
    

        String[] files = {
    
    
                "/path/foo.txt",
                ".",
                "..",
                "/path/run.exe",
                "/path/makefile",
                "/path/.htaccess",
                "/path/.tar.gz",
                "/path/../makefile",
                "/path/dir.test/makefile"
        };

        for (String file : files) {
    
    
            String output = String.format(OUTPUT_FORMAT, file, getFileExtension(file));
            System.out.println(output);
        }

    }

    /**
     * Fail for below cases
     * <p>
     * "/path/../makefile",
     * "/path/dir.test/makefile"
     */
    public static String getFileExtension(String fileName) {
    
    
        if (fileName == null) {
    
    
            throw new IllegalArgumentException("fileName must not be null!");
        }

        String extension = "";

        int index = fileName.lastIndexOf('.');
        if (index > 0) {
    
    
            extension = fileName.substring(index + 1);
        }

        return extension;

    }

} 

输出

Terminal

 Path: /path/foo.txt                  -> File Extension: txt
Path: .                              -> File Extension:
Path: ..                             -> File Extension:
Path: /path/run.exe                  -> File Extension: exe
Path: /path/makefile                 -> File Extension:
Path: /path/.htaccess                -> File Extension: htaccess
Path: /path/.tar.gz                  -> File Extension: gz
Path: /path/../makefile              -> File Extension: /makefile
Path: /path/dir.test/makefile        -> File Extension: test/makefile 

2。获取文件扩展名,严格版本。

这个例子实现了额外的检查,因为目录包含一个点,文件没有扩展名。

 Path: /path/../makefile              -> File Extension:
  Path: /path/dir.test/makefile        -> File Extension: 

额外的检查确保最后一个文件扩展名索引(位置)总是在最后一个文件分隔符(Windows 或 Unix)之后。

 if (indexOfLastExtension > indexOflastSeparator) {
    
    
      extension = fileName.substring(indexOfLastExtension + 1);
  } 

完整的例子。

GetFileExtension2.java

 package com.mkyong.io.howto;

import java.util.Map;

public class GetFileExtension2 {
    
    

    private static final String OUTPUT_FORMAT = "Path: %-30s -> File Extension: %s";
    private static final String WINDOWS_FILE_SEPARATOR = "\\";
    private static final String UNIX_FILE_SEPARATOR = "/";
    private static final String FILE_EXTENSION = ".";

    public static void main(String[] args) {
    
    

        String[] files = {
    
    
                "/path/foo.txt",
                ".",
                "..",
                "/path/run.exe",
                "/path/makefile",
                "/path/.htaccess",
                "/path/.tar.gz",
                "/path/../makefile",
                "/path/dir.test/makefile"
        };

        for (String file : files) {
    
    
            String output = String.format(OUTPUT_FORMAT, file, getFileExtensionImproved(file));
            System.out.println(output);
        }

    }

    /**
     * Add extra checking for below cases
     * <p>
     * "/path/../makefile",
     * "/path/dir.test/makefile"
     */
    public static String getFileExtensionImproved(String fileName) {
    
    

        if (fileName == null) {
    
    
            throw new IllegalArgumentException("fileName must not be null!");
        }

        String extension = "";

        int indexOfLastExtension = fileName.lastIndexOf(FILE_EXTENSION);

        // check last file separator, windows and unix
        int lastSeparatorPosWindows = fileName.lastIndexOf(WINDOWS_FILE_SEPARATOR);
        int lastSeparatorPosUnix = fileName.lastIndexOf(UNIX_FILE_SEPARATOR);

        // takes the greater of the two values, which mean last file separator
        int indexOflastSeparator = Math.max(lastSeparatorPosWindows, lastSeparatorPosUnix);

        // make sure the file extension appear after the last file separator
        if (indexOfLastExtension > indexOflastSeparator) {
    
    
            extension = fileName.substring(indexOfLastExtension + 1);
        }

        return extension;

    }

} 

输出

Terminal

 Path: /path/foo.txt                  -> File Extension: txt
Path: .                              -> File Extension:
Path: ..                             -> File Extension:
Path: /path/run.exe                  -> File Extension: exe
Path: /path/makefile                 -> File Extension:
Path: /path/.htaccess                -> File Extension: htaccess
Path: /path/.tar.gz                  -> File Extension: gz
Path: /path/../makefile              -> File Extension:
Path: /path/dir.test/makefile        -> File Extension: 

3。获取文件扩展名,硬编码版本

这个例子展示了如何硬编码一些文件扩展名并显示预定义的结果。例如,对于文件扩展名.tar.gz,我们希望显示tar.gz,而不是gz

GetFileExtension3.java

 package com.mkyong.io.howto;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class GetFileExtension3 {
    
    

    private static final String OUTPUT_FORMAT = "Path: %-30s -> File Extension: %s";
    private static final String WINDOWS_FILE_SEPARATOR = "\\";
    private static final String UNIX_FILE_SEPARATOR = "/";
    private static final String FILE_EXTENSION = ".";
    private static final Map<String, String> KNOWN_EXTENSION = createKnownExtensionMap();

    public static void main(String[] args) {
    
    

        String[] files = {
    
    
                "/path/foo.txt",
                ".",
                "..",
                "/path/run.exe",
                "/path/makefile",
                "/path/.htaccess",
                "/path/.tar.gz",
                "/path/../makefile",
                "/path/dir.test/makefile"
        };

        for (String file : files) {
    
    
            String output = String.format(OUTPUT_FORMAT, file, getFileExtensionKnownExtension(file));
            System.out.println(output);
        }

    }

    public static String getFileExtensionImproved(String fileName) {
    
    

        if (fileName == null) {
    
    
            throw new IllegalArgumentException("fileName must not be null!");
        }

        String extension = "";

        int indexOfLastExtension = fileName.lastIndexOf(FILE_EXTENSION);

        int indexOflastSeparator = Math.max(
              fileName.lastIndexOf(WINDOWS_FILE_SEPARATOR),
              fileName.lastIndexOf(UNIX_FILE_SEPARATOR)
        );

        if (indexOfLastExtension > indexOflastSeparator) {
    
    
            extension = fileName.substring(indexOfLastExtension + 1);
        }

        return extension;

    }

    // hardcoded
    public static String getFileExtensionKnownExtension(final String fileName) {
    
    

        if (fileName == null) {
    
    
            throw new IllegalArgumentException("fileName must not be null!");
        }

        // if the file name is end with the hard coded extension.
        // Java 8 stream, loop map if key matches get value
        String extension = KNOWN_EXTENSION
                .entrySet()
                .stream()
                .filter(x -> fileName.endsWith(x.getKey()))
                .map(x -> x.getValue())
                .collect(Collectors.joining());

        if ("".equals(extension)) {
    
    
            extension = getFileExtensionImproved(fileName); // see example 2
        }

        return extension;

    }

    private static Map<String, String> createKnownExtensionMap() {
    
    
        Map<String, String> result = new HashMap<>();
        result.put(".tar.gz", "tar.gz");    // if .tar.gz, gets tar.gz
        result.put("makefile", "make");     // if makefile, get make
        //...extra
        return result;
    }

} 

输出

Terminal

 Path: /path/foo.txt                  -> File Extension: txt
Path: .                              -> File Extension:
Path: ..                             -> File Extension:
Path: /path/run.exe                  -> File Extension: exe
Path: /path/makefile                 -> File Extension: make
Path: /path/.htaccess                -> File Extension: htaccess
Path: /path/.tar.gz                  -> File Extension: tar.gz
Path: /path/../makefile              -> File Extension: make
Path: /path/dir.test/makefile        -> File Extension: make 

4。阿帕奇通用 IO

对于 Apache commons-io,我们可以使用FilenameUtils.getExtension(fileName)来获取一个文件的文件扩展名。

pom.xml

 <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.7</version>
  </dependency> 

完整的例子。

GetFileExtension4.java

 package com.mkyong.io.howto;

import org.apache.commons.io.FilenameUtils;

public class GetFileExtension4 {
    
    

    private static final String OUTPUT_FORMAT = "Path: %-30s -> File Extension: %s";

    public static void main(String[] args) {
    
    

        String[] files = {
    
    
                "/path/foo.txt",
                ".",
                "..",
                "/path/run.exe",
                "/path/makefile",
                "/path/.htaccess",
                "/path/.tar.gz",
                "/path/../makefile",
                "/path/dir.test/makefile"
        };

        for (String file : files) {
    
    
            String output = String.format(OUTPUT_FORMAT, file, FilenameUtils.getExtension(fileName));
            System.out.println(output);
        }

    }

} 

输出

Terminal

 Path: /path/foo.txt                  -> File Extension: txt
Path: .                              -> File Extension:
Path: ..                             -> File Extension:
Path: /path/run.exe                  -> File Extension: exe
Path: /path/makefile                 -> File Extension:
Path: /path/.htaccess                -> File Extension: htaccess
Path: /path/.tar.gz                  -> File Extension: gz
Path: /path/../makefile              -> File Extension:
Path: /path/dir.test/makefile        -> File Extension: 

下载源代码

$ git 克隆https://github.com/mkyong/core-java

$ cd java-io

参考文献