Mkyong-中文博客翻译-五-

Mkyong 中文博客翻译(五)

原文:Mkyong

协议:CC BY-NC-SA 4.0

Java——如何在列表中搜索字符串?

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/java/java-how-to-search-a-string-in-a-list/

在 Java 中,我们可以将一个普通的循环和.contains().startsWith().matches()结合起来,在ArrayList中搜索一个字符串。

JavaExample1.java

 package com.mkyong.test;

import java.util.ArrayList;
import java.util.List;

public class JavaExample1 {

    public static void main(String[] args) {

        List<String> list = new ArrayList<>();
        list.add("Java");
        list.add("Kotlin");
        list.add("Clojure");
        list.add("Groovy");
        list.add("Scala");

        List<String> result = new ArrayList<>();
        for (String s : list) {
            if (s.contains("Java")) {
                result.add(s);
            }

            /*
            if (s.startsWith("J")) {
                result.add(s);
            }
            */

            /* regex
            if (s.matches("(?i)j.*")) {
                result.add(s);
            }
            */
        }

        System.out.println(result);

    }

} 

输出

 [Java] 

对于 Java 8,现在就简单多了。

JavaExample2.java

 package com.mkyong.test;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class JavaExample2 {

    public static void main(String[] args) {

        List<String> list = new ArrayList<>();
        list.add("Java");
        list.add("Kotlin");
        list.add("Clojure");
        list.add("Groovy");
        list.add("Scala");

        List<String> result = list
                .stream()
                .filter(x -> x.contains("Java"))
                .collect(Collectors.toList());

        System.out.println(result);

    }

} 

输出

 [Java] 

参考

Java——如何对所有流整数求和

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/java8/java-how-to-sum-all-the-stream-integers/

sum()方法在原始 int-value 流中可用,如IntStream,而不是Stream<Integer>。我们可以使用mapToInt()将一个流整数转换成一个IntStream

 int sum = integers.stream().mapToInt(Integer::intValue).sum();
int sum = integers.stream().mapToInt(x -> x).sum(); 

完整的例子。

Java8Stream.java

 package com.mkyong.concurrency;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class Java8Stream {

    public static void main(String[] args) {

        List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        int sum = integers.stream().mapToInt(Integer::intValue).sum();
        System.out.println("Total : " + sum);

        Stream<Integer> integers2 = Stream.iterate(1, n -> n + 1).limit(10);
        IntStream intStream = integers2.mapToInt(x -> x);
        int sum1 = intStream.sum();
        System.out.println("Total : " + sum1);

    }

} 

输出

 Total : 55
Total : 55 

参考

  1. 甲骨文文件–IntStream.html

Tags : java 8 sum

Java I/O 教程

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/tutorials/java-io-tutorials/

Java I/O Tutorials

Java 附带了许多方便的 I/O 类来支持字节流和文件系统的输入和输出。以下是 Java I/O 示例列表,包括文件、临时文件和目录操作、编码、序列化以及 zip 或 Gzip 压缩。

快乐学习 Java I/O🙂

文件

文件示例列表,显示使用 Java I/O 创建、读取、写入、修改文件以及获取文件信息。

文件序列化

取任意一个实现序列化接口的对象,转换成字节,存入文件;该文件可以在以后完全还原回原始对象。

文件压缩

文件压缩示例,ZIP 和 GZip。

暂存文件

临时文件操作示例列表。

目录

目录操作示例列表。

控制台 IO

控制台 IO 示例列表。

Java I/O 参考

Java JSON 教程

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/tutorials/java-json-tutorials/

json logo

JSON(JavaScript Object Notation)是一种简单、轻量且易于读写的数据交换格式。在 Java 中,通常我们使用杰克森Gson 来解析 JSON。

1.杰克逊

使用 Jackson 2.9.8 测试

2.Gson

使用 Gson 2.8.5 测试

3.法斯特森

用 FastJson 1.2.57 测试

常见问题

参考

java.lang.ClassFormatError:类文件中非本机或抽象的方法中缺少代码属性…

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/hibernate/java-lang-classformaterror-absent-code-attribute-in-method-that-is-not-native-or-abstract-in-class-file/

问题

一个非常奇怪和罕见的问题,发生在 JPA 或 Hibernate 开发中。

 Caused by: java.lang.ClassFormatError: Absent Code attribute in method that is 
        not native or abstract in class file javax/persistence/GenerationType

	at java.lang.ClassLoader.defineClass1(Native Method)
	at java.lang.ClassLoader.defineClassCond(Unknown Source)
	at java.lang.ClassLoader.defineClass(Unknown Source)
	at java.security.SecureClassLoader.defineClass(Unknown Source)
	at java.net.URLClassLoader.defineClass(Unknown Source)
	at java.net.URLClassLoader.access$000(Unknown Source)
	at java.net.URLClassLoader$1.run(Unknown Source)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.net.URLClassLoader.findClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknow 

解决办法

这总是由位于 Java.net 的 javaee.jar 引起的。许多开发人员喜欢用下面的 Maven 坐标抓取 javaee.jar :

 <repositories>
  	<repository>
  		<id>Java.Net</id>
  		<url>http://download.java.net/maven/2/</url>
  	</repository>
  </repositories>

  <dependencies>
    <!-- Javaee API -->
	<dependency>
    	<groupId>javax</groupId>
    	<artifactId>javaee-api</artifactId>
    	<version>6.0</version>
	</dependency>
  </dependencies> 

但是,来自 java.net 的 javaee.jar 不包含任何方法体,只包含 API 名称。它不适合与您的应用程序一起运行或部署。

The good practice is always get the original full version of javaee.jar file from the http://java.sun.com/javaee/. Just download and install the J2EE SDK, and the javaee.jar can be found in the “\J2EE_SDK_FOLDER\lib” folder. Include it into your local Maven repository or poject classpath will get rid of the above error message. ## 参考

  1. http://weblogs . Java . net/blog/ludo/archive/2007/01/Java _ ee _ 5 _ APIs . html
  2. http://forums.java.net/jive/message.jspa?messageID=226931
  3. http://jersey . 576304 . N2 . nable . com/Absent-Code-attribute-in-method-that-is-not-native-TD 2632542 . html

hibernate jpa

Java . lang . classnotfoundexception:javassist . util . proxy . method filter

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/hibernate/java-lang-classnotfoundexception-javassist-util-proxy-methodfilter/

问题

使用 Hibernate 3.6.3,但是遇到这个 javassist not found 错误,错误堆栈见下文:

 Caused by: java.lang.NoClassDefFoundError: javassist/util/proxy/MethodFilter
	...
	at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:77)
	... 16 more
Caused by: java.lang.ClassNotFoundException: javassist.util.proxy.MethodFilter
	at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
	at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
	at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
	... 21 more 

解决办法

javassist.jar 缺失,可以从JBoss Maven repository获取最新。

文件:pom.xml

 <project ...>
	<repositories>
		<repository>
			<id>JBoss repository</id>
			<url>http://repository.jboss.org/nexus/content/groups/public/</url>
		</repository>
	</repositories>

	<dependencies>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>3.6.3.Final</version>
		</dependency>

		<dependency>
			<groupId>javassist</groupId>
			<artifactId>javassist</artifactId>
			<version>3.12.1.GA</version>
		</dependency>

	</dependencies>
</project> 

hibernate (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190224165917/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

Java . lang . classnotfoundexception:javax . El . expression factory

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jsf2/java-lang-classnotfoundexception-javax-el-expressionfactory/

问题

部署在 Tomcat 中的一个 Java web 应用程序点击了以下错误消息:

 javax.servlet.ServletException: java.lang.NoClassDefFoundError: javax/el/ExpressionFactory
	org.apache.jasper.servlet.JspServlet.service(JspServlet.java:268)
	//...
java.lang.ClassNotFoundException: javax.el.ExpressionFactory
	java.net.URLClassLoader$1.run(URLClassLoader.java:200)
	java.security.AccessController.doPrivileged(Native Method)
	java.net.URLClassLoader.findClass(URLClassLoader.java:188)
	//...
	javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
note The full stack trace of the root cause is available in the Apache Tomcat/6.0.26 logs. 

解决办法

javax . El . expression factory”类属于“ el-api.jar ”库,可以从 Maven central repository 下载。

 <dependency>
	<groupId>org.glassfish.web</groupId>
	<artifactId>el-impl</artifactId>
	<version>2.2</version>
</dependency> 

可选择的解决方案

在某些情况下,即使包含了“ el-api.jar ”文件,Tomcat 仍然会提示相同的错误消息。然后你可以尝试包含 J2EE 标准 API 库,“ javaee.jar ”,它包含“javax . El . expression factory”类也一样,至少这对我来说是管用的。

Note
This “javaee.jar” could be find in your J2EE SDK folder.

对于 Eclipse IDE

如果您正在调试,请确保您的服务器实例能够找到javaee.jar文件。

javax.el.ExpressionFactory

或者您可以通过以下步骤自己添加

  1. 双击服务器实例。
  2. 点击“打开启动配置”。
  3. 在“引导入口”中添加javaee.jar

参考

  1. 如何从 Maven 下载 javaee.jar】

Tags : jsf2

Java . lang . classnotfoundexception:javax . persistence . entity

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/hibernate/java-lang-classnotfoundexception-javax-persistence-entity/

问题

在 JPA 或 Hibernate 开发中,它会显示以下错误消息:

 Caused by: java.lang.ClassNotFoundException: javax.persistence.Entity
	at java.net.URLClassLoader$1.run(Unknown Source)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.net.URLClassLoader.findClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	... 24 more 

解决办法

javax.persistence.Entity 是 J2EE SDK 库“ javaee.jar 中的一个类,您的项目类路径中缺少这个 jar 文件。

1.J2EE SDK

你总是可以从 http://java.sun.com/javaee/的 T2 那里得到 javaee.jar。在你的电脑中下载并安装 SDK, javaee.jar 可以在“\ J2EE _ SDK _ 文件夹\lib”文件夹中找到。举个例子,

 C:\Sun\SDK\lib\javaee.jar 

获取 javaee.jar 文件,并将其包含在项目类路径中。

2.Java.Net 知识库

或者,您可以从 java.net 专家那里获得" javaee.jar "

 <repositories>
  	<repository>
  		<id>Java.Net</id>
  		<url>http://download.java.net/maven/2/</url>
  	</repository>
  </repositories>

  <dependencies>
    <!-- Javaee API -->
	<dependency>
    	<groupId>javax</groupId>
    	<artifactId>javaee-api</artifactId>
    	<version>6.0</version>
	</dependency>
  </dependencies> 

The downloaded java.net javaee.jar is not contains any method bodies, see this “how to get javaee.jar from Maven” article for detail.

Java . lang . classnotfoundexception:javax . servlet . JSP . jstl . core . config

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jsf2/java-lang-classnotfoundexception-javax-servlet-jsp-jstl-core-config/

问题

将 JSF 2.0 web 应用程序部署到 Tomcat 6.0.26 时,遇到以下 jstl 类未找到错误。

 java.lang.NoClassDefFoundError: javax/servlet/jsp/jstl/core/Config
	...
Caused by: java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config
	... 18 more 

freestar.config.enabled_slots.push({ placementName: "mkyong_leaderboard_atf", slotId: "mkyong_leaderboard_atf" });

解决办法

默认情况下,Tomcat 容器不包含任何 jstl 库。为了修复它,在 Maven pom.xml文件中声明 jstl.jar

 <dependency>
	<groupId>javax.servlet</groupId>
	<artifactId>jstl</artifactId>
	<version>1.2</version>
  </dependency> 

Note
Please refer to this JSF 2.0 release note to identify the JSF 2.0 required dependency libraries.Tags : jsf2freestar.config.enabled_slots.push({ placementName: "mkyong_leaderboard_btf", slotId: "mkyong_leaderboard_btf" });

Java . lang . classnotfoundexception:javax . transaction . transaction manager

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/hibernate/java-lang-classnotfoundexception-javax-transaction-transactionmanager/

问题

在 JPA 或 Hibernate 开发中,它会显示以下错误消息:

 Caused by: java.lang.ClassNotFoundException: javax.transaction.TransactionManager
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
… 23 more 

解决办法

javax . transaction . transaction manager是 J2EE SDK 库“ javaee.jar ”中的一个类,您的项目类路径中缺少这个 jar 文件。

1.J2EE SDK

你总是可以从 http://java.sun.com/javaee/的 T2 那里得到 javaee.jar。在你的电脑中下载并安装 SDK, javaee.jar 可以在“\ J2EE _ SDK _ 文件夹\lib”文件夹中找到。举个例子,

 C:\Sun\SDK\lib\javaee.jar 

获取 javaee.jar 文件,并将其包含在项目类路径中。

2.Java.Net 知识库

或者,您可以从 java.net 专家那里获得" javaee.jar "

 <repositories>
  	<repository>
  		<id>Java.Net</id>
  		<url>http://download.java.net/maven/2/</url>
  	</repository>
  </repositories>

  <dependencies>
    <!-- Javaee API -->
	<dependency>
    	<groupId>javax</groupId>
    	<artifactId>javaee-api</artifactId>
    	<version>6.0</version>
	</dependency>
  </dependencies> 

The downloaded java.net javaee.jar is not contains any method bodies, see this “how to get javaee.jar from Maven” article for detail.

Java . lang . classnotfoundexception:org . Apache . struts . action . forward action

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/java-lang-classnotfoundexception-org-apache-struts-action-forwardaction/

问题

一个超级常见的 Struts 错误消息,找不到org . Apache . Struts . action . forward action类。

 javax.servlet.ServletException: java.lang.ClassNotFoundException: org.apache.struts.action.ForwardAction
	org.apache.struts.chain.ComposableRequestProcessor.process(ComposableRequestProcessor.java:286)
	org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
	org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:449)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:718)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:831)

root cause

java.lang.ClassNotFoundException: org.apache.struts.action.ForwardAction
	org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1516)
	org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1361)
	org.apache.struts.chain.commands.util.ClassUtils.getApplicationClass(ClassUtils.java:54)
	org.apache.struts.chain.commands.util.ClassUtils.getApplicationInstance(ClassUtils.java:71)
	org.apache.struts.chain.commands.servlet.CreateAction.createAction(CreateAction.java:98)
	org.apache.struts.chain.commands.servlet.CreateAction.getAction(CreateAction.java:68)
	org.apache.struts.chain.commands.AbstractCreateAction.execute(AbstractCreateAction.java:91)
	org.apache.struts.chain.commands.ActionCommandBase.execute(ActionCommandBase.java:51)
	org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:191)
	org.apache.commons.chain.generic.LookupCommand.execute(LookupCommand.java:305)
	org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:191)
	org.apache.struts.chain.ComposableRequestProcessor.process(ComposableRequestProcessor.java:283)
	org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
	org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:449)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:718)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:831) 

解决办法

ForwardAction 类打包在org . Apache . struts . actions . forward action中,而不是org . Apache . struts . action . forward action中,后面带“s”的动作。

struts (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190308095632/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

Java . lang . classnotfoundexception:org . slf4j . impl . staticloggerbinder

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/wicket/java-lang-classnotfoundexception-org-slf4j-impl-staticloggerbinder/

问题

当启动一个 Wicket web 应用程序时,它显示以下错误消息:

 java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder
	at org.slf4j.LoggerFactory.getSingleton(LoggerFactory.java:223)
	at org.slf4j.LoggerFactory.bind(LoggerFactory.java:120)
	at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:111)
	at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:269)
	at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:242)
	...
Caused by: java.lang.ClassNotFoundException: org.slf4j.impl.StaticLoggerBinder
	at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1516)
	at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1361)
	at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
	... 31 more 

解决办法

在 Wicket 开发中,你必须添加 SLF4j 日志实现,否则将无法启动。为了解决这个问题,在 Maven pom.xml文件中声明了 slf4j。

如果使用 log4j,那么声明 slf4j log4j 绑定:

 <dependency>
	<groupId>org.slf4j</groupId>
	<artifactId>slf4j-log4j12</artifactId>
	<version>1.5.6</version>
</dependency> 

For non-Maven users
Just download the library and put it into your project classpath.

参考

  1. SLF4j 参考

Java . lang . classnotfoundexception:org . spring framework . transaction . transaction exception

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/spring/java-lang-classnotfoundexception-org-springframework-transaction-transactionexception/

用 Spring 3 开发 Quartz,并点击以下错误信息。

 Caused by: 
       java.lang.NoClassDefFoundError: org/springframework/transaction/TransactionException
	at java.lang.Class.getDeclaredConstructors0(Native Method)
	at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389)
	at java.lang.Class.getConstructor0(Class.java:2699)
	at java.lang.Class.getDeclaredConstructor(Class.java:1985)
        .....
Caused by: java.lang.ClassNotFoundException: org.springframework.transaction.TransactionException
	at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1711)
	at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1556)
	... 29 more 

解决办法

与 Quartz 无关,上面的错误消息表明您需要 Spring 事务依赖。要修复它,只需包含spring-tx.jar

例如,pom.xml

 <dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-tx</artifactId>
	<version>3.1.2.RELEASE</version>
   </dependency> 

spring (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190205233956/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

Java . lang . illegalargumentexception:javax . faces . context . exception handlerfactory

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jsf2/java-lang-illegalargumentexception-javax-faces-context-exceptionhandlerfactory/

问题

在 Eclipse IDE 中,将 JSF 2.0 web 应用程序部署到 Tomcat 6.0.26 时,遇到以下异常,无法启动 Tomcat 服务器。

P.S 两个 jsf-api-2.1.0-b03.jarjsf-impl-2.1.0-b03.jar 库都包含在项目类路径中。

 INFO: Unsanitized stacktrace from failed start...
java.lang.IllegalArgumentException: javax.faces.context.ExceptionHandlerFactory
	at javax.faces.FactoryFinder.validateFactoryName(FactoryFinder.java:630)
	at javax.faces.FactoryFinder.setFactory(FactoryFinder.java:287)
	...
SEVERE: Critical error during deployment: 
com.sun.faces.config.ConfigurationException: 
CONFIGURATION FAILED! javax.faces.context.ExceptionHandlerFactory
	...
Caused by: java.lang.IllegalArgumentException: javax.faces.context.ExceptionHandlerFactory
	at javax.faces.FactoryFinder.validateFactoryName(FactoryFinder.java:630)
	... 

解决办法

在 Eclipse 调试模式下,深入源代码内部,找出 FactoryFinder 的 getFactory() 方法抛出的 IllegalArgumentException

FactoryFinder.java

 /*
 * @throws IllegalArgumentException if <code>factoryName</code> does not
 *                                  identify a standard JavaServer Faces factory name
 * @throws IllegalStateException    if there is no configured factory
 *                                  implementation class for the specified factory name
 * @throws NullPointerException     if <code>factoryname</code>
 *                                  is null
 */

 public static Object getFactory(String factoryName)
         throws FacesException {

        validateFactoryName(factoryName);
        //...
 } 

IllegalArgumentException 记录了因子查找器无法识别新的 JSF 2.0exception handler factory工厂名称。

经过上千次的测试和尝试,我终于找到了问题的根源,那就是我的项目类路径中包含的 javaee.jar 。看看 javaee.jar 里面,它也包含了一套 JSF 1.2 api,看起来 Tomcat 选择了这个 JSF 1.2 api,而不是我的新的 JSF 2.0 api。

在从项目类路径中移除 javaee.jar 之后,JSF 2.0 web 应用程序能够在 Tomcat 上启动并运行良好。

参考

  1. factory finder . html # get factory Javadoc
  2. JSF 2.0.3 发行说明

jsf2

Java . lang . noclassdeffounderror:org/Apache/commons/file upload/file upload exception

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/java-lang-noclassdeffounderror-orgapachecommonsfileuploadfileuploadexception/

问题

在 Struts 框架中,在文件上传过程中遇到以下异常。

 javax.servlet.ServletException: Servlet execution threw an exception

root cause

java.lang.NoClassDefFoundError: org/apache/commons/fileupload/FileUploadException
	java.lang.Class.getDeclaredConstructors0(Native Method)
	java.lang.Class.privateGetDeclaredConstructors(Unknown Source)
	java.lang.Class.getConstructor0(Unknown Source)
	java.lang.Class.newInstance0(Unknown Source)
	java.lang.Class.newInstance(Unknown Source) 

解决办法

Struts 使用“ commons-fileupload.jar ”库进行文件上传过程。您必须将此库包含到项目依赖项库文件夹中。

1.从 http://commons.apache.org/fileupload/官方网站获取“ commons-fileupload.jar

2.从 Maven 存储库中获取" commons-fileupload.jar "

 <dependency>
      <groupId>commons-fileupload</groupId>
	  <artifactId>commons-fileupload</artifactId>
      <version>1.2.1</version>
    </dependency> 

struts (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190223081913/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

Java . lang . noclassdeffounderror:org/Apache/commons/io/output/DeferredFileOutputStream

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/java-lang-noclassdeffounderror-orgapachecommonsiooutputdeferredfileoutputstream/

问题

在 Struts 框架中执行一些 I/O 操作,但是在文件上传过程中遇到以下异常。

 java.lang.NoClassDefFoundError: 
        org/apache/commons/io/output/DeferredFileOutputStream 

从哪里下载 Apache commons-io?

解决办法

默认情况下,Struts 使用 Apache " commons-io.jar "进行文件上传。要修复它,您必须将此库包含到项目依赖库文件夹中。

1.直接得到

http://commons.apache.org/io/官方网站获取“ commons-io.jar

2.从 Maven 获取

更好的方法是从 Maven 存储库中获取" commons-io.jar "

文件:pom.xml

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

struts

Java . lang . nosuchmethod error:org . object web . ASM . class writer

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/hibernate/java-lang-nosuchmethoderror-org-objectweb-asm-classwriter/

问题

在 Hibernate 开发中,经常会遇到以下错误消息。

 SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: 
Error creating bean with name 'sessionFactory' defined in ServletContext resource 
[/WEB-INF/classes/config/database/spring/HibernateSessionFactory.xml]: 
Invocation of init method failed; nested exception is 

Caused by: org.hibernate.HibernateException: 
Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]
	...
	...
Caused by: java.lang.reflect.InvocationTargetException
	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
	...
Caused by: java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(I)V
	at net.sf.cglib.core.DebuggingClassWriter.<init>(DebuggingClassWriter.java:47)
	... 

解决办法

无法实例化默认的 tu plizer[org . hibernate . tuple . entity . pojoentitytuplizer”是一个一般性的错误消息,它可能由多种原因引起。因此,您必须查看导致错误的最后一行。

 Caused by: java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter 

主要原因是旧的 asm.jar 库例如“asm-1.5.3.jar”,只需将 asm 库升级到最新版本就可以摆脱错误信息。例如,“asm-3.1.jar”。

参考

  1. ASM 图书馆官方网站

hibernate

Java . lang . unsupportedclassversionerror

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/java/java-lang-unsupportedclassversionerror/

启动一个 Java 类,点击这个java.lang.UnsupportedClassVersionError,什么是类文件版本 52 56?

 Error: A JNI error has occurred, please check your installation and try again

Exception in thread "main" java.lang.UnsupportedClassVersionError: 
TestHello has been compiled by a more recent version of the Java Runtime (class file version 56.0), 
this version of the Java Runtime only recognizes class file versions up to 52.0
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:468)
        at java.net.URLClassLoader.access$100(URLClassLoader.java:74)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:369)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:363)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:362)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:495) 

解决办法

Java 版本不匹配,这意味着你用JDK 12 (56)编译 Java 类,但试图在JDK 8 (52)中运行,从维基百科中阅读

 Java SE 13 = 57 (0x39 hex)
Java SE 12 = 56 (0x38 hex)
Java SE 11 = 55 (0x37 hex)
Java SE 10 = 54 (0x36 hex)
Java SE 9 = 53 (0x35 hex)
Java SE 8 = 52 (0x34 hex)
Java SE 7 = 51 (0x33 hex)
Java SE 6.0 = 50 (0x32 hex)
Java SE 5.0 = 49 (0x31 hex)
JDK 1.4 = 48 (0x30 hex)
JDK 1.3 = 47 (0x2F hex)
JDK 1.2 = 46 (0x2E hex)
JDK 1.1 = 45 (0x2D hex) 

修复,用--release选项编译 Java 类,目标是 Java 8。

 javac anyName.java --release 8 

或者 Maven。

pom.xml

 <plugin>
		<groupId>org.apache.maven.plugins</groupId>
		<artifactId>maven-compiler-plugin</artifactId>
		<version>3.8.0</version>
		<configuration>
			<source>1.8</source>
			<target>1.8</target>
		</configuration>
	</plugin> 

Note
The key is to make sure both the compile and runtime is using the same JDK.

参考

Java MongoDB:将 JSON 数据转换为 DBObject

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/mongodb/java-mongodb-convert-json-data-to-dbobject/

MongoDB 附带了“ com.mongodb.util.JSON ”类,将 JSON 数据直接转换为 DBObject。例如,数据以 JSON 格式表示:

 {
	'name' : 'mkyong',
	'age' : 30
} 

要将其转换为 DBObject,可以编写如下代码:

 DBObject dbObject = (DBObject) JSON.parse("{'name':'mkyong', 'age':30}"); 
例子

查看完整的示例,将上述 JSON 数据转换为 DBObject,并保存到 MongoDB 中。

 package com.mkyong.core;

import java.net.UnknownHostException;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.util.JSON;

/**
 * Java MongoDB : Convert JSON data to DBObject
 * 
 */

public class App {
	public static void main(String[] args) {

		try {

			Mongo mongo = new Mongo("localhost", 27017);
			DB db = mongo.getDB("yourdb");
			DBCollection collection = db.getCollection("dummyColl");

			// convert JSON to DBObject directly
			DBObject dbObject = (DBObject) JSON
					.parse("{'name':'mkyong', 'age':30}");

			collection.insert(dbObject);

			DBCursor cursorDoc = collection.find();
			while (cursorDoc.hasNext()) {
				System.out.println(cursorDoc.next());
			}

			System.out.println("Done");

		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (MongoException e) {
			e.printStackTrace();
		}
	}
} 

输出

 { "_id" : { "$oid" : "4dc9ebb5237f275c2fe4959f"} , "name" : "mkyong" , "age" : 30}
Done 

Tags : convert json mongodb

Java MongoDB:删除文档

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/mongodb/java-mongodb-delete-document/

在本教程中,我们将向您展示如何使用collection.remove()从集合中删除文档。

1.测试数据

从 1 号到 10 号插入 10 份文件进行测试。

 for (int i=1; i <= 10; i++) {
    collection.insert(new BasicDBObject().append("number", i));
} 

2.DBCollection.remove()

参见下面删除文档的代码片段。

示例 1

获取第一个文档并删除它。在这种情况下,number = 1 被删除。

 DBObject doc = collection.findOne(); //get first document
	collection.remove(doc); 
示例 2

将查询放在一个BasicDBObject中。在这种情况下,number = 2 被删除。

 BasicDBObject document = new BasicDBObject();
	document.put("number", 2);
	collection.remove(document); 

And Operator?

两个常见错误:

1.像这样的查询只删除数字= 3。

 BasicDBObject document = new BasicDBObject();
	document.put("number", 2);
        document.put("number", 3); //override above value 2
	collection.remove(document); 

2.下面的尝试很好,但是像这样的查询不起作用,它不会删除任何东西。

 BasicDBObject document = new BasicDBObject();
	List<Integer> list = new ArrayList<Integer>();
	list.add(7);
	list.add(8);
	document.put("number", list);
	collection.remove(document); 

对于“与”查询,需要使用“\(in”或“\)and”运算符,参见例 5。

示例 3

直接用BasicDBObject。在这种情况下,number = 3 被删除。

 collection.remove(new BasicDBObject().append("number", 3)); 
实例 4

将一个$gt操作符放在一个BasicDBObject对象中。在这种情况下,number = 10 被删除。

 BasicDBObject query = new BasicDBObject();
	query.put("number", new BasicDBObject("$gt", 9));
	collection.remove(query); 
实例 5

将一个$in操作符放在一个BasicDBObject对象中,在 ArrayList 中构造查询。在这种情况下,number = 4 和 number = 5 被删除。

 BasicDBObject query2 = new BasicDBObject();
	List<Integer> list = new ArrayList<Integer>();
	list.add(4);
	list.add(5);
	query2.put("number", new BasicDBObject("$in", list));
	collection.remove(query2); 

More MongoDB Operators
For more operators, read this MongoDB operators quick reference.

实例 6

使用光标删除所有可用的文档。(不推荐,首选示例 7)

 DBCursor cursor = collection.find();
	while (cursor.hasNext()) {
		collection.remove(cursor.next());
	} 
例 7

传递一个空的 BasicDBObject,整个文档将被删除。

 collection.remove(new BasicDBObject()); 
实施例 8

它删除整个文档并丢弃集合。

 collection.drop(); 
示例 9

remove()将返回一个WrireResult对象,它包含关于移除操作的有用信息。您可以使用getN()来获取受影响的文档数量。

 WriteResult result = collection.remove(query2);
       System.out.println("Number of documents are deleted : " + result.getN()); 

3.完整示例

完整的例子显示了不同的方式来删除文件。

 package com.mkyong.core;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

/**
 * Java MongoDB : Delete document
 * @author mkyong
 */

public class App {
    public static void main(String[] args) {

      try {

	Mongo mongo = new Mongo("localhost", 27017);
	DB db = mongo.getDB("yourdb");

	// get a single collection
	DBCollection collection = db.getCollection("dummyColl");

	//insert number 1 to 10 for testing
	for (int i=1; i <= 10; i++) {
		collection.insert(new BasicDBObject().append("number", i));
	}

	//remove number = 1
	DBObject doc = collection.findOne(); //get first document
	collection.remove(doc);

	//remove number = 2
	BasicDBObject document = new BasicDBObject();
	document.put("number", 2);
	collection.remove(document);

	//remove number = 3
	collection.remove(new BasicDBObject().append("number", 3));

	//remove number > 9 , means delete number = 10
	BasicDBObject query = new BasicDBObject();
	query.put("number", new BasicDBObject("$gt", 9));
	collection.remove(query);

	//remove number = 4 and 5
	BasicDBObject query2 = new BasicDBObject();
	List<Integer> list = new ArrayList<Integer>();
	list.add(4);
	list.add(5);
	query2.put("number", new BasicDBObject("$in", list));
	collection.remove(query2);

	//print out the document
	DBCursor cursor = collection.find();
        while(cursor.hasNext()) {
             System.out.println(cursor.next());
        }

        collection.drop();

        System.out.println("Done");

      } catch (UnknownHostException e) {
	e.printStackTrace();
      } catch (MongoException e) {
	e.printStackTrace();
      }

   }
} 

输出...

 { "_id" : { "$oid" : "4dc7a6989e3a66c5faeee757"} , "number" : 6}
{ "_id" : { "$oid" : "4dc7a6989e3a66c5faeee758"} , "number" : 7}
{ "_id" : { "$oid" : "4dc7a6989e3a66c5faeee759"} , "number" : 8}
{ "_id" : { "$oid" : "4dc7a6989e3a66c5faeee75a"} , "number" : 9}
Done 

参考

  1. MongoDB 操作员快速参考
  2. MongoDB write result JavaDoc

delete mongodb

Java MongoDB:从数据库获取集合

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/mongodb/java-mongodb-get-collection-from-database/

在 Java 中,可以使用db . get collection(" your collection name ")来获得一个要使用的集合。

 DBCollection collection = db.getCollection("yourCollection"); 

如果您不知道集合名称,请使用 db.getCollectionNames() 从选定的数据库中获取集合名称的完整列表。

 DB db = mongo.getDB("yourdb");
Set<String> collections = db.getCollectionNames();

for (String collectionName : collections) {
	System.out.println(collectionName);
} 

如果“yourdb”包含集合名称“yourCollection ”,那么您将看到以下结果:

 system.indexes  //system collection
system.users     //system colection
yourCollection 

通过 Java 驱动程序从 MongoDB 获取集合的完整示例。

 package com.mkyong.core;

import java.net.UnknownHostException;
import java.util.Set;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

/**
 * Java : Get collection from MongoDB
 * 
 */
public class GetCollectionApp {
  public static void main(String[] args) {

    try {

	Mongo mongo = new Mongo("localhost", 27017);
	DB db = mongo.getDB("yourdb");

	// get list of collections
	Set<String> collections = db.getCollectionNames();

	for (String collectionName : collections) {
		System.out.println(collectionName);
	}

	// get a single collection
	DBCollection collection = db.getCollection("yourCollection");
	System.out.println(collection.toString());

	System.out.println("Done");

    } catch (UnknownHostException e) {
	e.printStackTrace();
    } catch (MongoException e) {
	e.printStackTrace();
    }

  }
} 

mongodb query select (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190205025832/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

Java + MongoDB hello world 示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/mongodb/java-mongodb-hello-world-example/

Java mongodb hello world

一个简单的 Java + MongoDB hello world 例子——如何连接、创建数据库、集合和文档、保存、更新、删除、获取和显示文档(数据)。

使用的工具和技术:

  1. MongoDB 2.2.3
  2. MongoDB-Java-驱动程序 2.10.1
  3. JDK 1.6
  4. Maven 3.0.3
  5. Eclipse 4.2

P.S Maven 和 Eclipse 都是可选的,只是我个人最喜欢的开发工具。

1.创建一个 Java 项目

用 Maven 创建一个简单的 Java 项目

 mvn archetype:generate -DgroupId=com.mkyong.core -DartifactId=mongodb 
  -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false 

2.获取 Mongo Java 驱动程序

github 下载 mongo-java 驱动。对于 Maven 用户,mongo-java 驱动程序在pom.xml中声明。

pom.xml

 <project ...>
  <dependencies>

	<dependency>
		<groupId>org.mongodb</groupId>
		<artifactId>mongo-java-driver</artifactId>
		<version>2.10.1</version>
	</dependency>

  </dependencies>

  <build>
	<plugins>
		<plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-compiler-plugin</artifactId>
			<version>2.3.1</version>
			<configuration>
				<source>1.6</source>
				<target>1.6</target>
			</configuration>
		</plugin>
	        <plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-eclipse-plugin</artifactId>
			<configuration>
				<downloadSources>true</downloadSources>
				<downloadJavadocs>true</downloadJavadocs>
			</configuration>
		</plugin>

	</plugins>
  </build>

</project> 

3.Mongo 连接

连接到 MongoDB 服务器。对于 MongoDB 版本> = 2.10.0,使用MongoClient

 // Old version, uses Mongo
	Mongo mongo = new Mongo("localhost", 27017);

	// Since 2.10.0, uses MongoClient
	MongoClient mongo = new MongoClient( "localhost" , 27017 ); 

如果 MongoDB 处于安全模式,则需要身份验证。

 MongoClient mongoClient = new MongoClient();
	DB db = mongoClient.getDB("database name");
	boolean auth = db.authenticate("username", "password".toCharArray()); 

4.Mongo 数据库

获取数据库。如果数据库不存在,MongoDB 会为您创建一个。

 DB db = mongo.getDB("database name"); 

显示所有数据库。

 List<String> dbs = mongo.getDatabaseNames();
	for(String db : dbs){
		System.out.println(db);
	} 

5.Mongo 系列

获取集合/表格。

 DB db = mongo.getDB("testdb");
	DBCollection table = db.getCollection("user"); 

显示所选数据库中的所有集合。

 DB db = mongo.getDB("testdb");
	Set<String> tables = db.getCollectionNames();

	for(String coll : tables){
		System.out.println(coll);
	} 

Note
In RDBMS, collection is equal to table.

6.保存示例

将文档(数据)保存到名为“user”的集合(表)中。

 DBCollection table = db.getCollection("user");
	BasicDBObject document = new BasicDBObject();
	document.put("name", "mkyong");
	document.put("age", 30);
	document.put("createdDate", new Date());
	table.insert(document); 

参考这个 Java MongoDB 插入示例

7.更新示例

更新一个文档,其中“name=mkyong”。

 DBCollection table = db.getCollection("user");

	BasicDBObject query = new BasicDBObject();
	query.put("name", "mkyong");

	BasicDBObject newDocument = new BasicDBObject();
	newDocument.put("name", "mkyong-updated");

	BasicDBObject updateObj = new BasicDBObject();
	updateObj.put("$set", newDocument);

	table.update(query, updateObj); 

参考这个 Java MongoDB 更新实例

8.查找示例

找到“name=mkyong”处的文档,并用 DBCursor 显示它

 DBCollection table = db.getCollection("user");

	BasicDBObject searchQuery = new BasicDBObject();
	searchQuery.put("name", "mkyong");

	DBCursor cursor = table.find(searchQuery);

	while (cursor.hasNext()) {
		System.out.println(cursor.next());
	} 

参考这个 Java MongoDB 搜索查询例子

9.删除示例

找到“name=mkyong”处的文档,并删除它。

 DBCollection table = db.getCollection("user");

	BasicDBObject searchQuery = new BasicDBObject();
	searchQuery.put("name", "mkyong");

	table.remove(searchQuery); 

参考这个 Java MongoDB 删除例子

10.你好世界

让我们回顾一个完整的 Java + MongoDB 示例,不言自明的请参见注释。

App.java

 package com.mkyong.core;

import java.net.UnknownHostException;
import java.util.Date;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoException;

/**
 * Java + MongoDB Hello world Example
 * 
 */
public class App {
  public static void main(String[] args) {

    try {

	/**** Connect to MongoDB ****/
	// Since 2.10.0, uses MongoClient
	MongoClient mongo = new MongoClient("localhost", 27017);

	/**** Get database ****/
	// if database doesn't exists, MongoDB will create it for you
	DB db = mongo.getDB("testdb");

	/**** Get collection / table from 'testdb' ****/
	// if collection doesn't exists, MongoDB will create it for you
	DBCollection table = db.getCollection("user");

	/**** Insert ****/
	// create a document to store key and value
	BasicDBObject document = new BasicDBObject();
	document.put("name", "mkyong");
	document.put("age", 30);
	document.put("createdDate", new Date());
	table.insert(document);

	/**** Find and display ****/
	BasicDBObject searchQuery = new BasicDBObject();
	searchQuery.put("name", "mkyong");

	DBCursor cursor = table.find(searchQuery);

	while (cursor.hasNext()) {
		System.out.println(cursor.next());
	}

	/**** Update ****/
	// search document where name="mkyong" and update it with new values
	BasicDBObject query = new BasicDBObject();
	query.put("name", "mkyong");

	BasicDBObject newDocument = new BasicDBObject();
	newDocument.put("name", "mkyong-updated");

	BasicDBObject updateObj = new BasicDBObject();
	updateObj.put("$set", newDocument);

	table.update(query, updateObj);

	/**** Find and display ****/
	BasicDBObject searchQuery2 
	    = new BasicDBObject().append("name", "mkyong-updated");

	DBCursor cursor2 = table.find(searchQuery2);

	while (cursor2.hasNext()) {
		System.out.println(cursor2.next());
	}

	/**** Done ****/
	System.out.println("Done");

    } catch (UnknownHostException e) {
	e.printStackTrace();
    } catch (MongoException e) {
	e.printStackTrace();
    }

  }
} 

输出…

 { "_id" : { "$oid" : "51398e6e30044a944cc23e2e"} , "name" : "mkyong" , "age" : 30 , "createdDate" : { "$date" : "2013-03-08T07:08:30.168Z"}}
{ "_id" : { "$oid" : "51398e6e30044a944cc23e2e"} , "age" : 30 , "createdDate" : { "$date" : "2013-03-08T07:08:30.168Z"} , "name" : "mkyong-updated"}
Done 

让我们使用mongo控制台来检查创建的数据库“testdb”、集合“user”和文档。

 $ mongo
MongoDB shell version: 2.2.3
connecting to: test

> show dbs
testdb	0.203125GB

> use testdb
switched to db testdb

> show collections
system.indexes
user
> db.user.find()
{ "_id" : ObjectId("51398e6e30044a944cc23e2e"), "age" : 30, "createdDate" : ISODate("2013-03-08T07:08:30.168Z"), "name" : "mkyong-updated" } 

下载源代码

Download it – Java-mongodb-hello-world-example.zip (13KB)

参考

  1. 【Java 驱动程序入门
  2. Java-MongoDB 驱动程序

java mongodb

Java MongoDB:插入文档

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/mongodb/java-mongodb-insert-a-document/

在本教程中,我们向您展示了通过 Java MongoDB API 将下面的 JSON 数据插入到一个文档中的 4 种方法。

测试数据

JSON 格式的测试数据。

 {
	"database" : "mkyongDB",
	"table" : "hosting",
	"detail" : 
		{
			records : 99,
			index : "vps_index1",
			active : "true"
		}
	}
} 

1.BasicDBObject 示例

 BasicDBObject document = new BasicDBObject();
	document.put("database", "mkyongDB");
	document.put("table", "hosting");

	BasicDBObject documentDetail = new BasicDBObject();
	documentDetail.put("records", 99);
	documentDetail.put("index", "vps_index1");
	documentDetail.put("active", "true");

	document.put("detail", documentDetail);

	collection.insert(document); 

2.BasicDBObjectBuilder 示例

 BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start()
		.add("database", "mkyongDB")
		.add("table", "hosting");

	BasicDBObjectBuilder documentBuilderDetail = BasicDBObjectBuilder.start()
	.add("records", 99)
	.add("index", "vps_index1")
	.add("active", "true");

	documentBuilder.add("detail", documentBuilderDetail.get());

	collection.insert(documentBuilder.get()); 

3.地图示例

 Map<String, Object> documentMap = new HashMap<String, Object>();
	documentMap.put("database", "mkyongDB");
	documentMap.put("table", "hosting");

	Map<String, Object> documentMapDetail = new HashMap<String, Object>();
	documentMapDetail.put("records", 99);
	documentMapDetail.put("index", "vps_index1");
	documentMapDetail.put("active", "true");

	documentMap.put("detail", documentMapDetail);

	collection.insert(new BasicDBObject(documentMap)); 

4.JSON 解析示例

 String json = "{'database' : 'mkyongDB','table' : 'hosting'," +
	  "'detail' : {'records' : 99, 'index' : 'vps_index1', 'active' : 'true'}}}";

	DBObject dbObject = (DBObject)JSON.parse(json);

	collection.insert(dbObject); 

完整示例

 package com.mkyong.core;

import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.util.JSON;

/**
 * Java MongoDB : Insert a Document
 * 
 */
public class InsertDocumentApp {
  public static void main(String[] args) {

    try {

	Mongo mongo = new Mongo("localhost", 27017);
	DB db = mongo.getDB("yourdb");

	DBCollection collection = db.getCollection("dummyColl");

	// 1\. BasicDBObject example
	System.out.println("BasicDBObject example...");
	BasicDBObject document = new BasicDBObject();
	document.put("database", "mkyongDB");
	document.put("table", "hosting");

	BasicDBObject documentDetail = new BasicDBObject();
	documentDetail.put("records", 99);
	documentDetail.put("index", "vps_index1");
	documentDetail.put("active", "true");
	document.put("detail", documentDetail);

	collection.insert(document);

	DBCursor cursorDoc = collection.find();
	while (cursorDoc.hasNext()) {
		System.out.println(cursorDoc.next());
	}

	collection.remove(new BasicDBObject());

	// 2\. BasicDBObjectBuilder example
	System.out.println("BasicDBObjectBuilder example...");
	BasicDBObjectBuilder documentBuilder = BasicDBObjectBuilder.start()
		.add("database", "mkyongDB")
                .add("table", "hosting");

	BasicDBObjectBuilder documentBuilderDetail = BasicDBObjectBuilder.start()
                .add("records", "99")
                .add("index", "vps_index1")
		.add("active", "true");

	documentBuilder.add("detail", documentBuilderDetail.get());

	collection.insert(documentBuilder.get());

	DBCursor cursorDocBuilder = collection.find();
	while (cursorDocBuilder.hasNext()) {
		System.out.println(cursorDocBuilder.next());
	}

	collection.remove(new BasicDBObject());

	// 3\. Map example
	System.out.println("Map example...");
	Map<String, Object> documentMap = new HashMap<String, Object>();
	documentMap.put("database", "mkyongDB");
	documentMap.put("table", "hosting");

	Map<String, Object> documentMapDetail = new HashMap<String, Object>();
	documentMapDetail.put("records", "99");
	documentMapDetail.put("index", "vps_index1");
	documentMapDetail.put("active", "true");

	documentMap.put("detail", documentMapDetail);

	collection.insert(new BasicDBObject(documentMap));

	DBCursor cursorDocMap = collection.find();
	while (cursorDocMap.hasNext()) {
		System.out.println(cursorDocMap.next());
	}

	collection.remove(new BasicDBObject());

	// 4\. JSON parse example
	System.out.println("JSON parse example...");

	String json = "{'database' : 'mkyongDB','table' : 'hosting'," +
	  "'detail' : {'records' : 99, 'index' : 'vps_index1', 'active' : 'true'}}}";

	DBObject dbObject = (DBObject)JSON.parse(json);

	collection.insert(dbObject);

	DBCursor cursorDocJSON = collection.find();
	while (cursorDocJSON.hasNext()) {
		System.out.println(cursorDocJSON.next());
	}

	collection.remove(new BasicDBObject());

    } catch (UnknownHostException e) {
	e.printStackTrace();
    } catch (MongoException e) {
	e.printStackTrace();
    }

  }
} 

输出…

 BasicDBObject example...
{ "_id" : { "$oid" : "4dc9ef6f237f86642d5b34bd"} , "database" : "mkyongDB" , 
"table" : "hosting" , "detail" : { "records" : "99" , "index" : "vps_index1" , "active" : "true"}}

BasicDBObjectBuilder example...
{ "_id" : { "$oid" : "4dc9ef6f237f86642d5b34be"} , "database" : "mkyongDB" , 
"table" : "hosting" , "detail" : { "records" : "99" , "index" : "vps_index1" , "active" : "true"}}

Map example...
{ "_id" : { "$oid" : "4dc9ef6f237f86642d5b34bf"} , "detail" : { "index" : "vps_index1" , 
"active" : "true" , "records" : "99"} , "table" : "hosting" , "database" : "mkyongDB"}

JSON parse example...
{ "_id" : { "$oid" : "4dc9ef6f237f86642d5b34c0"} , "database" : "mkyongDB" , 
"table" : "hosting" , "detail" : { "records" : 199 , "index" : "vps_index1" , "active" : "true"}} 

What is “_id” ?
The _id is added by MongoDB automatically, for identity purpose. From MongoDB document, it said, all element names that start with “_”, “/” and “$” are reserved for internal use.

参考

  1. 基础对象 Java 文档
  2. 基础对象构建器 Java 文档

mongodb save

Java MongoDB:查询文档

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/mongodb/java-mongodb-query-document/

在本教程中,我们将向您展示从集合中获取或查询文档的几种常用方法。

测试数据

插入 5 份模拟文件进行测试。

 { "_id" : { "$oid" : "id"} , "number" : 1 , "name" : "mkyong-1"}
{ "_id" : { "$oid" : "id"} , "number" : 2 , "name" : "mkyong-2"}
{ "_id" : { "$oid" : "id"} , "number" : 3 , "name" : "mkyong-3"}
{ "_id" : { "$oid" : "id"} , "number" : 4 , "name" : "mkyong-4"}
{ "_id" : { "$oid" : "id"} , "number" : 5 , "name" : "mkyong-5"} 

1.查找()示例

1.1 仅获取第一个匹配的文档。

 DBObject doc = collection.findOne();
	System.out.println(dbObject); 

输出

 { "_id" : { "$oid" : "id"} , "number" : 1 , "name" : "mkyong-1"} 

1.2 获取所有匹配的文档。

 DBCursor cursor = collection.find();
	while(cursor.hasNext()) {
	    System.out.println(cursor.next());
	} 

输出

 { "_id" : { "$oid" : "id"} , "number" : 1 , "name" : "mkyong-1"}
{ "_id" : { "$oid" : "id"} , "number" : 2 , "name" : "mkyong-2"}
{ "_id" : { "$oid" : "id"} , "number" : 3 , "name" : "mkyong-3"}
{ "_id" : { "$oid" : "id"} , "number" : 4 , "name" : "mkyong-4"}
{ "_id" : { "$oid" : "id"} , "number" : 5 , "name" : "mkyong-5"} 

1.3 从匹配的文档中获取单个字段。

 BasicDBObject allQuery = new BasicDBObject();
	BasicDBObject fields = new BasicDBObject();
	fields.put("name", 1);

	DBCursor cursor = collection.find(allQuery, fields);
	while (cursor.hasNext()) {
		System.out.println(cursor.next());
	} 

输出

 { "_id" : { "$oid" : "id"} , "name" : "mkyong-1"}
{ "_id" : { "$oid" : "id"} , "name" : "mkyong-2"}
{ "_id" : { "$oid" : "id"} , "name" : "mkyong-3"}
{ "_id" : { "$oid" : "id"} , "name" : "mkyong-4"}
{ "_id" : { "$oid" : "id"} , "name" : "mkyong-5"} 

2.查找()和比较

2.1 在number = 5处获取所有文件。

 BasicDBObject whereQuery = new BasicDBObject();
	whereQuery.put("number", 5);
	DBCursor cursor = collection.find(whereQuery);
	while(cursor.hasNext()) {
	    System.out.println(cursor.next());
	} 

输出

 { "_id" : { "$oid" : "id"} , "number" : 5 , "name" : "mkyong-5"} 

2.2 $in示例–在number in 2, 4 and 5处获取文件。

 BasicDBObject inQuery = new BasicDBObject();
	List<Integer> list = new ArrayList<Integer>();
	list.add(2);
	list.add(4);
	list.add(5);
	inQuery.put("number", new BasicDBObject("$in", list));
	DBCursor cursor = collection.find(inQuery);
	while(cursor.hasNext()) {
		System.out.println(cursor.next());
	} 

输出

 { "_id" : { "$oid" : "id"} , "number" : 2 , "name" : "mkyong-2"}
{ "_id" : { "$oid" : "id"} , "number" : 4 , "name" : "mkyong-4"}
{ "_id" : { "$oid" : "id"} , "number" : 5 , "name" : "mkyong-5"} 

2.3 $gt $lt示例–在 5 > number > 2 处获取文件。

 BasicDBObject gtQuery = new BasicDBObject();
	gtQuery.put("number", new BasicDBObject("$gt", 2).append("$lt", 5));
	DBCursor cursor = collection.find(gtQuery);
	while(cursor.hasNext()) {
		System.out.println(cursor.next());
	} 

输出

 { "_id" : { "$oid" : "id"} , "number" : 3 , "name" : "mkyong-3"}
{ "_id" : { "$oid" : "id"} , "number" : 4 , "name" : "mkyong-4"} 

2.4 $ne示例–在 number != 4 处获取文件。

 BasicDBObject neQuery = new BasicDBObject();
	neQuery.put("number", new BasicDBObject("$ne", 4));
	DBCursor cursor = collection.find(neQuery);
	while(cursor.hasNext()) {
		System.out.println(cursor.next());
	} 

输出

 { "_id" : { "$oid" : "id"} , "number" : 1 , "name" : "mkyong-1"}
{ "_id" : { "$oid" : "id"} , "number" : 2 , "name" : "mkyong-2"}
{ "_id" : { "$oid" : "id"} , "number" : 3 , "name" : "mkyong-3"}
{ "_id" : { "$oid" : "id"} , "number" : 5 , "name" : "mkyong-5"} 

3.find()和逻辑

3.1 $and示例-从number = 2 and name = 'mkyong-2'处获取文件。

 BasicDBObject andQuery = new BasicDBObject();
	List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
	obj.add(new BasicDBObject("number", 2));
	obj.add(new BasicDBObject("name", "mkyong-2"));
	andQuery.put("$and", obj);

	System.out.println(andQuery.toString());

	DBCursor cursor = collection.find(andQuery);
	while (cursor.hasNext()) {
		System.out.println(cursor.next());
	} 

输出

 { "$and" : [ { "number" : 2} , { "name" : "mkyong-2"}]}

{ "_id" : { "$oid" : "id"} , "number" : 2 , "name" : "mkyong-2"} 

4.find()和 Regex

使用正则表达式模式查找文档。

4.1 $regex示例-从name like pattern 'Mky.*-[1-3]', case insensitive处获取文件。

 BasicDBObject regexQuery = new BasicDBObject();
	regexQuery.put("name", 
		new BasicDBObject("$regex", "Mky.*-[1-3]")
		.append("$options", "i"));

	System.out.println(regexQuery.toString());

	DBCursor cursor = collection.find(regexQuery);
	while (cursor.hasNext()) {
		System.out.println(cursor.next());
	} 

输出

 { "name" : { "$regex" : "Mky.*-[1-3]" , "$options" : "i"}}

{ "_id" : { "$oid" : "515ad59e3004c89329c7b259"} , "number" : 1 , "name" : "mkyong-1"}
{ "_id" : { "$oid" : "515ad59e3004c89329c7b25a"} , "number" : 2 , "name" : "mkyong-2"}
{ "_id" : { "$oid" : "515ad59e3004c89329c7b25b"} , "number" : 3 , "name" : "mkyong-3"} 

There are more…
Read this MongoDB operator documentation for complete set of query operators supported in MongoDB.

5.完整示例

 package com.mkyong.core;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

/**
 * Java MongoDB : Query document
 * 
 * @author mkyong
 * 
 */
public class QueryApp {

	public static void insertDummyDocuments(DBCollection collection) {

		List<DBObject> list = new ArrayList<DBObject>();

		Calendar cal = Calendar.getInstance();

		for (int i = 1; i <= 5; i++) {

			BasicDBObject data = new BasicDBObject();
			data.append("number", i);
			data.append("name", "mkyong-" + i);
			// data.append("date", cal.getTime());

			// +1 day
			cal.add(Calendar.DATE, 1);

			list.add(data);

		}

		collection.insert(list);

	}

	public static void main(String[] args) {

	try {

	  Mongo mongo = new Mongo("localhost", 27017);
	  DB db = mongo.getDB("yourdb");

	  // get a single collection
	  DBCollection collection = db.getCollection("dummyColl");

	  insertDummyDocuments(collection);

	  System.out.println("1\. Find first matched document");
	  DBObject dbObject = collection.findOne();
	  System.out.println(dbObject);

	  System.out.println("\n1\. Find all matched documents");
	  DBCursor cursor = collection.find();
	  while (cursor.hasNext()) {
		System.out.println(cursor.next());
	  }

	  System.out.println("\n1\. Get 'name' field only");
	  BasicDBObject allQuery = new BasicDBObject();
	  BasicDBObject fields = new BasicDBObject();
	  fields.put("name", 1);

	  DBCursor cursor2 = collection.find(allQuery, fields);
	  while (cursor2.hasNext()) {
		System.out.println(cursor2.next());
	  }

	  System.out.println("\n2\. Find where number = 5");
	  BasicDBObject whereQuery = new BasicDBObject();
	  whereQuery.put("number", 5);
	  DBCursor cursor3 = collection.find(whereQuery);
	  while (cursor3.hasNext()) {
		System.out.println(cursor3.next());
	  }

	  System.out.println("\n2\. Find where number in 2,4 and 5");
	  BasicDBObject inQuery = new BasicDBObject();
	  List<Integer> list = new ArrayList<Integer>();
	  list.add(2);
	  list.add(4);
	  list.add(5);
	  inQuery.put("number", new BasicDBObject("$in", list));
	  DBCursor cursor4 = collection.find(inQuery);
	  while (cursor4.hasNext()) {
		System.out.println(cursor4.next());
	  }

	  System.out.println("\n2\. Find where 5 > number > 2");
	  BasicDBObject gtQuery = new BasicDBObject();
	  gtQuery.put("number", new BasicDBObject("$gt", 2).append("$lt", 5));
	  DBCursor cursor5 = collection.find(gtQuery);
	  while (cursor5.hasNext()) {
		System.out.println(cursor5.next());
	  }

	  System.out.println("\n2\. Find where number != 4");
	  BasicDBObject neQuery = new BasicDBObject();
	  neQuery.put("number", new BasicDBObject("$ne", 4));
	  DBCursor cursor6 = collection.find(neQuery);
	  while (cursor6.hasNext()) {
		System.out.println(cursor6.next());
	  }

	  System.out.println("\n3\. Find when number = 2 and name = 'mkyong-2' example");
	  BasicDBObject andQuery = new BasicDBObject();

	  List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
	  obj.add(new BasicDBObject("number", 2));
	  obj.add(new BasicDBObject("name", "mkyong-2"));
	  andQuery.put("$and", obj);

	  System.out.println(andQuery.toString());

	  DBCursor cursor7 = collection.find(andQuery);
	  while (cursor7.hasNext()) {
		System.out.println(cursor7.next());
	  }

	  System.out.println("\n4\. Find where name = 'Mky.*-[1-3]', case sensitive example");
	  BasicDBObject regexQuery = new BasicDBObject();
	  regexQuery.put("name",
		new BasicDBObject("$regex", "Mky.*-[1-3]")
                    .append("$options", "i"));

	  System.out.println(regexQuery.toString());

	  DBCursor cursor8 = collection.find(regexQuery);
	  while (cursor8.hasNext()) {
		System.out.println(cursor8.next());
	  }

	  collection.drop();

	  System.out.println("Done");

	 } catch (UnknownHostException e) {
		e.printStackTrace();
	 } catch (MongoException e) {
		e.printStackTrace();
	 }

	}
} 

完成了。

参考

  1. 查询、更新和投影运算符快速参考

mongodb query

Java MongoDB:保存图像示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/mongodb/java-mongodb-save-image-example/

在本教程中,我们向您展示如何通过 GridFS API 将图像文件保存到 MongoDB 中。GridFS APIs 也能够服务于其他二进制文件,比如视频和音乐文件。

Note
For detail explanation, read this MongoDB GridFS manual.

1.保存图像

将图像文件保存到 MongoDB 的“photo”名称空间下的代码片段,并为保存的图像分配一个新的“filename”。

 String newFileName = "mkyong-java-image";
	File imageFile = new File("c:\\JavaWebHosting.png");
	GridFS gfsPhoto = new GridFS(db, "photo");
	GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);
	gfsFile.setFilename(newFileName);
	gfsFile.save(); 

2.获取图像

通过“文件名”获取保存图像的代码片段。

 String newFileName = "mkyong-java-image";
	GridFS gfsPhoto = new GridFS(db, "photo");
	GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName);
	System.out.println(imageForOutput); 

输出,图像保存为以下 JSON 格式。

 { 
	"_id" : 
	{ 
		"$oid" : "4dc9511a14a7d017fee35746"
	} , 
	"chunkSize" : 262144 , 
	"length" : 22672 , 
	"md5" : "1462a6cfa27669af1d8d21c2d7dd1f8b" , 
	"filename" : "mkyong-java-image" , 
	"contentType" :  null  , 
	"uploadDate" : 
	{ 
		"$date" : "2011-05-10T14:52:10Z"
	} , 
	"aliases" :  null 
} 

3.打印所有保存的图像

从 MongoDB 获取所有保存的文件并用 DBCursor 迭代它的代码片段。

 GridFS gfsPhoto = new GridFS(db, "photo");
	DBCursor cursor = gfsPhoto.getFileList();
	while (cursor.hasNext()) {
		System.out.println(cursor.next());
	} 

4.保存到另一个图像

从 MongoDB 获取一个图像文件并将其输出到另一个图像文件的代码片段。

 String newFileName = "mkyong-java-image";
	GridFS gfsPhoto = new GridFS(db, "photo");
	GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName);
	imageForOutput.writeTo("c:\\JavaWebHostingNew.png"); //output to new file 

5.删除图像

删除图像文件的代码片段。

 String newFileName = "mkyong-java-image";
	GridFS gfsPhoto = new GridFS(db, "photo");
	gfsPhoto.remove(gfsPhoto.findOne(newFileName)); 

完整示例

通过 Java MongoDB GridFS API 处理图像的完整示例。解释见评论。

 package com.mkyong.core;

import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.mongodb.gridfs.GridFSInputFile;

/**
 * Java MongoDB : Save image example
 * 
 */

public class SaveImageApp {
	public static void main(String[] args) {

		try {

			Mongo mongo = new Mongo("localhost", 27017);
			DB db = mongo.getDB("imagedb");
			DBCollection collection = db.getCollection("dummyColl");

			String newFileName = "mkyong-java-image";

			File imageFile = new File("c:\\JavaWebHosting.png");

			// create a "photo" namespace
			GridFS gfsPhoto = new GridFS(db, "photo");

			// get image file from local drive
			GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);

			// set a new filename for identify purpose
			gfsFile.setFilename(newFileName);

			// save the image file into mongoDB
			gfsFile.save();

			// print the result
			DBCursor cursor = gfsPhoto.getFileList();
			while (cursor.hasNext()) {
				System.out.println(cursor.next());
			}

			// get image file by it's filename
			GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName);

			// save it into a new image file
			imageForOutput.writeTo("c:\\JavaWebHostingNew.png");

			// remove the image file from mongoDB
			gfsPhoto.remove(gfsPhoto.findOne(newFileName));

			System.out.println("Done");

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

	}
} 

程序结束时,在“c:\ \ javawebhostingnew . png”中创建了一个新的图像文件。

参考

  1. MongoDB GridFS 规范

image mongodb

Java MongoDB 教程

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/tutorials/java-mongodb-tutorials/

mongodb-tutorials

MongoDB ,noSQL 开源数据库,用 C++写的,有很多很棒的特性,比如 map-reduce,自动分片,复制,高可用性等等。

下面的 Java / Spring Data MongoDB 教程和例子是用:

  1. MongoDB 2.2.3
  2. Java-MongoDB-驱动程序 2.11.0
  3. Spring-Data-MongoDB 1.2.0 .发行版

1.MongoDB 核心示例

MongoDB 安装、配置、连接、查询和备份。

2.Java MongoDB 示例

Java MongoDB 驱动程序 API 示例,用于在 MongoDB 中执行插入、更新、查询和删除文档。

3.Spring 数据 MongoDB 示例

Spring Data for MongoDB 示例,用于从 MongoDB 中执行插入、更新、查询和删除文档。

4. MongoDB FAQs

MongoDB 中的一些常见问答。

参考

Java MongoDB:更新文档

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/mongodb/java-mongodb-update-document/

在本教程中,我们将向您展示如何使用 Java MongoDB API collection.update()来更新文档。

测试数据

假设插入了以下数据/文件。

 {
	"hosting" : "hostA",
	"type" : "vps",
	"clients" : 1000
},
{
	"hosting" : "hostB",
	"type" : "dedicated server",
	"clients" : 100
},
{
	"hosting" : "hostC",
	"type" : "vps",
	"clients" : 900
} 
 { "_id" : { "$oid" : "id"} , "hosting" : "hostA" , "type" : "vps" , "clients" : 1000}
{ "_id" : { "$oid" : "id"} , "hosting" : "hostB" , "type" : "dedicated server" , "clients" : 100}
{ "_id" : { "$oid" : "id"} , "hosting" : "hostC" , "type" : "vps" , "clients" : 900} 

1.带有 set 的 DBCollection.update()

查找 hosting = 'hostB '的文档,并将其客户端值从 100 更新为 110。

 BasicDBObject newDocument = new BasicDBObject();
	newDocument.put("clients", 110);

	BasicDBObject searchQuery = new BasicDBObject().append("hosting", "hostB");

	collection.update(searchQuery, newDocument); 

输出

 { "_id" : { "$oid" : "id"} , "hosting" : "hostA" , "type" : "vps" , "clients" : 1000}
{ "_id" : { "$oid" : "id"} , "clients" : 110}
{ "_id" : { "$oid" : "id"} , "hosting" : "hostC" , "type" : "vps" , "clients" : 900} 

The document is replaced!?
Wait, the entire “hostB” document is replaced with another new document, this is not what we want.

要仅更新特定值,使用$set更新修改器。

 BasicDBObject newDocument = new BasicDBObject();
	newDocument.append("$set", new BasicDBObject().append("clients", 110));

	BasicDBObject searchQuery = new BasicDBObject().append("hosting", "hostB");

	collection.update(searchQuery, newDocument); 

输出

 { "_id" : { "$oid" : "id"} , "hosting" : "hostA" , "type" : "vps" , "clients" : 1000}
{ "_id" : { "$oid" : "id"} , "hosting" : "hostB" , "type" : "dedicated server" , "clients" : 110}
{ "_id" : { "$oid" : "id"} , "hosting" : "hostC" , "type" : "vps" , "clients" : 900} 

Note
The MongoDB team should create another new API named DBCollection.replace(), many beginners are trapped in this DBCollection.update() API and replace the entire document accidentally. Again, to update a particular value, use $set. ## 2.带有$inc .的 DBCollection.update()

这个例子显示了使用$inc修饰符来增加一个特定的值。查找 hosting = 'hostB '的文档,通过将值从 100 增加到 199,(100 + 99) = 199 来更新它的' clients '值。

 BasicDBObject newDocument = 
		new BasicDBObject().append("$inc", 
		new BasicDBObject().append("total clients", 99));

	collection.update(new BasicDBObject().append("hosting", "hostB"), newDocument); 

输出

 { "_id" : { "$oid" : "id"} , "hosting" : "hostA" , "type" : "vps" , "clients" : 1000}
{ "_id" : { "$oid" : "id"} , "hosting" : "hostB" , "type" : "dedicated server" , "clients" : 199}
{ "_id" : { "$oid" : "id"} , "hosting" : "hostC" , "type" : "vps" , "clients" : 900} 

3.带有多个的 DBCollection.update()

这个例子展示了使用multi参数来更新一组匹配的文档。查找 type = 'vps '的文档,将所有匹配文档的' clients '值更新为 888。

 BasicDBObject updateQuery = new BasicDBObject();
	updateQuery.append("$set", 
		new BasicDBObject().append("clients", "888"));

	BasicDBObject searchQuery = new BasicDBObject();
	searchQuery.append("type", "vps");

	collection.updateMulti(searchQuery, updateQuery);			

	//below statement set multi to true.
	//collection.update(searchQuery, updateQuery, false, true); 

输出

 { "_id" : { "$oid" : "id"} , "hosting" : "hostA" , "clients" : "888" , "type" : "vps"}
{ "_id" : { "$oid" : "id"} , "hosting" : "hostB" , "type" : "dedicated server" , "clients" : 100}
{ "_id" : { "$oid" : "id"} , "hosting" : "hostC" , "clients" : "888" , "type" : "vps"} 

Note
If update without the multi set to true.

 BasicDBObject updateQuery = new BasicDBObject();
	updateQuery.append("$set", 
		new BasicDBObject().append("clients", "888"));

	BasicDBObject searchQuery = new BasicDBObject();
	searchQuery.append("type", "vps");

	collection.update(searchQuery, updateQuery); 

您会注意到只有第一个匹配的文档被更新。

 {"_id":{ "$oid" : "x"} , "hosting" : "hostA" , "clients" : "888" , "type" : "vps"}
{"_id":{ "$oid" : "x"} , "hosting" : "hostB" , "type" : "dedicated server" , "clients" : 100}
{"_id":{ "$oid" : "x"} , "hosting" : "hostC" , "type" : "vps" , "clients" : 900} 

要更新一组匹配的文档,需要将“multi”设置为 true。

4.完整示例

完整的例子结合上述代码片段。

 package com.mkyong.core;

import java.net.UnknownHostException;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

/**
 * Java MongoDB update document
 * 
 * @author mkyong
 * 
 */

public class UpdateApp {

	public static void printAllDocuments(DBCollection collection) {
		DBCursor cursor = collection.find();
		while (cursor.hasNext()) {
			System.out.println(cursor.next());
		}
	}

	public static void removeAllDocuments(DBCollection collection) {
		collection.remove(new BasicDBObject());
	}

	public static void insertDummyDocuments(DBCollection collection) {
		BasicDBObject document = new BasicDBObject();
		document.put("hosting", "hostA");
		document.put("type", "vps");
		document.put("clients", 1000);

		BasicDBObject document2 = new BasicDBObject();
		document2.put("hosting", "hostB");
		document2.put("type", "dedicated server");
		document2.put("clients", 100);

		BasicDBObject document3 = new BasicDBObject();
		document3.put("hosting", "hostC");
		document3.put("type", "vps");
		document3.put("clients", 900);

		collection.insert(document);
		collection.insert(document2);
		collection.insert(document3);
	}

	public static void main(String[] args) {

	try {

	  Mongo mongo = new Mongo("localhost", 27017);
	  DB db = mongo.getDB("yourdb");

	  // get a single collection
	  DBCollection collection = db.getCollection("dummyColl");

	  System.out.println("Testing 1...no $set");

	  insertDummyDocuments(collection);

	  // find hosting = hostB, and update the clients to 110
	  BasicDBObject newDocument = new BasicDBObject();
	  newDocument.put("clients", 110);

	  BasicDBObject searchQuery = new BasicDBObject().append("hosting", "hostB");

	  collection.update(searchQuery, newDocument);

	  printAllDocuments(collection);
	  removeAllDocuments(collection);

	  System.out.println("\nTesting 1...with $set");

	  insertDummyDocuments(collection);

	  BasicDBObject updateDocument = new BasicDBObject();
	  updateDocument.append("$set", new BasicDBObject().append("clients", 110));

	  BasicDBObject searchQuery2 = new BasicDBObject().append("hosting", "hostB");

	  collection.update(searchQuery2, updateDocument);

	  printAllDocuments(collection);
	  removeAllDocuments(collection);

	  System.out.println("\nTesting 2... with $inc");
	  insertDummyDocuments(collection);
	  // find hosting = hostB and increase it's "clients" value by 99
	  BasicDBObject newDocument2 = new BasicDBObject().append("$inc",
		new BasicDBObject().append("clients", 99));

	  collection.update(new BasicDBObject().append("hosting", "hostB"), newDocument2);

	  printAllDocuments(collection);
	  removeAllDocuments(collection);

	  System.out.println("\nTesting 3... with $multi");

	  insertDummyDocuments(collection);
	  // find type = vps , update all matched documents , clients value to 888
	  BasicDBObject updateQuery = new BasicDBObject();
	  updateQuery.append("$set", new BasicDBObject().append("clients", "888"));

	  BasicDBObject searchQuery3 = new BasicDBObject();
	  searchQuery3.append("type", "vps");

	  collection.updateMulti(searchQuery3, updateQuery);
	  // collection.update(searchQuery3, updateQuery, false, true);

	  printAllDocuments(collection);
	  removeAllDocuments(collection);

	  System.out.println("Done");

	} catch (UnknownHostException e) {
		e.printStackTrace();
	} catch (MongoException e) {
		e.printStackTrace();
	}

    }
} 

输出

 Testing 1...no $set
{ "_id" : { "$oid" : "id"} , "hosting" : "hostA" , "type" : "vps" , "clients" : 1000}
{ "_id" : { "$oid" : "id"} , "clients" : 110}
{ "_id" : { "$oid" : "id"} , "hosting" : "hostC" , "type" : "vps" , "clients" : 900}

Testing 1...with $set
{ "_id" : { "$oid" : "id"} , "hosting" : "hostA" , "type" : "vps" , "clients" : 1000}
{ "_id" : { "$oid" : "id"} , "hosting" : "hostB" , "type" : "dedicated server" , "clients" : 110}
{ "_id" : { "$oid" : "id"} , "hosting" : "hostC" , "type" : "vps" , "clients" : 900}

Testing 2... with $inc
{ "_id" : { "$oid" : "id"} , "hosting" : "hostA" , "type" : "vps" , "clients" : 1000}
{ "_id" : { "$oid" : "id"} , "hosting" : "hostB" , "type" : "dedicated server" , "clients" : 199}
{ "_id" : { "$oid" : "id"} , "hosting" : "hostC" , "type" : "vps" , "clients" : 900}

Testing 3... with $multi
{ "_id" : { "$oid" : "id"} , "hosting" : "hostB" , "type" : "dedicated server" , "clients" : 100}
{ "_id" : { "$oid" : "id"} , "hosting" : "hostC" , "type" : "vps" , "clients" : 900}
{ "_id" : { "$oid" : "id"} , "clients" : "888" , "hosting" : "hostA" , "type" : "vps"}
Done 

参考

  1. 如何在 MongoDB 中进行更新
  2. $设置更新修改量
  3. $inc 更新修改量
  4. Java MongoDB API,DBCollection JavaDoc

mongodb update

JAX-WS–Java . net . bind 异常:地址已在使用中:bind

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/webservices/jax-ws/java-net-bindexception-address-already-in-use-bind/

用 JAX-WS 开发一个 Java web 服务开发,并发布一个端点…

 public static void main(String[] args) {
   Endpoint.publish("http://localhost:8080/ws/hello", new WallStreetImpl());
} 

1.问题

它会显示以下错误消息。

 Exception in thread "main" com.sun.xml.internal.ws.server.ServerRtException: 
	Server Runtime Error: java.net.BindException: Address already in use: bind
	...
Caused by: java.net.BindException: Address already in use: bind
	at sun.nio.ch.Net.bind(Native Method)
	... 

2.解决办法

一个非常常见的错误消息,它意味着地址(通常是端口号)已经被另一个应用程序使用。

要修复它,请更改端点端口号:

 public static void main(String[] args) {
   Endpoint.publish("http://localhost:1234/ws/hello", new WallStreetImpl());
} 

参考

  1. Linux–哪个应用程序正在使用端口 8080

jax-ws web services

Java 质数示例

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/java/java-prime-numbers-examples/

下面的 Java 示例将打印一个列表,列出所有的质数直到 1,000:

 2	3	5	7	11	13	17	19	23	29	31	37	41	43	47	53	59	61	67	71
73	79	83	89	97	101	103	107	109	113	127	131	137	139	149	151	157	163	167	173	
179	181	191	193	197	199	211	223	227	229	233	239	241	251	257	263	269	271	277	281	
283	293	307	311	313	317	331	337	347	349	353	359	367	373	379	383	389	397	401	409	
419	421	431	433	439	443	449	457	461	463	467	479	487	491	499	503	509	521	523	541	
547	557	563	569	571	577	587	593	599	601	607	613	617	619	631	641	643	647	653	659	
661	673	677	683	691	701	709	719	727	733	739	743	751	757	761	769	773	787	797	809	
811	821	823	827	829	839	853	857	859	863	877	881	883	887	907	911	919	929	937	941	
947	953	967	971	977	983	991	997	

Total: 168 

3 个 Java 示例:

  • Java 8 流和 BigInteger
  • 普通的旧爪哇咖啡
  • 厄拉多塞算法的筛选

1.Java 8 流和 BigInteger

1.1 使用流。

PrintPrimeNumber.java

 package com.mkyong.test;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class PrintPrimeNumber {

    public static void main(String[] args) {

        long count = Stream.iterate(0, n -> n + 1)
                .limit(1000)
                .filter(TestPrime::isPrime)
                .peek(x -> System.out.format("%s\t", x))
                .count();

        System.out.println("\nTotal: " + count);

    }

    public static boolean isPrime(int number) {

        if (number <= 1) return false; // 1 is not prime and also not composite

        return !IntStream.rangeClosed(2, number / 2).anyMatch(i -> number % i == 0);
    }

} 

1.2 使用BigInteger::nextProbablePrime

 Stream.iterate(BigInteger.valueOf(2), BigInteger::nextProbablePrime)
			.limit(168)
			.forEach(x -> System.out.format("%s\t", x)); 

或者针对 Java 9 的BigInteger.TWO

 Stream.iterate(BigInteger.TWO, BigInteger::nextProbablePrime)
			.limit(168)
			.forEach(x -> System.out.format("%s\t", x)); 

2.普通的旧爪哇咖啡

没有更多的 Java 8 流,回到基本。

PrintPrimeNumber2.java

 package com.mkyong.test;

import java.util.ArrayList;
import java.util.List;

public class PrintPrimeNumber2 {

    public static void main(String[] args) {

        List<Integer> collect = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
            if (isPrime(i)) {
                collect.add(i);
            }
        }

        for (Integer prime : collect) {
            System.out.format("%s\t", prime);
        }

        System.out.println("\nTotal: " + collect.size());

    }

    private static boolean isPrime(int number) {

        if (number <= 1) return false;    //  1 is not prime and also not composite

        for (int i = 2; i * i <= number; i++) {
            if (number % i == 0) {
                return false;
            }
        }
        return true;
    }

} 

3.厄拉多塞筛

厄拉多塞算法的这个筛子很快就能找到所有的质数。

Sieve of Eratosthenes

P.S 图片来自维基百科

概念是这样的:

  • 循环 1# p=2 =真,接下来 4,6,8,10,12,14…极限,所有+2 设置为假
  • Loop 2# p=3 = true,next 6{false,1#,ignore},9,12{false,1#,ignore},15,18{false,1#,ignore},21…limit,all +3 set false
  • 循环 3# p=4 =
  • 循环 4# p=5 =真,接下来的 10 个{假,1#,忽略},15 个{假,2#,忽略},20 个{假,1#,忽略}…全部+5 设置为假
  • 循环 5# p=6 =
  • 循环…直到极限,同样的想法。
  • 收集所有真=质数。

PrintPrimeNumber3

 package com.mkyong.test;

import java.util.Arrays;
import java.util.BitSet;
import java.util.LinkedList;
import java.util.List;

public class PrintPrimeNumber3 {

    public static void main(String[] args) {

        List<Integer> result = primes_soe_array(1000);

        result.forEach(x -> System.out.format("%s\t", x));

        System.out.println("\nTotal: " + result.size());

    }

    /**
     * Sieve of Eratosthenes, true = prime number
     */
    private static List<Integer> primes_soe(int limit) {

        BitSet primes = new BitSet(limit);
        primes.set(0, false);                       
        primes.set(1, false);                       
        primes.set(2, limit, true);

        for (int p = 2; p * p <= limit; p++) {
            if (primes.get(p)) {
                for (int j = p * 2; j <= limit; j += p) {
                    primes.set(j, false);
                }
            }
        }

        List<Integer> result = new LinkedList<>();
        for (int i = 0; i <= limit; i++) {
            if (primes.get(i)) {
                result.add(i);
            }
        }

        return result;

    }

    // Some developers prefer array.
    public static List<Integer> primes_soe_array(int limit) {

        boolean primes[] = new boolean[limit + 1];
        Arrays.fill(primes, true);
        primes[0] = false;
        primes[1] = false;

        for (int p = 2; p * p <= limit; p++) {
            if (primes[p]) {
                for (int j = p * 2; j <= limit; j += p) {
                    primes[j] = false;
                }
            }
        }

        List<Integer> result = new LinkedList<>();
        for (int i = 0; i <= limit; i++) {
            if (primes[i]) {
                result.add(i);
            }
        }
        return result;
    }

} 

有人能帮忙把上面的算法转换成纯 Java 8 流吗?🙂

参考

Java–从资源文件夹中读取文件

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/java/java-read-a-file-from-resources-folder/

Java resources folder

在 Java 中,我们可以使用getResourceAsStreamgetResource从类路径的resources文件夹或根目录中读取一个或多个文件。

getResourceAsStream方法返回一个InputStream

 // the stream holding the file content
  InputStream is = getClass().getClassLoader().getResourceAsStream("file.txt");

  // for static access, uses the class name directly
  InputStream is = JavaClassName.class.getClassLoader().getResourceAsStream("file.txt"); 

getResource方法返回一个URL并通常将其转换为一个File不在 JAR 文件中工作

 // get the file url, not working in JAR file.
  URL resource = getClass().getClassLoader().getResource("file.txt");
  if (resource == null) {
      throw new IllegalArgumentException("file not found!");
  } else {

      // failed if files have whitespaces or special characters
      //return new File(resource.getFile());

      return new File(resource.toURI());
  }

  // for static access
  // URL resource = JavaClassName.class.getClassLoader().getResource("fileName"); 

1.资源文件夹中的文件

1.1 查看src/main/resources中的文件,稍后我们将访问这些文件并打印出文件内容。

project structuresrc/main/resources/database.properties

 datasource.url=jdbc:mysql://localhost/mkyong?useSSL=false
datasource.username=root
datasource.password=password
datasource.driver-class-name=com.mysql.jdbc.Driver 

src/main/resources/json/file1.json

 {
  "name": "mkyong",
  "age": 38
} 

src/main/resources/json/file2.json

 {
  "name": "jack",
  "age": 40
} 

src/main/resources/json/sub/subfile1.json

 {
  "name": "sub",
  "age": 99
} 

1.2 默认情况下,Maven、Gradle 或 common Java practice 等构建工具会将所有文件从src/main/resources复制到target/classesbuild/classes的根目录下。因此,当我们试图从src/main/resources读取文件时,我们从项目类路径的根目录读取文件。

copy resources to classes

1.3 下面是一个 JAR 文件结构。通常,resources文件夹中的文件会复制到类路径的根目录。

Terminal

 $ jar -tf target/example.jar

META-INF/MANIFEST.MF
META-INF/
json/
json/sub/
json/file2.json
json/sub/subfile1.json
json/file1.json
database.properties
com/
com/mkyong/
com/mkyong/io/
com/mkyong/io/utils/
//... 

2.从资源文件夹中获取文件。

2.1 下面的例子演示了使用getResourceAsStreamgetResource方法从resources文件夹中读取文件json/file1.json并打印出文件内容。

  • getResource方法在 JAR 文件中不起作用。
  • getResourceAsStream方法在任何地方都有效。

FileResourcesUtils.java

 package com.mkyong.io.utils;

import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;

public class FileResourcesUtils {

    public static void main(String[] args) throws IOException {

        FileResourcesUtils app = new FileResourcesUtils();

        //String fileName = "database.properties";
        String fileName = "json/file1.json";

        System.out.println("getResourceAsStream : " + fileName);
        InputStream is = app.getFileFromResourceAsStream(fileName);
        printInputStream(is);

        System.out.println("\ngetResource : " + fileName);
        File file = app.getFileFromResource(fileName);
        printFile(file);

    }

    // get a file from the resources folder
    // works everywhere, IDEA, unit test and JAR file.
    private InputStream getFileFromResourceAsStream(String fileName) {

        // The class loader that loaded the class
        ClassLoader classLoader = getClass().getClassLoader();
        InputStream inputStream = classLoader.getResourceAsStream(fileName);

        // the stream holding the file content
        if (inputStream == null) {
            throw new IllegalArgumentException("file not found! " + fileName);
        } else {
            return inputStream;
        }

    }

    /*
        The resource URL is not working in the JAR
        If we try to access a file that is inside a JAR,
        It throws NoSuchFileException (linux), InvalidPathException (Windows)

        Resource URL Sample: file:java-io.jar!/json/file1.json
     */
    private File getFileFromResource(String fileName) throws URISyntaxException{

        ClassLoader classLoader = getClass().getClassLoader();
        URL resource = classLoader.getResource(fileName);
        if (resource == null) {
            throw new IllegalArgumentException("file not found! " + fileName);
        } else {

            // failed if files have whitespaces or special characters
            //return new File(resource.getFile());

            return new File(resource.toURI());
        }

    }

    // print input stream
    private static void printInputStream(InputStream is) {

        try (InputStreamReader streamReader =
                    new InputStreamReader(is, StandardCharsets.UTF_8);
             BufferedReader reader = new BufferedReader(streamReader)) {

            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

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

    }

    // print a file
    private static void printFile(File file) {

        List<String> lines;
        try {
            lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
            lines.forEach(System.out::println);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

} 

输出

Terminal

 getResourceAsStream : json/file1.json
{
  "name": "mkyong",
  "age": 38
}

getResource : json/file1.json
{
  "name": "mkyong",
  "age": 38
} 

2.2 现在,我们把项目打包成一个 JAR 文件,运行它;这一次,getResource将失败并返回NoSuchFileExceptionInvalidPathException。我们无法通过资源 URL 读取 JAR 文件中的文件。

在 Linux (Ubuntu)上运行 JAR 文件,它抛出NoSuchFileException

Terminal

 $ mvn clean package

$ java -jar target/java-io.jar

getResourceAsStream : json/file1.json
{
  "name": "mkyong",
  "age": 38
}

# for new File(resource.getFile());
getResource : json/file1.json
java.nio.file.NoSuchFileException: file:/home/mkyong/projects/core-java/java-io/target/java-io.jar!/json/file1.json
	at java.base/sun.nio.fs.UnixException.translateToIOException(UnixException.java:92)
	at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:111)
	at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:116)
	at java.base/sun.nio.fs.UnixFileSystemProvider.newByteChannel(UnixFileSystemProvider.java:219)
	at java.base/java.nio.file.Files.newByteChannel(Files.java:370)
	at java.base/java.nio.file.Files.newByteChannel(Files.java:421)
	at java.base/java.nio.file.spi.FileSystemProvider.newInputStream(FileSystemProvider.java:420)
	at java.base/java.nio.file.Files.newInputStream(Files.java:155)
	at java.base/java.nio.file.Files.newBufferedReader(Files.java:2838)
	at java.base/java.nio.file.Files.readAllLines(Files.java:3329)
	at com.mkyong.io.utils.FileResourcesUtils.printFile(FileResourcesUtils.java:135)
	at com.mkyong.io.utils.FileResourcesUtils.main(FileResourcesUtils.java:24)

# for new File(resource.toURI());
getResource : json/file1.json
Exception in thread "main" java.lang.IllegalArgumentException: URI is not hierarchical
	at java.base/java.io.File.<init>(File.java:420)
	at com.mkyong.io.utils.FileResourcesUtils.getFileFromResource(FileResourcesUtils.java:112)
	at com.mkyong.io.utils.FileResourcesUtils.main(FileResourcesUtils.java:29) 

在 Windows 上运行 JAR 文件,它抛出InvalidPathException

Terminal

 $ mvn clean package

$ java -jar target/java-io.jar

getResourceAsStream : json/file1.json
{
  "name": "mkyong",
  "age": 38
}

getResource : json/file1.json
Exception in thread "main" java.nio.file.InvalidPathException:
        Illegal char <:> at index 4: file:\C:\Users\mkyong\projects\core-java\java-io\target\java-io.jar!\json\file1.json

        at java.base/sun.nio.fs.WindowsPathParser.normalize(WindowsPathParser.java:182)
        at java.base/sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:153)
        at java.base/sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:77)
        at java.base/sun.nio.fs.WindowsPath.parse(WindowsPath.java:92)
        at java.base/sun.nio.fs.WindowsFileSystem.getPath(WindowsFileSystem.java:229)
        at java.base/java.io.File.toPath(File.java:2290)
        at com.mkyong.io.utils.FileResourcesUtils.printFile(FileResourcesUtils.java:166)
        at com.mkyong.io.utils.FileResourcesUtils.main(FileResourcesUtils.java:32) 

这个例子使用 Maven 插件maven-jar-plugin来创建 JAR 文件。

pom.xml

 <!-- Make this jar executable -->
  <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-jar-plugin</artifactId>
      <version>3.2.0</version>
      <configuration>
          <archive>
              <manifest>
                  <addClasspath>true</addClasspath>
                  <mainClass>com.mkyong.io.utils.FileResourcesUtils</mainClass>
              </manifest>
          </archive>
      </configuration>
  </plugin> 

3.从 resources 文件夹获取一个文件——单元测试

3.1 我们将测试资源放在文件夹src/test/resources中进行单元测试。通常,测试资源中的文件会复制到target/test-classes文件夹中。

resources for unit testssrc/test/resources/json/file1.json

 {
  "name": "unit test",
  "age": 38
} 

src/test/resources/database.properties

 datasource.url=jdbc:mysql://localhost/test?useSSL=false
datasource.username=test
datasource.password=password
datasource.driver-class-name=com.mysql.jdbc.Driver 

3.2 它的工作方式与我们从src/main/resources读取文件的方式相同。我们使用相同的getResourceAsStreamgetResource方法从src/test/resources中读取文件。

FileResourcesTest.java

 package com.mkyong.io;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;

// Unit test class
public class FileResourcesTest {

    @DisplayName("Test loading a JSON file")
    @Test
    void loadJSONTest() {

        String fileName = "json/file1.json";

        ClassLoader classLoader = getClass().getClassLoader();

        try (InputStream inputStream = classLoader.getResourceAsStream(fileName);
             InputStreamReader streamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
             BufferedReader reader = new BufferedReader(streamReader)) {

            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

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

    @DisplayName("Test loading a properties file")
    @Test
    void loadPropTest() throws IOException, URISyntaxException {

        String fileName = "database.properties";

        ClassLoader classLoader = getClass().getClassLoader();

        URL resource = classLoader.getResource(fileName);
        if (resource == null) {
            throw new IllegalArgumentException("file not found! " + fileName);
        }

        //File file = new File(resource.getFile());
        File file = new File(resource.toURI());

        List<String> lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
        lines.forEach(System.out::println);

    }

} 

输出

Terminal

 {
  "name": "unit test",
  "age": 38
}

datasource.url=jdbc:mysql://localhost/test?useSSL=false
datasource.username=test
datasource.password=password
datasource.driver-class-name=com.mysql.jdbc.Driver 

4.从资源文件夹中获取所有文件。(非 JAR 环境)

如果我们不知道确切的文件名,并且想要读取所有文件,包括 resources 文件夹中的子文件夹文件,我们可以使用 NIO Files.walk轻松地访问和读取文件。

4.1 以下示例使用Files.walk从文件夹src/main/resources/json中读取所有文件:

FileResourcesUtils.java

 package com.mkyong.io.utils;

import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

public class FileResourcesUtils {

    public static void main(String[] args) throws IOException {

        FileResourcesUtils app = new FileResourcesUtils();

        // read all files from a resources folder
        try {

            // files from src/main/resources/json
            List<File> result = app.getAllFilesFromResource("json");
            for (File file : result) {
                System.out.println("file : " + file);
                printFile(file);
            }

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

    }

    private List<File> getAllFilesFromResource(String folder)
        throws URISyntaxException, IOException {

        ClassLoader classLoader = getClass().getClassLoader();

        URL resource = classLoader.getResource(folder);

        // dun walk the root path, we will walk all the classes
        List<File> collect = Files.walk(Paths.get(resource.toURI()))
                .filter(Files::isRegularFile)
                .map(x -> x.toFile())
                .collect(Collectors.toList());

        return collect;
    }

    // print a file
    private static void printFile(File file) {

        List<String> lines;
        try {
            lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
            lines.forEach(System.out::println);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

} 

输出

Terminal

 file : /home/mkyong/projects/core-java/java-io/target/classes/json/file1.json
{
"name": "mkyong",
"age": 38
}

file : /home/mkyong/projects/core-java/java-io/target/classes/json/file2.json
{
"name": "jack",
"age": 40
}

file : /home/mkyong/projects/core-java/java-io/target/classes/json/sub/subfile1.json
{
"name": "sub",
"age": 99
} 

4.2 但是,例 4.1 中的标准Files.walk不能直接访问 JAR 文件中的文件,尝试在 JAR 环境中运行例 4.1,它抛出FileSystemNotFoundException

Terminal

 $ mvn clean package

$ java -jar target/java-io.jar
Exception in thread "main" java.nio.file.FileSystemNotFoundException
        at jdk.zipfs/jdk.nio.zipfs.ZipFileSystemProvider.getFileSystem(ZipFileSystemProvider.java:169)
        at jdk.zipfs/jdk.nio.zipfs.ZipFileSystemProvider.getPath(ZipFileSystemProvider.java:155)
        at java.base/java.nio.file.Path.of(Path.java:208)
        at java.base/java.nio.file.Paths.get(Paths.java:97)
        at com.mkyong.io.utils.FileResourcesUtils.getAllFilesFromResource(FileResourcesUtils.java:128)
        at com.mkyong.io.utils.FileResourcesUtils.main(FileResourcesUtils.java:35) 

5.从资源文件夹中获取所有文件。(JAR 版本)

5.1 这个例子展示了如何通过FileSystems和 URI jar:file:xxx.jarFiles.walk一个 JAR 文件中的一个文件夹。

这个想法是:

  • File 使用FileSystems遍历 JAR 文件中的文件夹,并获取所有文件名,参见getPathsFromResourceJAR()
  • 循环所有文件名,像例 2.1 一样访问并打印每个文件,见getFileFromResourceAsStream()

FileResourcesUtils.java

 package com.mkyong.io.utils;

import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class FileResourcesUtils {

    public static void main(String[] args) throws IOException {

        FileResourcesUtils app = new FileResourcesUtils();

        // Sample 3 - read all files from a resources folder (JAR version)
        try {

            // get paths from src/main/resources/json
            List<Path> result = app.getPathsFromResourceJAR("json");
            for (Path path : result) {
                System.out.println("Path : " + path);

                String filePathInJAR = path.toString();
                // Windows will returns /json/file1.json, cut the first /
                // the correct path should be json/file1.json
                if (filePathInJAR.startsWith("/")) {
                    filePathInJAR = filePathInJAR.substring(1, filePathInJAR.length());
                }

                System.out.println("filePathInJAR : " + filePathInJAR);

                // read a file from resource folder
                InputStream is = app.getFileFromResourceAsStream(filePathInJAR);
                printInputStream(is);
            }

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

    }

    // get a file from the resources folder
    // works everywhere, IDEA, unit test and JAR file.
    private InputStream getFileFromResourceAsStream(String fileName) {

        // The class loader that loaded the class
        ClassLoader classLoader = getClass().getClassLoader();
        InputStream inputStream = classLoader.getResourceAsStream(fileName);

        // the stream holding the file content
        if (inputStream == null) {
            throw new IllegalArgumentException("file not found! " + fileName);
        } else {
            return inputStream;
        }

    }

    // Get all paths from a folder that inside the JAR file
    private List<Path> getPathsFromResourceJAR(String folder)
        throws URISyntaxException, IOException {

        List<Path> result;

        // get path of the current running JAR
        String jarPath = getClass().getProtectionDomain()
                .getCodeSource()
                .getLocation()
                .toURI()
                .getPath();
        System.out.println("JAR Path :" + jarPath);

        // file walks JAR
        URI uri = URI.create("jar:file:" + jarPath);
        try (FileSystem fs = FileSystems.newFileSystem(uri, Collections.emptyMap())) {
            result = Files.walk(fs.getPath(folder))
                    .filter(Files::isRegularFile)
                    .collect(Collectors.toList());
        }

        return result;

    }

    // print input stream
    private static void printInputStream(InputStream is) {

        try (InputStreamReader streamReader = new InputStreamReader(is, StandardCharsets.UTF_8);
             BufferedReader reader = new BufferedReader(streamReader)) {

            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

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

    }

} 

输出

Terminal

 $ java -jar target/java-io.jar

JAR Path :/C:/Users/mkyong/projects/core-java/java-io/target/java-io.jar

Path : /json/file2.json
filePathInJAR : json/file2.json
{
  "name": "jack",
  "age": 40
}

Path : /json/file1.json
filePathInJAR : json/file1.json
{
  "name": "mkyong",
  "age": 38
}

Path : /json/sub/subfile1.json
filePathInJAR : json/sub/subfile1.json
{
  "name": "sub",
  "age": 99
} 

下载源代码

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

$ cd java-io

参考

Java 正则表达式示例

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/java/java-regular-expression-examples/

Java 8 流和正则表达式示例。

Note
Learn the basic regular expression at Wikipedia

1.字符串匹配(正则表达式)

1.1 本例中,检查字符串是否为数字。

JavaRegEx1.java

 package com.mkyong.regex;

import java.util.Arrays;
import java.util.List;

public class JavaRegEx1 {

    public static void main(String[] args) {

        List<String> numbers = Arrays.asList("1", "20", "A1", "333", "A2A211");

        for (String number : numbers) {

            if (number.matches("\\d+")) {
                System.out.println(number);		// 1, 20, 333
            }
        }

        // Java 8 stream example
        numbers.stream()
                .filter(x -> x.matches("\\d+"))
                .forEach(System.out::println);

    }
} 

输出

 1
20
333

1
20
333 

2.String.replaceAll(正则表达式,替换)

2.1 本例用#替换所有数字

JavaRegEx2.java

 package com.mkyong.regex;

import java.util.Arrays;
import java.util.List;

public class JavaRegEx2 {

    public static void main(String[] args) {

        List<String> numbers = Arrays.asList("1", "20", "A1", "333", "A2A211");

        for (String number : numbers) {
            System.out.println(number.replaceAll("\\d", "#"));
        }

        // Java 8 stream example
        numbers.stream()
                .map(x -> x.replaceAll("\\d", "#"))
                .forEach(System.out::println);

    }
} 

输出

 #
##
A#
###
A#A###

#
##
A#
###
A#A### 

3.模式和匹配器

3.1 从字符串列表中查找所有数字。

JavaRegEx3.java

 package com.mkyong.regex;

import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JavaRegEx3 {

    public static void main(String[] args) {

        List<String> numbers = Arrays.asList("1", "20", "A1", "333", "A2A211");

        Pattern pattern = Pattern.compile("\\d+");

        for (String number : numbers) {

            Matcher matcher = pattern.matcher(number);
            while (matcher.find()) {
                System.out.println(matcher.group(0));
            }

        }

	}
} 

输出

 1
20
1
333
2
211 

3.2 对于 Java 8 流,首先我们尝试这样转换:

 numbers.stream()
		.map(x -> pattern.matcher(x))
		.filter(Matcher::find)          // A2A211, will it loop?
		.map(x -> x.group())
		.forEach(x -> System.out.println(x)); 

输出,最后一个 211 不见了?

 1
20
1
333
2 

该流不能循环使用.filter来获取所有的组,我们需要一个自定义的Spliteratorshack

JavaRegEx4.java

 package com.mkyong.regex;

import java.util.Arrays;
import java.util.List;
import java.util.Spliterators;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.StreamSupport;

public class JavaRegEx4 {

    public static void main(String[] args) {

        List<String> numbers = Arrays.asList("1", "20", "A1", "333", "A2A211");

        Pattern pattern = Pattern.compile("\\d+");

        numbers.stream()
                .flatMap(x ->
                        StreamSupport.stream(new MatchItr(pattern.matcher(x)), false))
                .forEach(x -> System.out.println(x));

    }

    final static class MatchItr extends Spliterators.AbstractSpliterator<String> {
        private final Matcher matcher;

        MatchItr(Matcher m) {
            super(m.regionEnd() - m.regionStart(), ORDERED | NONNULL);
            matcher = m;
        }

        public boolean tryAdvance(Consumer<? super String> action) {
            if (!matcher.find()) return false;
            action.accept(matcher.group());
            return true;
        }
    }

} 

输出

 1
20
1
333
2
211 

4.Java 9,Scanner.findAll(regex)

4.1 Java 9,我们可以使用Scanner.findAll(regex)返回一个匹配结果流,匹配提供的正则表达式。

 Scanner scan = new Scanner("A2A211");
	List<String> collect = scan
			.findAll("\\d+")
			.map(m -> m.group())
			.collect(Collectors.toList());
	collect.forEach(x -> System.out.println(x)); 

输出

 2
211 

最终版本,用 Java 9。

JavaRegEx5.java

 package com.mkyong.regex;

import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class JavaRegEx5 {

    public static void main(String[] args) {

        List<String> numbers = Arrays.asList("1", "20", "A1", "333", "A2A211");

        Pattern pattern = Pattern.compile("\\d+");

        List<String> collect = numbers.stream()
                .map(x -> new Scanner(x).findAll(pattern)
                        .map(m -> m.group())
                        .collect(Collectors.toList())
                )
                .flatMap(List::stream)
                .collect(Collectors.toList());

        collect.forEach(x -> System.out.println(x));

    }

} 

输出

 1
20
1
333
2
211 

参考

Java–在远程服务器上运行 shell 脚本

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/java/java-run-shell-script-on-a-remote-server/

本文展示了如何使用 JSch 库通过 SSH 在远程服务器上运行或执行 shell 脚本。

pom.xml

 <dependency>
      <groupId>com.jcraft</groupId>
      <artifactId>jsch</artifactId>
      <version>0.1.55</version>
  </dependency> 

1.运行远程 Shell 脚本

这个 Java 示例使用 JSch 通过 SSH 登录一个远程服务器(使用密码),并运行一个 shell 脚本hello.sh

1.1 下面是一个远程服务器中的简单 shell 脚本,IP 地址是1.1.1.1

hello.sh

 #! /bin/sh
echo "hello $1\n"; 

分配了执行权限。

Terminal

 $ chmod +x hello.sh 

1.2 在本地,我们可以使用下面的代码在远程服务器上运行或执行上面的 shell 脚本。

RunRemoteScript.java

 package com.mkyong.io.howto;

import com.jcraft.jsch.*;

import java.io.IOException;
import java.io.InputStream;

public class RunRemoteScript {

    private static final String REMOTE_HOST = "1.1.1.1";
    private static final String USERNAME = "";
    private static final String PASSWORD = "";
    private static final int REMOTE_PORT = 22;
    private static final int SESSION_TIMEOUT = 10000;
    private static final int CHANNEL_TIMEOUT = 5000;

    public static void main(String[] args) {

        String remoteShellScript = "/root/hello.sh";

        Session jschSession = null;

        try {

            JSch jsch = new JSch();
            jsch.setKnownHosts("/home/mkyong/.ssh/known_hosts");
            jschSession = jsch.getSession(USERNAME, REMOTE_HOST, REMOTE_PORT);

            // not recommend, uses jsch.setKnownHosts
            //jschSession.setConfig("StrictHostKeyChecking", "no");

            // authenticate using password
            jschSession.setPassword(PASSWORD);

            // 10 seconds timeout session
            jschSession.connect(SESSION_TIMEOUT);

            ChannelExec channelExec = (ChannelExec) jschSession.openChannel("exec");

            // run a shell script
            channelExec.setCommand("sh " + remoteShellScript + " mkyong");

            // display errors to System.err
            channelExec.setErrStream(System.err);

            InputStream in = channelExec.getInputStream();

            // 5 seconds timeout channel
            channelExec.connect(CHANNEL_TIMEOUT);

            // read the result from remote server
            byte[] tmp = new byte[1024];
            while (true) {
                while (in.available() > 0) {
                    int i = in.read(tmp, 0, 1024);
                    if (i < 0) break;
                    System.out.print(new String(tmp, 0, i));
                }
                if (channelExec.isClosed()) {
                    if (in.available() > 0) continue;
                    System.out.println("exit-status: "
                         + channelExec.getExitStatus());
                    break;
                }
                try {
                    Thread.sleep(1000);
                } catch (Exception ee) {
                }
            }

            channelExec.disconnect();

        } catch (JSchException | IOException e) {

            e.printStackTrace();

        } finally {
            if (jschSession != null) {
                jschSession.disconnect();
            }
        }

    }
} 

输出

Terminal

 hello mkyong

exit-status: 0 

注意
对于 JSch UnknownHostKey异常,请将远程服务器 ip 添加到.ssh/known_hosts中,读取这个

2.运行远程命令

2.1 下面的例子与上面的例子#1 非常相似。相反,它使用私钥id_rsa来 SSH 登录远程服务器,确保远程服务器正确配置了公钥

 jsch.addIdentity("/home/mkyong/.ssh/id_rsa"); 

2.2 并且我们把命令改成了ls,剩下的代码都是一样的。

 channelExec.setCommand("ls -lsah"); 

2.3 这个 Java 示例运行一个远程服务器命令ls -lsah来显示目录列表。

RunRemoteCommand.java

 package com.mkyong.io.howto;

import com.jcraft.jsch.*;

import java.io.IOException;
import java.io.InputStream;

public class RunRemoteCommand {

    private static final String REMOTE_HOST = "1.1.1.1";
    private static final String USERNAME = "";
    private static final int REMOTE_PORT = 22;
    private static final int SESSION_TIMEOUT = 10000;
    private static final int CHANNEL_TIMEOUT = 5000;

    public static void main(String[] args) {

        Session jschSession = null;

        try {

            JSch jsch = new JSch();
            jsch.setKnownHosts("/home/mkyong/.ssh/known_hosts");
            jschSession = jsch.getSession(USERNAME, REMOTE_HOST, REMOTE_PORT);

            // not recommend, uses jsch.setKnownHosts
            //jschSession.setConfig("StrictHostKeyChecking", "no");

            // authenticate using private key
            jsch.addIdentity("/home/mkyong/.ssh/id_rsa");

            // 10 seconds timeout session
            jschSession.connect(SESSION_TIMEOUT);

            ChannelExec channelExec = (ChannelExec) jschSession.openChannel("exec");

            // Run a command
            channelExec.setCommand("ls -lsah");

            // display errors to System.err
            channelExec.setErrStream(System.err);

            InputStream in = channelExec.getInputStream();

            // 5 seconds timeout channel
            channelExec.connect(CHANNEL_TIMEOUT);

            // read the result from remote server
            byte[] tmp = new byte[1024];
            while (true) {
                while (in.available() > 0) {
                    int i = in.read(tmp, 0, 1024);
                    if (i < 0) break;
                    System.out.print(new String(tmp, 0, i));
                }
                if (channelExec.isClosed()) {
                    if (in.available() > 0) continue;
                    System.out.println("exit-status: "
                        + channelExec.getExitStatus());
                    break;
                }
                try {
                    Thread.sleep(1000);
                } catch (Exception ee) {
                }
            }

            channelExec.disconnect();

        } catch (JSchException | IOException e) {

            e.printStackTrace();

        } finally {
            if (jschSession != null) {
                jschSession.disconnect();
            }
        }

    }
} 

输出

Terminal

 otal 48K
4.0K drwx------  6 root root 4.0K Aug  4 07:57 .
4.0K drwxr-xr-x 22 root root 4.0K Sep 11  2019 ..
8.0K -rw-------  1 root root 5.5K Aug  3 08:50 .bash_history
4.0K -rw-r--r--  1 root root  570 Jan 31  2010 .bashrc
4.0K drwx------  2 root root 4.0K Dec 15  2019 .cache
4.0K drwx------  2 root root 4.0K Dec 15  2019 .docker
4.0K -rwxr-xr-x  1 root root   31 Aug  4 07:54 hello.sh
4.0K -rw-r--r--  1 root root  148 Aug 17  2015 .profile
4.0K drwx------  2 root root 4.0K Aug  3 05:32 .ssh
4.0K drwxr-xr-x  2 root root 4.0K Aug  3 04:42 test
4.0K -rw-------  1 root root 1.2K Aug  4 07:57 .viminfo
exit-status: 0 

2.4 现在,我们测试一个无效命令abc

RunRemoteCommand.java

 // Run a invalid command
  channelExec.setCommand("abc"); 

输出

Terminal

 bash: abc: command not found
exit-status: 127 

错误将输出到System.err

下载源代码

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

$ cd java-io

参考

Java . security . cert . certificate 异常:找不到与本地主机匹配的名称

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/webservices/jax-ws/java-security-cert-certificateexception-no-name-matching-localhost-found/

问题

配置了 Tomcat 来支持 SSL 并部署了这个简单 hello world web 服务。并通过 SSL 连接使用以下客户端连接到已部署的 web 服务:

 package com.mkyong.client;

import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;

import com.mkyong.ws.HelloWorld;

public class HelloWorldClient{

	public static void main(String[] args) throws Exception {

	URL url = new URL("https://localhost:8443/HelloWorld/hello?wsdl");
        QName qname = new QName("http://ws.mkyong.com/", "HelloWorldImplService");

        Service service = Service.create(url, qname);
        HelloWorld hello = service.getPort(HelloWorld.class);
        System.out.println(hello.getHelloWorldAsString());

    }
} 

命中“未找到与本地主机匹配的名称”异常:

 Caused by: javax.net.ssl.SSLHandshakeException: 
    java.security.cert.CertificateException: No name matching localhost found
	at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:174)
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1611)
	at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:187)
	at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:181)
	......
Caused by: java.security.cert.CertificateException: No name matching localhost found
	at sun.security.util.HostnameChecker.matchDNS(HostnameChecker.java:210)
	at sun.security.util.HostnameChecker.match(HostnameChecker.java:77)
	...... 

解决办法

这个问题和解决方案在这篇文章中有很好的解释,您可以为您的“ localhost 开发环境使用一个传输安全(SSL)解决方案。

要修复它,添加一个javax.net.ssl.HostnameVerifier()方法来覆盖现有的主机名验证器,如下所示:

 package com.mkyong.client;

import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;

import com.mkyong.ws.HelloWorld;

public class HelloWorldClient{

	static {
	    //for localhost testing only
	    javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(
	    new javax.net.ssl.HostnameVerifier(){

	        public boolean verify(String hostname,
	                javax.net.ssl.SSLSession sslSession) {
	            if (hostname.equals("localhost")) {
	                return true;
	            }
	            return false;
	        }
	    });
	}

	public static void main(String[] args) throws Exception {

	URL url = new URL("https://localhost:8443/HelloWorld/hello?wsdl");
        QName qname = new QName("http://ws.mkyong.com/", "HelloWorldImplService");

        Service service = Service.create(url, qname);
        HelloWorld hello = service.getPort(HelloWorld.class);
        System.out.println(hello.getHelloWorldAsString());

    }
} 

输出

 Hello World JAX-WS 

它现在工作正常。

jax-ws web services (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190223080735/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

Java 序列化和反序列化示例

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/java/java-serialization-examples/

在 Java 中,Serialization的意思是将 Java 对象转换成字节流;Deserialization表示将序列化对象的字节流转换回原来的 Java 对象。

目录。

1。Hello World Java 序列化

在 Java 中,我们必须实现Serializable接口来支持序列化和反序列化。

1.1 一个 Java 对象。

Person.java

 package com.mkyong.io.object;

import java.io.Serializable;
import java.math.BigDecimal;

public class Person implements Serializable {

    private String name;
    private int age;
    private BigDecimal salary;

    // getters setters constructor
} 

1.2 Java 对象Person.java的完整 Java 序列化和反序列化示例。

HelloSerialization.java

 package com.mkyong.io.object;

import java.io.*;
import java.math.BigDecimal;

public class HelloSerialization {

    public static void main(String[] args) {

        Person person = new Person("mkyong", 40, new BigDecimal(900));

        byte[] bytes = convertObjectToBytes(person);

        Person p = (Person) convertBytesToObject(bytes);

        System.out.println(p);
    }

    // Convert object to byte[]
    public static byte[] convertObjectToBytes(Object obj) {
        ByteArrayOutputStream boas = new ByteArrayOutputStream();
        try (ObjectOutputStream ois = new ObjectOutputStream(boas)) {
            ois.writeObject(obj);
            return boas.toByteArray();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        throw new RuntimeException();
    }

    // Convert byte[] to object
    public static Object convertBytesToObject(byte[] bytes) {
        InputStream is = new ByteArrayInputStream(bytes);
        try (ObjectInputStream ois = new ObjectInputStream(is)) {
            return ois.readObject();
        } catch (IOException | ClassNotFoundException ioe) {
            ioe.printStackTrace();
        }
        throw new RuntimeException();
    }

} 

输出

Terminal

 Person{name='mkyong', age=40, salary=900} 

2。Java . io . notserializableexception

如果我们序列化一个没有实现Serializable接口的对象,Java 抛出java.io.NotSerializableException

Person.java

 public class Person {

    private String name;
    private int age;
    private BigDecimal salary;

    // getters setters constructor
} 

HelloSerialization.java

 Person person = new Person("mkyong", 40, new BigDecimal(900));

  byte[] bytes = convertObjectToBytes(person); 

输出

Terminal

 java.io.NotSerializableException: com.mkyong.io.object.Person
  	at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1197)
  	at java.base/java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:354)
  	at com.mkyong.io.object.HelloSerialization.convertObjectToBytes(HelloSerialization.java:22)
  	at com.mkyong.io.object.HelloSerialization.main(HelloSerialization.java:12)
  Exception in thread "main" java.lang.RuntimeException
  	at com.mkyong.io.object.HelloSerialization.convertObjectToBytes(HelloSerialization.java:27)
  	at com.mkyong.io.object.HelloSerialization.main(HelloSerialization.java:12) 

3。什么是 serialVersionUID?

如果serialVersionUID丢失,JVM 将自动创建它。serialVersionUID类似于版本号;简而言之,如果我们用1L保存一个对象,我们需要提供相同的1L来读取该对象,否则会遇到不兼容的错误。

Person.java

 public class Person implements Serializable {

    private static final long serialVersionUID = 1L;
    //...
} 

例如,我们将一个带有serialVersionUID = 1L的对象保存到一个文件名person.obj中。稍后,我们从对象中添加或删除一些字段,并将serialVersionUID更新为2L。现在,读取person.obj文件,尝试将其转换回修改后的对象;由于两者serialVersionUID不同,我们会遇到以下不兼容的错误:

Terminal

 Exception in thread "main" java.io.InvalidClassException: com.mkyong.io.object.Person;

  local class incompatible: stream classdesc serialVersionUID = 1, local class serialVersionUID = 2

	at java.base/java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:689)
	at java.base/java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1903)
	at java.base/java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1772)
	at java.base/java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2060)
	at java.base/java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1594)
	at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:430)
	at com.mkyong.io.object.ObjectUtils.readObject(ObjectUtils.java:25)
	at com.mkyong.io.object.ObjectUtils.main(ObjectUtils.java:38) 

4。什么是瞬变?

在序列化过程中,JVM 忽略所有的transient字段。如果我们需要在序列化过程中排除特定的对象字段,将它们标记为transient.

Person.java

 public class Person implements Serializable {

    private String name;
    private int age;

    //exclude this field
    private transient BigDecimal salary;

    // getters setters constructor
} 
 Person person = new Person("mkyong", 40, new BigDecimal(900));

  byte[] bytes = convertObjectToBytes(person);

  Person p = (Person) convertBytesToObject(bytes);

  System.out.println(p); 

输出

Terminal

 Person{name='mkyong', age=40, salary=null} 

5。将对象序列化到文件

此示例将 Java 对象序列化为文件,并将文件反序列化回原始对象。

HelloSerializationFile.java

 package com.mkyong.io.object;

import java.io.*;
import java.math.BigDecimal;

public class HelloSerializationFile {

  public static void main(String[] args) throws IOException, ClassNotFoundException {

      Person person = new Person("mkyong", 50, new BigDecimal(1000));

      File file = new File("person.anything");

      writeObjectToFile(person, file);

      Person p = readObjectFromFile(file);

      System.out.println(p);

  }

  // Serialization
  // Save object into a file.
  public static void writeObjectToFile(Person obj, File file) throws IOException {
      try (FileOutputStream fos = new FileOutputStream(file);
           ObjectOutputStream oos = new ObjectOutputStream(fos)) {
          oos.writeObject(obj);
          oos.flush();
      }
  }

  // Deserialization
  // Get object from a file.
  public static Person readObjectFromFile(File file) throws IOException, ClassNotFoundException {
      Person result = null;
      try (FileInputStream fis = new FileInputStream(file);
           ObjectInputStream ois = new ObjectInputStream(fis)) {
          result = (Person) ois.readObject();
      }
      return result;
  }

} 

6。为什么需要 Java 中的序列化?

阅读这篇文章Brian Goetz——迈向更好的序列化

Java 序列化的一些用例:

  1. 套接字、应用程序、客户端和服务器之间的数据交换格式。它喜欢 JSON 或 XML,但采用字节格式。
  2. 序列化是几项关键 Java 技术的基础,包括 Java 远程方法调用(Java RMI) 、公共对象请求代理架构(CORBA),以及分布式计算,如 Java 命名和目录接口(JNDI)、Java
    管理扩展(JMX)和 Java 消息传递(JMS)。
  3. 对于作为轻量级持久性的游戏,我们可以在磁盘上序列化当前游戏的状态,并在以后恢复它。文件是字节格式的,我们不能轻易修改敏感游戏的数据,比如武器或者金钱。
  4. 保存一个对象图磁盘用于进一步分析,比如 UML 类图。
  5. 服务器集群和恢复会话。例如,如果其中一个服务器关闭或重启,服务器集群(服务器 A 和服务器 B)需要同步会话。当服务器 A 关闭时,它将对象保存为HttpSession的属性,并通过网络发送给服务器 B,服务器 B 可以从HttpSession恢复对象。阅读这篇的帖子

对于数据交换,考虑人类可读的数据交换格式,如 JSONXMLGoogle 协议缓冲区

7。不可信数据的反序列化

但是,从不受信任的字节流进行反序列化是危险的,会导致以下 Java 漏洞:

  • 一路向下——以嵌套容器为目标,比如列表中的列表。
  • 串行拒绝服务(DOS)
  • 河豚
  • 远程代码执行(RCE)

延伸阅读

7.1 反序列化和堆栈溢出

反序列化下面的字节流,它抛出StackOverflowError

StackOverflowExample.java

 package com.mkyong.io.object.attack;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class StackOverflowExample {

    public static void main(String[] args) {

        System.out.println(bomb().length);

        deserialize(bomb());  // throws StackOverflow

        System.out.println("Done");
    }

    static byte[] bomb() {
        HashMap map = new HashMap();
        List list = new ArrayList();
        map.put(list, "");
        list.add(list);
        return serialize(map);
    }

    public static byte[] serialize(Object o) {
        ByteArrayOutputStream ba = new ByteArrayOutputStream();
        try {
            new ObjectOutputStream(ba).writeObject(o);
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }
        return ba.toByteArray();
    }

    public static Object deserialize(byte[] bytes) {
        try {
            return new ObjectInputStream(
                    new ByteArrayInputStream(bytes)).readObject();
        } catch (IOException | ClassNotFoundException e) {
            throw new IllegalArgumentException(e);
        }
    }

} 

输出

Terminal

 Exception in thread "main" java.lang.StackOverflowError
  at java.base/java.util.ArrayList.hashCode(ArrayList.java:582)
  at java.base/java.util.ArrayList.hashCodeRange(ArrayList.java:595)
  //... 

7.2 反序列化和拒绝服务攻击(DoS 攻击)

反序列化下面的字节流将保持进程运行,挂起,并慢慢降低系统速度,这是典型的 DoS 攻击。

DosExample.java

 package com.mkyong.io.object.attack;

import java.io.*;
import java.util.HashSet;
import java.util.Set;

public class DosExample {

  public static void main(String[] args) throws Exception {
      System.out.println(bomb().length);

      deserialize(bomb());  // Dos here

      System.out.println("Done");
  }

  static byte[] bomb() {
      Set<Object> root = new HashSet<>();
      Set<Object> s1 = root;
      Set<Object> s2 = new HashSet<>();
      for (int i = 0; i < 100; i++) {
          Set<Object> t1 = new HashSet<>();
          Set<Object> t2 = new HashSet<>();
          t1.add("test-" + i); // make it not equal to t2

          s1.add(t1); // root also add set
          s1.add(t2);

          s2.add(t1);
          s2.add(t2);

          s1 = t1;    // reference to t1, so that `root` can add new set from the last t1
          s2 = t2;
      }
      return serialize(root);
  }

  public static byte[] serialize(Object o) {
      ByteArrayOutputStream ba = new ByteArrayOutputStream();
      try {
          new ObjectOutputStream(ba).writeObject(o);
      } catch (IOException e) {
          throw new IllegalArgumentException(e);
      }
      return ba.toByteArray();
  }

  public static Object deserialize(byte[] bytes) {
      try {
          return new ObjectInputStream(
                  new ByteArrayInputStream(bytes)).readObject();
      } catch (IOException | ClassNotFoundException e) {
          throw new IllegalArgumentException(e);
      }
  }

} 

输出

Terminal

 // keep the process running, hanging there
  // and slowly slowing down the system, a classic DoS attack. 

8。Java 9 反序列化过滤器

Java 9, JEP 290 引入了反序列化过滤器ObjectInputFilter来过滤传入的序列化数据。

8.1 stack overflow 的反序列化过滤器

用反序列化过滤器maxdepth=2重构上面的StackOverflowExample.java示例。如果我们重新运行程序,反序列化过程将停止并返回filter status: REJECTED

StackOverflowExample.java

 package com.mkyong.io.object.attack;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class StackOverflowExample {

  public static void main(String[] args) {
      System.out.println(bomb().length);

      //deserialize(bomb());  // throws StackOverflow

      ObjectInputFilter filter =
              ObjectInputFilter.Config.createFilter(
                      "maxdepth=2;java.base/*;!*");

      // java.io.InvalidClassException: filter status: REJECTED
      deserializeFilter(bomb(), filter);  

      System.out.println("Done");
  }

  static byte[] bomb() {
      HashMap map = new HashMap();
      List list = new ArrayList();
      map.put(list, "");
      list.add(list);
      return serialize(map);
  }

  public static byte[] serialize(Object o) {
      ByteArrayOutputStream ba = new ByteArrayOutputStream();
      try {
          new ObjectOutputStream(ba).writeObject(o);
      } catch (IOException e) {
          throw new IllegalArgumentException(e);
      }
      return ba.toByteArray();
  }

  public static Object deserializeFilter(byte[] bytes, ObjectInputFilter filter) {

      try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
           ObjectInputStream ois = new ObjectInputStream(bais)) {

          // add filter before readObject
          ois.setObjectInputFilter(filter);

          return ois.readObject();
      } catch (IOException | ClassNotFoundException e) {
          throw new IllegalArgumentException(e);
      }

  }

} 

输出

Terminal

 Exception in thread "main" java.lang.IllegalArgumentException: java.io.InvalidClassException: filter status: REJECTED
  at com.mkyong.io.object.attack.StackOverflowExample.deserializeFilter(StackOverflowExample.java:70)
  at com.mkyong.io.object.attack.StackOverflowExample.main(StackOverflowExample.java:27)
  Caused by: java.io.InvalidClassException: filter status: REJECTED 

8.2 针对 DoS 攻击的反序列化过滤器

maxdepth反序列化过滤器重构上面的DosExample.java示例,以阻止 DoS 攻击。

DosExample.java

 package com.mkyong.io.object.attack;

import java.io.*;
import java.util.HashSet;
import java.util.Set;

public class DosExample {

  public static void main(String[] args) throws Exception {
      System.out.println(bomb().length);

      //deserialize(bomb());  // Dos here

      ObjectInputFilter filter =
              ObjectInputFilter.Config.createFilter(
                      "maxdepth=10;java.base/*;!*");

      deserializeFilter(bomb(), filter);  // Dos here

      System.out.println("Done");
  }

  static byte[] bomb() {
      Set<Object> root = new HashSet<>();
      Set<Object> s1 = root;
      Set<Object> s2 = new HashSet<>();
      for (int i = 0; i < 100; i++) {
          Set<Object> t1 = new HashSet<>();
          Set<Object> t2 = new HashSet<>();
          t1.add("test-" + i); // make it not equal to t2

          s1.add(t1); // root also add set
          s1.add(t2);

          s2.add(t1);
          s2.add(t2);

          s1 = t1;    // reference to t1, so that `root` can add new set from the last t1
          s2 = t2;
      }
      return serialize(root);
  }

  public static byte[] serialize(Object o) {
      ByteArrayOutputStream ba = new ByteArrayOutputStream();
      try {
          new ObjectOutputStream(ba).writeObject(o);
      } catch (IOException e) {
          throw new IllegalArgumentException(e);
      }
      return ba.toByteArray();
  }

  public static Object deserializeFilter(byte[] bytes, ObjectInputFilter filter) {

      try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
           ObjectInputStream ois = new ObjectInputStream(bais)) {

          // add filter before readObject
          ois.setObjectInputFilter(filter);

          return ois.readObject();
      } catch (IOException | ClassNotFoundException e) {
          throw new IllegalArgumentException(e);
      }

  }

} 

如果我们重新运行程序,反序列化过程将停止并返回filter status: REJECTED

Terminal

 Exception in thread "main" java.lang.IllegalArgumentException:
  java.io.InvalidClassException: filter status: REJECTED
  at com.mkyong.io.object.attack.DosExample.deserializeFilter(DosExample.java:74)
  at com.mkyong.io.object.attack.DosExample.main(DosExample.java:19) 

阅读关于序列化过滤的官方指南。

9。Java 17 特定于上下文的反序列化过滤器

Java 17 JEP 415 引入了一个过滤器工厂,它允许动态或上下文相关地选择不同的反序列化过滤器,参考 Java 17 过滤器工厂示例

下载源代码

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

$ CD Java-io/com/mkyong/io/object

参考文献

java.sql.SQLException:不允许操作:序号绑定和命名绑定不能组合!

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/jdbc/java-sql-sqlexception-operation-not-allowed-ordinal-binding-and-named-binding-cannot-be-combined/

顺序绑定或索引绑定:

 String name = stat.getString(2);
	BigDecimal salary = stat.getBigDecimal(3);
	Timestamp createdDate = stat.getTimestamp(4); 

命名绑定:

 String name = stat.getString("NAME");
	BigDecimal salary = stat.getBigDecimal("SALARY");
	Timestamp createdDate = stat.getTimestamp("CREATED_DATE"); 

如果我们像这样混合两者:

 String name = stat.getString(2);
	BigDecimal salary = stat.getBigDecimal("SALARY");
	Timestamp createdDate = stat.getTimestamp(4); 

错误:

 java.sql.SQLException: operation not allowed: 
		Ordinal binding and Named binding cannot be combined! 

JDBC 可赎回声明

调用进出存储过程的CallableStatement示例:

 // IN with ordinal binding
	callableStatement.setInt(1, 999);

	// OUT with name binding
	String name = callableStatement.getString("NAME");
    BigDecimal salary = callableStatement.getBigDecimal("SALARY");
    Timestamp createdDate = callableStatement.getTimestamp("CREATED_DATE"); 

输出

 java.sql.SQLException: operation not allowed: 
		Ordinal binding and Named binding cannot be combined! 

要修复此问题,请将 all 更新为序号绑定或名称绑定:

 callableStatement.setInt(1, 999);

	String name = callableStatement.getString(2);
	BigDecimal salary = callableStatement.getBigDecimal(3);
	Timestamp createdDate = callableStatement.getTimestamp(4); 

参考

java.sql.SQLException:无法识别服务器时区值“xx time”

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/jdbc/java-sql-sqlexception-the-server-time-zone-value-xx-time-is-unrecognized/

使用最新的mysql-connector-java:8.0.16与 MySQL 服务器建立 JDBC 连接,并遇到以下 SQLException:

测试

  • MySQL 5.7
  • Java 8
  • JDBC 驱动程序,MySQL-连接器-java 8.0.16
 try (Connection conn = DriverManager.getConnection(
			"jdbc:mysql://127.0.0.1:3306/test", "root", "password")) {

		//...

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

输出

 java.sql.SQLException: The server time zone value 'Malay Peninsula Standard Time' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89)
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63)
	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:73)
	at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:76)
	at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:835)
	at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:455)
	at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:240)
	at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:199)
	at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:677)
	at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
	at com.mkyong.jdbc.JDBCExample.main(JDBCExample.java:23)
Caused by: com.mysql.cj.exceptions.InvalidConnectionAttributeException: The server time zone value 'Malay Peninsula Standard Time' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
	at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
	at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
	at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
	at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61)
	at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:85)
	at com.mysql.cj.util.TimeUtil.getCanonicalTimezone(TimeUtil.java:132)
	at com.mysql.cj.protocol.a.NativeProtocol.configureTimezone(NativeProtocol.java:2243)
	at com.mysql.cj.protocol.a.NativeProtocol.initServerSession(NativeProtocol.java:2267)
	at com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:1319)
	at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:966)
	at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:825)
	... 6 more 

1.解决办法

1.1 找到 MySQL 配置文件,例如my.inimy.cnf。在文件末尾添加默认时区:

my.ini

 # Indicates the InnoDB Cluster Port.
# innodbclusterport=3306

# Load mysql plugins at start."plugin_x ; plugin_y".
# plugin_load

# MySQL server's plugin configuration.
# loose_mysqlx_port=33060

# Set default time zone
default-time-zone = '+08:00' 

1.2 重启 MySQL 服务。

附注:阅读这个 MySQL 选项文件,找出文件(my.inimy.cnf)的位置。

2.解决办法

或者,直接在 JDBC 连接字符串中传递一个serverTimezone属性。

 try (Connection conn = DriverManager.getConnection(
			"jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC", "root", "password")) {

		//...

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

参考

Tags : java jdbc mysql

Java–流已经被操作或关闭

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/java8/java-stream-has-already-been-operated-upon-or-closed/

在 Java 8 中,不能被重用,一旦被消耗或使用,该流将被关闭。

1.示例–流已关闭!

回顾下面的例子,它会抛出一个IllegalStateException,说“stream closed”。

TestJava8.java

 package com.mkyong.java8;

import java.util.Arrays;
import java.util.stream.Stream;

public class TestJava8 {

    public static void main(String[] args) {

        String[] array = {"a", "b", "c", "d", "e"};
        Stream<String> stream = Arrays.stream(array);

        // loop a stream
        stream.forEach(x -> System.out.println(x));

        // reuse it to filter again! throws IllegalStateException
        long count = stream.filter(x -> "b".equals(x)).count();
        System.out.println(count);

    }

} 

输出

java.lang.IllegalStateException: stream has already been operated upon or closed
	at java.util.stream.AbstractPipeline.(AbstractPipeline.java:203)
	at java.util.stream.ReferencePipeline.<init>(ReferencePipeline.java:94)
	at java.util.stream.ReferencePipeline$StatelessOp.<init>(ReferencePipeline.java:618)
	at java.util.stream.ReferencePipeline$2.<init>(ReferencePipeline.java:163)
	at java.util.stream.ReferencePipeline.filter(ReferencePipeline.java:162)
	at com.hostingcompass.whois.range.run.TestJava8.main(TestJava8.java:25)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144) 

2.示例–重用流

不管出于什么原因,你真的想重用一个流,尝试下面的Supplier解决方案:

TestJava8.java

 package com.mkyong.java8;

import java.util.function.Supplier;
import java.util.stream.Stream;

public class TestJava8 {

    public static void main(String[] args) {

        String[] array = {"a", "b", "c", "d", "e"};

        Supplier<Stream<String>> streamSupplier = () -> Stream.of(array);

        //get new stream
        streamSupplier.get().forEach(x -> System.out.println(x));

        //get another new stream
        long count = streamSupplier.get().filter(x -> "b".equals(x)).count();
        System.out.println(count);

    }

} 

输出

a
b
c
d
e
1

每个get()将返回一个新的流。

Why?
May I know why you need to reuse a stream, for testing?

参考

  1. 供应商 JavaDoc
  2. 流摘要 JavaDoc

Java XML 教程

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/tutorials/java-xml-tutorials/

java xml logo

在这一系列 Java XML 教程中,我们将展示如何使用 DOM、SAX、StAX 和 JDOM 等 XML 解析器来读写 XML 文档;另外,JAXB 将 XML 转换成对象或从对象转换成 XML。

一般来说,有两种处理 XML 文档的编程模型:DOM 和 SAX(流)。

目录

DOM、SAX 和 StAX 都是 Java APIs 的一部分。

1。文档对象模型

文档对象模型(DOM) 使用节点将整个 XML 文档表示为一个树形结构,并将它们存储在内存中。

DOM 有利于操纵小的 XML 文件,比如读、写和修改 XML 结构;DOM 不用于解析或操作大型 XML 文件,因为在内存中构建整个 XML 结构会消耗大量内存。

DOM 解析器示例

  1. DOM–读取 XML
  2. DOM–编写 XML
  3. DOM–修改 XML
  4. DOM–漂亮的打印 XML
  5. DOM–XML 和 XSLT

2。XML 的简单应用编程接口(SAX)

Simple API for XML (SAX)是一个流模型、事件驱动、推送解析 API,用于读取 XML 文档(需要另一个 API 来编写)。SAX 从头到尾读取 XML 文件,当遇到一个元素时调用一个方法,或者当找到特定的文本或属性时调用另一个方法。

SAX 快速高效,比 DOM 需要更少的内存,因为 SAX 不像 DOM 那样创建 XML 数据的内部表示(树结构)。

SAX 解析器示例

  1. SAX–读取 XML
  2. SAX–读取 XML UTF-8

3。XML 流应用编程接口(StAX)

XML 流 API(StAX)是一个流模型、事件驱动、用于读写 XML 文档的拉解析 API。StAX 提供了比 SAX 更简单的编程模型和比 DOM 更高效的内存管理。

StAX 解析器示例

  1. StAX–读取 XML
  2. StAX–编写 XML

4。第三方 XML 解析器(JDOM)

DOM、SAX 和 StAX 是 Java APIs 的一部分。然而,原料药可能不适合每个人的口味。或者,我们可以使用第三方 XML 解析器:

JDOM 解析器示例

  1. JDOM–读取 XML
  2. JDOM–编写 XML
  3. JDOM–修改 XML

5。用于 XML 绑定的 Java 架构(JAXB)

Jakarta XML 绑定(JAXB;以前的 Java Architecture for XML Binding)是一个 XML 绑定框架,用于在 Java 类和 XML 之间进行转换。

JAXB 示例

  1. JAXB 历史和 hello world 示例

6。Java XML 常见问题解答

一些常见问题。

  1. XML 外部实体(XXE)
  2. 将 XML 转换为属性
  3. 将属性转换为 XML
  4. 计算 XML 元素数量
  5. 计算 XML 的深度
  6. 将字符串转换成 XML

7。下载源代码

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

$ cd java-xml

$ CD src/main/Java/com/mkyong/XML/

8。参考文献

javax . naming . namenotfoundexception:名称 jdbc 未在此上下文中绑定

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jsf2/javax-naming-namenotfoundexception-name-jdbc-is-not-bound-in-this-context/

问题

JSF 2.0 web 应用程序,一个托管 bean 使用@Resource将数据源jdbc/mkyongdb注入到一个 ds 属性中。

 @ManagedBean(name="customer")
@SessionScoped
public class CustomerBean implements Serializable{

	//resource injection
	@Resource(name="jdbc/mkyongdb")
	private DataSource ds; 

当部署到 Tomcat 6 时,它会遇到以下 MySQL 数据源配置的错误消息。

 com.sun.faces.mgbean.ManagedBeanCreationException: 
        An error occurred performing resource injection on managed bean customer
	at com.sun.faces.mgbean.BeanBuilder.injectResources(BeanBuilder.java:207)
Caused by: com.sun.faces.spi.InjectionProviderException: 
        javax.naming.NameNotFoundException: Name jdbc is not bound in this Context
	at com.sun.faces.vendor.Tomcat6InjectionProvider.inject(Tomcat6InjectionProvider.java:84)
	at com.sun.faces.mgbean.BeanBuilder.injectResources(BeanBuilder.java:201)
	... 53 more
Caused by: javax.naming.NameNotFoundException: Name jdbc is not bound in this Context
	at org.apache.naming.NamingContext.lookup(NamingContext.java:770)
	at org.apache.naming.NamingContext.lookup(NamingContext.java:153)
	... 54 more 

解决办法

“JDBC/mkyondb”数据源在 Tomcat 中配置不正确,请参阅本指南了解详细信息–如何在 Tomcat 6 中配置 MySQL 数据源

jdbc jsf2 (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190224205626/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

javax.swing.tree.TreeNode 是一个受限类

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/google-app-engine/javax-swing-tree-treenode-is-a-restricted-class/

问题

在以下环境中,在 Google App Engine 上开发 Struts2。

  1. struts 2.3.1.2
  2. freemaker 2.3.18
  3. JDK 1.6
  4. Eclipse 3.7+Eclipse 的 Google 插件
  5. 谷歌应用引擎 Java SDK 1.6.3.1

GAE 抱怨说javax.swing.tree.TreeNode是本地开发中的受限类,如果部署在真实的 GAE 生产环境中,错误消息就消失了。

 Caused by:
java.lang.NoClassDefFoundError: javax.swing.tree.TreeNode is a restricted class. 
	Please see the Google  App Engine developer's guide for more details.
	at com.google.appengine.tools.development.agent.runtime.Runtime.reject(Runtime.java:51)
	at freemarker.core.TextBlock.isIgnorable(TextBlock.java:375)
	at freemarker.core.TextBlock.heedsTrailingWhitespace(TextBlock.java:337) 

解决办法

不知道为什么它能在 GAE 生产环境中工作,对于 GAE 本地环境,你可以重载TextBlock 类,编译下面的代码并将其移动到 WEB-INF/classes ,这样它将重载原来的TextBlock类。

treenote is restricted class

文件:TextBlock.java

 /* 
 * Copyright (c) 2003 The Visigoth Software Society. All rights 
 * reserved. 
 * 
 * Redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions 
 * are met: 
 * 
 * 1\. Redistributions of source code must retain the above copyright 
 *    notice, this list of conditions and the following disclaimer. 
 * 
 * 2\. Redistributions in binary form must reproduce the above 
copyright 
 *    notice, this list of conditions and the following disclaimer in 
 *    the documentation and/or other materials provided with the 
 *    distribution. 
 * 
 * 3\. The end-user documentation included with the redistribution, if 
 *    any, must include the following acknowledgement: 
 *       "This product includes software developed by the 
 *        Visigoth Software Society (http://www.visigoths.org/)." 
 *    Alternately, this acknowledgement may appear in the software 
itself, 
 *    if and wherever such third-party acknowledgements normally 
appear. 
 * 
 * 4\. Neither the name "FreeMarker", "Visigoth", nor any of the names 
of the 
 *    project contributors may be used to endorse or promote products 
derived 
 *    from this software without prior written permission. For written 
 *    permission, please contact visigo...@visigoths.org. 
 * 
 * 5\. Products derived from this software may not be called 
"FreeMarker" or "Visigoth" 
 *    nor may "FreeMarker" or "Visigoth" appear in their names 
 *    without prior written permission of the Visigoth Software 
Society. 
 * 
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED 
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
 * DISCLAIMED.  IN NO EVENT SHALL THE VISIGOTH SOFTWARE SOCIETY OR 
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF 
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 
 * SUCH DAMAGE. 
 * 
==================================================================== 
 * 
 * This software consists of voluntary contributions made by many 
 * individuals on behalf of the Visigoth Software Society. For more 
 * information on the Visigoth Software Society, please see 
 * http://www.visigoths.org/ 
 */
package freemarker.core;

import java.io.IOException;

/**
 * A TemplateElement representing a block of plain text.
 * 
 * @version $Id: TextBlock.java,v 1.17 2004/01/06 17:06:42 szegedia Exp $
 */
public final class TextBlock extends TemplateElement {
	private static final char[] EMPTY_CHAR_ARRAY = new char[0];
	static final TextBlock EMPTY_BLOCK = new TextBlock(EMPTY_CHAR_ARRAY, false);
	// We're using char[] instead of String for storing the text block because
	// Writer.write(String) involves copying the String contents to a char[]
	// using String.getChars(), and then calling Writer.write(char[]). By
	// using Writer.write(char[]) directly, we avoid array copying on each
	// write.
	private char[] text;
	private final boolean unparsed;

	public TextBlock(String text) {
		this(text, false);
	}

	public TextBlock(String text, boolean unparsed) {
		this(text.toCharArray(), unparsed);
	}

	private TextBlock(char[] text, boolean unparsed) {
		this.text = text;
		this.unparsed = unparsed;
	}

	/**
	 * Simply outputs the text.
	 */
	public void accept(Environment env) throws IOException {
		env.getOut().write(text);
	}

	public String getCanonicalForm() {
		String text = new String(this.text);
		if (unparsed) {
			return "<#noparse>" + text + "</#noparse>";
		}
		return text;
	}

	public String getDescription() {
		String s = new String(text).trim();
		if (s.length() == 0) {
			return "whitespace";
		}
		if (s.length() > 20) {
			s = s.substring(0, 20) + "...";
			s = s.replace('\n', ' ');
			s = s.replace('\r', ' ');
		}
		return "text block (" + s + ")";
	}

	TemplateElement postParseCleanup(boolean stripWhitespace) {
		if (text.length == 0)
			return this;
		int openingCharsToStrip = 0, trailingCharsToStrip = 0;
		boolean deliberateLeftTrim = deliberateLeftTrim();
		boolean deliberateRightTrim = deliberateRightTrim();
		if (!stripWhitespace || text.length == 0) {
			return this;
		}
		if (parent.parent == null && previousSibling() == null)
			return this;
		if (!deliberateLeftTrim) {
			trailingCharsToStrip = trailingCharsToStrip();
		}
		if (!deliberateRightTrim) {
			openingCharsToStrip = openingCharsToStrip();
		}
		if (openingCharsToStrip == 0 && trailingCharsToStrip == 0) {
			return this;
		}
		this.text = substring(text, openingCharsToStrip, text.length
				- trailingCharsToStrip);
		if (openingCharsToStrip > 0) {
			this.beginLine++;
			this.beginColumn = 1;
		}
		if (trailingCharsToStrip > 0) {
			this.endColumn = 0;
		}
		return this;
	}

	/**
	 * Scans forward the nodes on the same line to see whether there is a
	 * deliberate left trim in effect. Returns true if the left trim was
	 * present.
	 */
	private boolean deliberateLeftTrim() {
		boolean result = false;
		for (TemplateElement elem = this.nextTerminalNode(); elem != null
				&& elem.beginLine == this.endLine; elem = elem
				.nextTerminalNode()) {
			if (elem instanceof TrimInstruction) {
				TrimInstruction ti = (TrimInstruction) elem;
				if (!ti.left && !ti.right) {
					result = true;
				}
				if (ti.left) {
					result = true;
					int lastNewLineIndex = lastNewLineIndex();
					if (lastNewLineIndex >= 0 || beginColumn == 1) {
						char[] firstPart = substring(text, 0,
								lastNewLineIndex + 1);
						char[] lastLine = substring(text, 1 + lastNewLineIndex);
						if (trim(lastLine).length == 0) {
							this.text = firstPart;
							this.endColumn = 0;
						} else {
							int i = 0;
							while (Character.isWhitespace(lastLine[i])) {
								i++;
							}
							char[] printablePart = substring(lastLine, i);
							this.text = concat(firstPart, printablePart);
						}
					}
				}
			}
		}
		if (result) {
		}
		return result;
	}

	/**
	 * Checks for the presence of a t or rt directive on the same line. Returns
	 * true if the right trim directive was present.
	 */
	private boolean deliberateRightTrim() {
		boolean result = false;
		for (TemplateElement elem = this.prevTerminalNode(); elem != null
				&& elem.endLine == this.beginLine; elem = elem
				.prevTerminalNode()) {
			if (elem instanceof TrimInstruction) {
				TrimInstruction ti = (TrimInstruction) elem;
				if (!ti.left && !ti.right) {
					result = true;
				}
				if (ti.right) {
					result = true;
					int firstLineIndex = firstNewLineIndex() + 1;
					if (firstLineIndex == 0) {
						return false;
					}
					if (text.length > firstLineIndex
							&& text[firstLineIndex - 1] == '\r'
							&& text[firstLineIndex] == '\n') {
						firstLineIndex++;
					}
					char[] trailingPart = substring(text, firstLineIndex);
					char[] openingPart = substring(text, 0, firstLineIndex);
					if (trim(openingPart).length == 0) {
						this.text = trailingPart;
						this.beginLine++;
						this.beginColumn = 1;
					} else {
						int lastNonWS = openingPart.length - 1;
						while (Character.isWhitespace(text[lastNonWS])) {
							lastNonWS--;
						}
						char[] printablePart = substring(text, 0, lastNonWS + 1);
						if (trim(trailingPart).length == 0) {
							// THIS BLOCK IS HEINOUS! THERE MUST BE A BETTER
							// WAY! REVISIT (JR)
							boolean trimTrailingPart = true;
							for (TemplateElement te = this.nextTerminalNode(); te != null
									&& te.beginLine == this.endLine; te = te
									.nextTerminalNode()) {
								if (te.heedsOpeningWhitespace()) {
									trimTrailingPart = false;
								}
								if (te instanceof TrimInstruction
										&& ((TrimInstruction) te).left) {
									trimTrailingPart = true;
									break;
								}
							}
							if (trimTrailingPart)
								trailingPart = EMPTY_CHAR_ARRAY;
						}
						this.text = concat(printablePart, trailingPart);
					}
				}
			}
		}
		return result;
	}

	/*
	 * private String leftTrim(String s) { int i =0; while (i<s.length()) { if
	 * (!Character.isWhitespace(s.charAt(i))) break; ++i; } return
	 * s.substring(i); }
	 */
	private int firstNewLineIndex() {
		String content = new String(text);
		int newlineIndex1 = content.indexOf('\n');
		int newlineIndex2 = content.indexOf('\r');
		int result = newlineIndex1 >= 0 ? newlineIndex1 : newlineIndex2;
		if (newlineIndex1 >= 0 && newlineIndex2 >= 0) {
			result = Math.min(newlineIndex1, newlineIndex2);
		}
		return result;
	}

	private int lastNewLineIndex() {
		String content = new String(text);
		return Math.max(content.lastIndexOf('\r'), content.lastIndexOf('\n'));
	}

	/**
	 * figures out how many opening whitespace characters to strip in the
	 * post-parse cleanup phase.
	 */
	private int openingCharsToStrip() {
		int newlineIndex = firstNewLineIndex();
		if (newlineIndex == -1 && beginColumn != 1) {
			return 0;
		}
		++newlineIndex;
		if (text.length > newlineIndex) {
			if (newlineIndex > 0 && text[newlineIndex - 1] == '\r'
					&& text[newlineIndex] == '\n') {
				++newlineIndex;
			}
		}
		if (new String(text).substring(0, newlineIndex).trim().length() > 0) {
			return 0;
		}
		// We look at the preceding elements on the line to see if we should
		// strip the opening newline and any whitespace preceding it.
		for (TemplateElement elem = this.prevTerminalNode(); elem != null
				&& elem.endLine == this.beginLine; elem = elem
				.prevTerminalNode()) {
			if (elem.heedsOpeningWhitespace()) {
				return 0;
			}
		}
		return newlineIndex;
	}

	/**
	 * figures out how many trailing whitespace characters to strip in the
	 * post-parse cleanup phase.
	 */
	private int trailingCharsToStrip() { 
        String content = new String(text); 
        int lastNewlineIndex = lastNewLineIndex(); 
        if (lastNewlineIndex == -1 && beginColumn != 1) { 
            return 0; 
        } 
        String substring = content.substring(lastNewlineIndex +1); 
        if (substring.trim().length() >0) { 
            return 0; 
        } 
// We look at the elements afterward on the same line to see if we should 
// strip any whitespace after the last newline 
        for (TemplateElement elem = this.nextTerminalNode(); 
             elem != null && elem.beginLine == this.endLine; 
             elem = elem.nextTerminalNode()) 
        { 
            if (elem.heedsTrailingWhitespace()) 
            { 
                return 0; 
            } 
        } 
        return substring.length(); 
    }
	boolean heedsTrailingWhitespace() {
		if (isIgnorable()) {
			return false;
		}
		for (int i = 0; i < text.length; i++) {
			char c = text[i];
			if (c == '\n' || c == '\r') {
				return false;
			}
			if (!Character.isWhitespace(c)) {
				return true;
			}
		}
		return true;
	}

	boolean heedsOpeningWhitespace() {
		if (isIgnorable()) {
			return false;
		}
		for (int i = text.length - 1; i >= 0; i--) {
			char c = text[i];
			if (c == '\n' || c == '\r') {
				return false;
			}
			if (!Character.isWhitespace(c)) {
				return true;
			}
		}
		return true;
	}

	boolean isIgnorable() {
		if (text == null || text.length == 0) {
			return true;
		}
		if (!isWhitespace()) {
			return false;
		}
		// do the trick
		boolean atTopLevel = true;
		TemplateElement prevSibling = previousSibling();
		TemplateElement nextSibling = nextSibling();
		return ((prevSibling == null && atTopLevel) || nonOutputtingType(prevSibling))
				&& ((nextSibling == null && atTopLevel) || nonOutputtingType(nextSibling));
	}

	private boolean nonOutputtingType(TemplateElement element) {
		return (element instanceof Macro || element instanceof Assignment
				|| element instanceof AssignmentInstruction
				|| element instanceof PropertySetting
				|| element instanceof LibraryLoad || element instanceof Comment);
	}

	private static char[] substring(char[] c, int from, int to) {
		char[] c2 = new char[to - from];
		System.arraycopy(c, from, c2, 0, c2.length);
		return c2;
	}

	private static char[] substring(char[] c, int from) {
		return substring(c, from, c.length);
	}

	private static char[] trim(char[] c) {
		if (c.length == 0) {
			return c;
		}
		return new String(c).trim().toCharArray();
	}

	private static char[] concat(char[] c1, char[] c2) {
		char[] c = new char[c1.length + c2.length];
		System.arraycopy(c1, 0, c, 0, c1.length);
		System.arraycopy(c2, 0, c, c1.length, c2.length);
		return c;
	}

	boolean isWhitespace() {
		return text == null || trim(text).length == 0;
	}
} 

参考

  1. Freemarker 2.4,GAE/J 1.2.6 和 javax.swing.tree.TreeNode

gae struts2

JAX-遥感教程

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/tutorials/jax-rs-tutorials/

jax-rs tutorials

Java API for RESTful Web Services(JAX-RS),是一套为开发者提供 REST 服务的 API。JAX-RS 是 Java EE6 的一部分,使开发者开发 REST web 应用变得容易。

在这一系列的 JAX-RS 教程中,我们同时使用了 JerseyRESTEasy ,流行的 JAX-RS 实现。

快乐学习 JAX🙂

快速启动

一些快速使用 JAX 遥感器的例子。

基本示例

开发 REST 服务的基本注释和函数。

文件上传示例

如何处理 JAX 遥感中的多部分数据?

使用 XML

JAX 遥感系统中的 XML 支持。

使用 JSON

JAX 的 JSON 支持。

RESTful Java 客户端

创建一个 RESTful Java 客户端来执行“GET”和“POST”请求,以操作 json 数据。

JAX-遥感+春天

将 JAX 遥感系统与 Spring 框架集成。

常见错误消息

JAX 遥感器开发中的一些常见错误信息。

参考

  1. 球衣官网
  2. 球衣用户指南
  3. RESTEasy 官网
  4. RESTEasy 用户指南
  5. 维客休息解释

JAX-WS 与 MTOM 的关系

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/webservices/jax-ws/jax-ws-attachment-with-mtom/

一个完整的基于 JAX-WS SOAP 的示例,展示了如何使用消息传输优化机制(MTOM)XML-二进制优化打包(XOP) 技术在服务器和客户端之间发送二进制附件(图像)。

Note
There are ton of articles about what’s MTOM and the benefits of using it (see reference sites below), but it’s lack of complete example to use MTOM in JAX-WS, hope this example can fill in some missing pieces in the whole picture.

在服务器上启用 MTOM

让服务器通过 MTOM 发送附件非常容易,只需用javax.xml.ws.soap.MTOM注释 web 服务实现类。

1.web 服务端点

这里有一个 RPC 风格的 web 服务,发布了两个方法,downloadImage(String name)uploadImage(Image data),让用户上传或下载图像文件。

文件:ImageServer.java

 package com.mkyong.ws;

import java.awt.Image;

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;

//Service Endpoint Interface
@WebService
@SOAPBinding(style = Style.RPC)
public interface ImageServer{

	//download a image from server
	@WebMethod Image downloadImage(String name);

	//update image to server
	@WebMethod String uploadImage(Image data);

} 

文件:ImageServerImpl.java

 package com.mkyong.ws;

import java.awt.Image;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.jws.WebService;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.soap.MTOM;

//Service Implementation Bean
@MTOM
@WebService(endpointInterface = "com.mkyong.ws.ImageServer")
public class ImageServerImpl implements ImageServer{

	@Override
	public Image downloadImage(String name) {

		try {

			File image = new File("c:\\images\\" + name);
			return ImageIO.read(image);

		} catch (IOException e) {

			e.printStackTrace();
			return null; 

		}
	}

	@Override
	public String uploadImage(Image data) {

		if(data!=null){
			//store somewhere
			return "Upload Successful";
		}

		throw new WebServiceException("Upload Failed!");

	}

} 

文件:ImagePublisher.java

 package com.mkyong.endpoint;

import javax.xml.ws.Endpoint;
import com.mkyong.ws.ImageServerImpl;

//Endpoint publisher
public class ImagePublisher{

    public static void main(String[] args) {

	Endpoint.publish("http://localhost:9999/ws/image", new ImageServerImpl());

	System.out.println("Server is published!");

    }

} 

2.web 服务客户端

这里有一个 web 服务客户端,用于访问位于 URL "http://localhost:9999/ws/image的已发布的 web 服务。

文件:ImageClient.java

 package com.mkyong.client;

import java.awt.Image;
import java.io.File;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Service;
import javax.xml.ws.soap.MTOMFeature;
import javax.xml.ws.soap.SOAPBinding;

import com.mkyong.ws.ImageServer;

public class ImageClient{

	public static void main(String[] args) throws Exception {

	URL url = new URL("http://localhost:9999/ws/image?wsdl");
        QName qname = new QName("http://ws.mkyong.com/", "ImageServerImplService");

        Service service = Service.create(url, qname);
        ImageServer imageServer = service.getPort(ImageServer.class);

        /************  test download  ***************/
        Image image = imageServer.downloadImage("rss.png");

        //display it in frame
        JFrame frame = new JFrame();
        frame.setSize(300, 300);
        JLabel label = new JLabel(new ImageIcon(image));
        frame.add(label);
        frame.setVisible(true);

        System.out.println("imageServer.downloadImage() : Download Successful!");

    }

} 

3.HTTP 和 SOAP 流量

这是客户端生成的 HTTP 和 SOAP 流量,由流量监控工具捕获。

为了节省空间,省略了第一个 wsdl 请求。
客户端发送请求:

 POST /ws/image HTTP/1.1
SOAPAction: ""
Accept: text/xml, multipart/related, text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Content-Type: text/xml; charset=utf-8
User-Agent: Java/1.6.0_13
Host: localhost:9999
Connection: keep-alive
Content-Length: 209

<?xml version="1.0" ?>
	<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
		<S:Body>
			<ns2:downloadImage xmlns:ns2="http://ws.mkyong.com/">
				<arg0>rss.png</arg0>
			</ns2:downloadImage>
		</S:Body>
	</S:Envelope> 

服务器发送响应:

 HTTP/1.1 200 OK
Transfer-encoding: chunked
Content-type: multipart/related;
start="<rootpart*c73c9ce8-6e02-40ce-9f68-064e18843428@example.jaxws.sun.com>";
type="application/xop+xml";
boundary="uuid:c73c9ce8-6e02-40ce-9f68-064e18843428";
start-info="text/xml"

--uuid:c73c9ce8-6e02-40ce-9f68-064e18843428
Content-Id: <rootpart*c73c9ce8-6e02-40ce-9f68-064e18843428@example.jaxws.sun.com>
Content-Type: application/xop+xml;charset=utf-8;type="text/xml"
Content-Transfer-Encoding: binary

<?xml version="1.0" ?>
  <S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
     <S:Body>
	<ns2:downloadImageResponse xmlns:ns2="http://ws.mkyong.com/">
	  <return>
	    <xop:Include xmlns:xop="http://www.w3.org/2004/08/xop/include" 
		href="cid:012eb00e-9460-407c-b622-1be987fdb2cf@example.jaxws.sun.com">
	    </xop:Include>
	  </return>
	</ns2:downloadImageResponse>
     </S:Body>
   </S:Envelope>
--uuid:c73c9ce8-6e02-40ce-9f68-064e18843428
Content-Id: <012eb00e-9460-407c-b622-1be987fdb2cf@example.jaxws.sun.com>
Content-Type: image/png
Content-Transfer-Encoding: binary

Binary data here............. 

在客户端启用 MTOM

允许客户端通过 MTOM 向服务器发送附件需要一些额外的工作,请参见以下示例:

 //codes enable MTOM in client
BindingProvider bp = (BindingProvider) imageServer;
SOAPBinding binding = (SOAPBinding) bp.getBinding();
binding.setMTOMEnabled(true); 

1.web 服务客户端

下面是一个 webservice 客户端,它通过 MTOM 将一个图像文件发送到上面发布的端点(http://localhost:8888/ws/image)。

文件:ImageClient.java

 package com.mkyong.client;

import java.awt.Image;
import java.io.File;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Service;
import javax.xml.ws.soap.MTOMFeature;
import javax.xml.ws.soap.SOAPBinding;

import com.mkyong.ws.ImageServer;

public class ImageClient{

	public static void main(String[] args) throws Exception {

	URL url = new URL("http://localhost:8888/ws/image?wsdl");
        QName qname = new QName("http://ws.mkyong.com/", "ImageServerImplService");

        Service service = Service.create(url, qname);
        ImageServer imageServer = service.getPort(ImageServer.class);

        /************  test upload ****************/
        Image imgUpload = ImageIO.read(new File("c:\\images\\rss.png"));

        //enable MTOM in client
        BindingProvider bp = (BindingProvider) imageServer;
        SOAPBinding binding = (SOAPBinding) bp.getBinding();
        binding.setMTOMEnabled(true);

        String status = imageServer.uploadImage(imgUpload);
        System.out.println("imageServer.uploadImage() : " + status);

    }

} 

2.HTTP 和 SOAP 流量

这是客户端生成的 HTTP 和 SOAP 流量,由流量监控工具捕获。

为了节省空间,省略了第一个 wsdl 请求。
客户端发送请求:

 POST /ws/image HTTP/1.1
Content-type: multipart/related;
start="<rootpart*751f2e5d-47f8-47d8-baf0-f793c29bd931@example.jaxws.sun.com>";
type="application/xop+xml";
boundary="uuid:751f2e5d-47f8-47d8-baf0-f793c29bd931";

start-info="text/xml"
Soapaction: ""
Accept: text/xml, multipart/related, text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
User-Agent: JAX-WS RI 2.1.6 in JDK 6
Host: localhost:9999
Connection: keep-alive
Content-Length: 6016

--uuid:751f2e5d-47f8-47d8-baf0-f793c29bd931
Content-Id: <rootpart*751f2e5d-47f8-47d8-baf0-f793c29bd931@example.jaxws.sun.com>
Content-Type: application/xop+xml;charset=utf-8;type="text/xml"
Content-Transfer-Encoding: binary

<?xml version="1.0" ?>
  <S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
     <S:Body>
	<ns2:uploadImage xmlns:ns2="http://ws.mkyong.com/">
	  <arg0>
	    <xop:Include xmlns:xop="http://www.w3.org/2004/08/xop/include" 
		href="cid:2806f201-e15e-4ee0-8347-b7b4dffad5cb@example.jaxws.sun.com">
	    </xop:Include>
	  </arg0>
	 </ns2:uploadImage>
     </S:Body>
   </S:Envelope>

--uuid:751f2e5d-47f8-47d8-baf0-f793c29bd931
Content-Id: <2806f201-e15e-4ee0-8347-b7b4dffad5cb@example.jaxws.sun.com>
Content-Type: image/png
Content-Transfer-Encoding: binary

Binary data here............. 

服务器发送响应:

 HTTP/1.1 200 OK
Transfer-encoding: chunked
Content-type: multipart/related;
start="<rootpart*188a5835-198b-4c28-9b36-bf030578f2bd@example.jaxws.sun.com>";
type="application/xop+xml";
boundary="uuid:188a5835-198b-4c28-9b36-bf030578f2bd";
start-info="text/xml"

--uuid:188a5835-198b-4c28-9b36-bf030578f2bd
Content-Id: <rootpart*188a5835-198b-4c28-9b36-bf030578f2bd@example.jaxws.sun.com>
Content-Type: application/xop+xml;charset=utf-8;type="text/xml"
Content-Transfer-Encoding: binary

<?xml version="1.0" ?>
  <S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
      <S:Body>
	<ns2:uploadImageResponse xmlns:ns2="http://ws.mkyong.com/">
		<return>Upload Successful</return>
	</ns2:uploadImageResponse>
      </S:Body>
  </S:Envelope>

--uuid:188a5835-198b-4c28-9b36-bf030578f2bd-- 

完整的 WSDL 文档

有兴趣研究 WSDL 文件的,可以通过 URL:http://localhost:9999/ws/image 获取 wsdl 文件?wsdl

ImageServer WSDL 文件示例

 <?xml version="1.0" encoding="UTF-8"?>

<definitions 
	xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" 
	xmlns:tns="http://ws.mkyong.com/" 
	xmlns:xsd="http://www.w3.org/2001/XMLSchema" 

	targetNamespace="http://ws.mkyong.com/" 
	name="ImageServerImplService">

<types></types>

<message name="downloadImage">
	<part name="arg0" type="xsd:string"></part>
</message>
<message name="downloadImageResponse">
	<part name="return" type="xsd:base64Binary"></part>
</message>

<message name="uploadImage">
	<part name="arg0" type="xsd:base64Binary"></part>
</message>
<message name="uploadImageResponse">
	<part name="return" type="xsd:string"></part>
</message>

<portType name="ImageServer">

	<operation name="downloadImage">
		<input message="tns:downloadImage"></input>
		<output message="tns:downloadImageResponse"></output>
	</operation>
	<operation name="uploadImage">
		<input message="tns:uploadImage"></input>
		<output message="tns:uploadImageResponse"></output>
	</operation>

</portType>

<binding name="ImageServerImplPortBinding" type="tns:ImageServer">
	<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc">
        </soap:binding>

	<operation name="downloadImage">
		<soap:operation soapAction=""></soap:operation>
		<input>
			<soap:body use="literal" namespace="http://ws.mkyong.com/"></soap:body>
		</input>
		<output>
			<soap:body use="literal" namespace="http://ws.mkyong.com/"></soap:body>
		</output>
	</operation>

	<operation name="uploadImage">
		<soap:operation soapAction=""></soap:operation>
		<input>
			<soap:body use="literal" namespace="http://ws.mkyong.com/">
                        </soap:body>
		</input>
		<output>
			<soap:body use="literal" namespace="http://ws.mkyong.com/">
                        </soap:body>
		</output>
	</operation>

</binding>

<service name="ImageServerImplService">
<port name="ImageServerImplPort" binding="tns:ImageServerImplPortBinding">
<soap:address location="http://localhost:9999/ws/image"></soap:address>
</port>
</service>
</definitions> 

下载源代码

Download It – JAX-WS-Attachment-MTOM-Example.zip (20KB)

参考

  1. http://www.devx.com/xml/Article/34797/1763/page/1
  2. http://download . Oracle . com/docs/CD/e 17802 _ 01/web services/web services/docs/2.0/jaxws/mtom-swaref . html
  3. http://www.crosschecknet.com/intro_to_mtom.php
  4. http://download . Oracle . com/docs/CD/e 12840 _ 01/WLS/docs 103/webserv _ adv/mtom . html
  5. http://www . the server side . com/news/1363957/Sending-Attachments-with-SOAP
  6. http://metro.java.net/guide/Binary_Attachments__MTOM_.html

Tags : attachment jax-ws mtom web services

JAX-WS Hello World 示例-文档样式

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/webservices/jax-ws/jax-ws-hello-world-example-document-style/

在本教程中,我们将向您展示如何使用 JAX-WS 来创建一个基于 SOAP 的 web 服务(文档样式)端点。与 RPC 风格相比,它需要一些额外的努力来使它工作。

本例的目录结构

jaxws-document-hello-world--example

JAX-WS Web 服务端点

下面是在 JAX WS 中创建文档样式 web 服务的步骤。

1.创建 Web 服务端点接口

实际上,用@SOAPBinding标注是可选的,因为默认样式是 document。

文件:HelloWorld.java

 package com.mkyong.ws;

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;

//Service Endpoint Interface
@WebService
@SOAPBinding(style = Style.DOCUMENT, use=Use.LITERAL) //optional
public interface HelloWorld{

	@WebMethod String getHelloWorldAsString(String name);

} 

Note
In JAX-WS development, convert from “RPC style” to “Document style” is very easy, just change the @SOAPBinding style option. ## 2.创建 Web 服务端点实现

文件:HelloWorldImpl.java

 package com.mkyong.ws;

import javax.jws.WebService;

//Service Implementation
@WebService(endpointInterface = "com.mkyong.ws.HelloWorld")
public class HelloWorldImpl implements HelloWorld{

	@Override
	public String getHelloWorldAsString(String name) {
		return "Hello World JAX-WS " + name;
	}

} 

3.创建端点发布者。

文件:HelloWorldPublisher.java

 package com.mkyong.endpoint;

import javax.xml.ws.Endpoint;
import com.mkyong.ws.HelloWorldImpl;

//Endpoint publisher
public class HelloWorldPublisher{

	public static void main(String[] args) {
	   Endpoint.publish("http://localhost:9999/ws/hello", new HelloWorldImpl());
    }

} 

等等,当您运行端点发布器时,您会遇到以下错误消息:

 Wrapper class com.mkyong.ws.jaxws.GetHelloWorldAsString is not found. 
    Have you run APT to generate them? 

见此。您需要使用“ wsgen 工具来生成必要的 JAX-WS 可移植工件。让我们进入下一步。

4.wsgen 命令

文档样式需要额外的类来运行,您可以使用" wsgen "来生成所有必需的 Java 工件(映射类、wsdl 或 xsd 模式)。需要" wsgen "命令来读取服务端点实现类:

 wsgen -keep -cp . com.mkyong.ws.HelloWorldImpl 

它将生成两个类,将其复制到您的“ package.jaxws 文件夹中。

文件:GetHelloWorldAsString.java

 package com.mkyong.ws.jaxws;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement(name = "getHelloWorldAsString", namespace = "http://ws.mkyong.com/")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "getHelloWorldAsString", namespace = "http://ws.mkyong.com/")
public class GetHelloWorldAsString {

    @XmlElement(name = "arg0", namespace = "")
    private String arg0;

    /**
     * 
     * @return
     *     returns String
     */
    public String getArg0() {
        return this.arg0;
    }

    /**
     * 
     * @param arg0
     *     the value for the arg0 property
     */
    public void setArg0(String arg0) {
        this.arg0 = arg0;
    }

} 

文件:GetHelloWorldAsStringResponse.java

 package com.mkyong.ws.jaxws;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement(name = "getHelloWorldAsStringResponse", namespace = "http://ws.mkyong.com/")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "getHelloWorldAsStringResponse", namespace = "http://ws.mkyong.com/")
public class GetHelloWorldAsStringResponse {

    @XmlElement(name = "return", namespace = "")
    private String _return;

    /**
     * 
     * @return
     *     returns String
     */
    public String getReturn() {
        return this._return;
    }

    /**
     * 
     * @param _return
     *     the value for the _return property
     */
    public void setReturn(String _return) {
        this._return = _return;
    }

} 

Note
The “wsgen” tool is available in the “JDK_Path\bin\” folder. For detail, please read this JAX-WS : wsgen tool example article.

5.完成的

完成,发布并通过 URL 测试:http://localhost:9999/ws/hello?wsdl

Web 服务客户端

创建 web 服务客户端以访问您发布的服务。

文件:HelloWorldClient.java

 package com.mkyong.client;

import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import com.mkyong.ws.HelloWorld;

public class HelloWorldClient{

	public static void main(String[] args) throws Exception {

	URL url = new URL("http://localhost:9999/ws/hello?wsdl");
        QName qname = new QName("http://ws.mkyong.com/", "HelloWorldImplService");

        Service service = Service.create(url, qname);

        HelloWorld hello = service.getPort(HelloWorld.class);

         System.out.println(hello.getHelloWorldAsString("mkyong"));

    }

} 

输出

 Hello World JAX-WS mkyong 

跟踪 SOAP 流量

从上到下,展示了 SOAP 信封如何在这个文档风格的 web 服务中在客户机和服务器之间流动。

1.申请一份 WSDL 档案

首先,客户端向服务端点发送一个 wsdl 请求:

客户端发送请求:

 GET /ws/hello?wsdl HTTP/1.1
User-Agent: Java/1.6.0_13
Host: localhost:9999
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive 

服务器发送响应:

 HTTP/1.1 200 OK
Transfer-encoding: chunked
Content-type: text/xml;charset=utf-8

<?xml version="1.0" encoding="UTF-8"?>
	<!-- Published by JAX-WS RI at http://jax-ws.dev.java.net. 
		RI's version is JAX-WS RI 2.1.1 in JDK 6\. -->
	<!-- Generated by JAX-WS RI at http://jax-ws.dev.java.net. 
		RI's version is JAX-WS RI 2.1.1 in JDK 6\. -->
<definitions 
	xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" 
	xmlns:tns="http://ws.mkyong.com/" 
	xmlns:xsd="http://www.w3.org/2001/XMLSchema" 

	targetNamespace="http://ws.mkyong.com/" 
	name="HelloWorldImplService">
<types>
<xsd:schema>
	<xsd:import namespace="http://ws.mkyong.com/" 
		schemaLocation="http://localhost:9999/ws/hello?xsd=1"></xsd:import>
</xsd:schema>
</types>

<message name="getHelloWorldAsString">
	<part name="parameters" element="tns:getHelloWorldAsString"></part>
</message>
<message name="getHelloWorldAsStringResponse">
	<part name="parameters" element="tns:getHelloWorldAsStringResponse"></part>
</message>

<portType name="HelloWorld">
	<operation name="getHelloWorldAsString">
		<input message="tns:getHelloWorldAsString"></input>
		<output message="tns:getHelloWorldAsStringResponse"></output>
	</operation>
</portType>

<binding name="HelloWorldImplPortBinding" type="tns:HelloWorld">

	<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document">
	</soap:binding>
	<operation name="getHelloWorldAsString">
		<soap:operation soapAction=""></soap:operation>
		<input>
			<soap:body use="literal"></soap:body>
		</input>
		<output>
			<soap:body use="literal"></soap:body>
		</output>
	</operation>

</binding>

<service name="HelloWorldImplService">

<port name="HelloWorldImplPort" binding="tns:HelloWorldImplPortBinding">

<soap:address location="http://localhost:9999/ws/hello"></soap:address>

</port>
</service>
</definitions> 

2.getHelloWorldAsString(字符串名称)

第二次调用,客户端将方法调用请求放入 SOAP 信封,并将其发送到服务端点。在服务端点,调用请求的方法,将结果放入 SOAP 信封,并将其发送回客户端。

客户端发送请求:

 POST /ws/hello HTTP/1.1
SOAPAction: ""
Accept: text/xml, multipart/related, text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Content-Type: text/xml; charset=utf-8
User-Agent: Java/1.6.0_13
Host: localhost:9999
Connection: keep-alive
Content-Length: 224

<?xml version="1.0" ?>
	<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
		<S:Body>
			<ns2:getHelloWorldAsString xmlns:ns2="http://ws.mkyong.com/">
				<arg0>mkyong</arg0>
			</ns2:getHelloWorldAsString>
		</S:Body>
	</S:Envelope> 

服务器发送响应:

 HTTP/1.1 200 OK
Transfer-encoding: chunked
Content-type: text/xml; charset=utf-8

<?xml version="1.0" ?>
	<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
		<S:Body>
			<ns2:getHelloWorldAsStringResponse xmlns:ns2="http://ws.mkyong.com/">
				<return>Hello World JAX-WS mkyong</return>
			</ns2:getHelloWorldAsStringResponse>
		</S:Body>
	</S:Envelope> 

下载源代码

Download It – JAX-WS-HelloWorld-Document-Example.zip (10KB)hello world jax-ws web services

JAX-WS Hello World 示例 RPC 风格

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/webservices/jax-ws/jax-ws-hello-world-example/

JAX-WS 与 JDK 1.6 捆绑在一起,这使得 Java web 服务开发更容易开发。本教程向您展示了如何执行以下任务:

  1. 使用 JAX-WS 创建一个基于 SOAP 的 RPC 样式的 web 服务端点。
  2. 手动创建 Java web 服务客户端。
  3. 通过 wsimport 工具创建一个 Java web 服务客户端。
  4. 创建一个 Ruby web 服务客户端。

你会惊奇地发现在 JAX WS 中开发一个 RPC 样式 web 服务是多么简单。

Note
In general words, “web service endpoint” is a service which published outside for user to access; where “web service client” is the party who access the published service.

JAX-WS Web 服务端点

以下步骤显示了如何使用 JAX-WS 来创建 RPC 样式的 web 服务端点。

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

1.创建 Web 服务端点接口

文件:HelloWorld.java

 package com.mkyong.ws;

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;

//Service Endpoint Interface
@WebService
@SOAPBinding(style = Style.RPC)
public interface HelloWorld{

	@WebMethod String getHelloWorldAsString(String name);

} 

2.创建 Web 服务端点实现

文件:HelloWorldImpl.java

 package com.mkyong.ws;

import javax.jws.WebService;

//Service Implementation
@WebService(endpointInterface = "com.mkyong.ws.HelloWorld")
public class HelloWorldImpl implements HelloWorld{

	@Override
	public String getHelloWorldAsString(String name) {
		return "Hello World JAX-WS " + name;
	}

} 

3.创建端点发布者

文件:HelloWorldPublisher.java

 package com.mkyong.endpoint;

import javax.xml.ws.Endpoint;
import com.mkyong.ws.HelloWorldImpl;

//Endpoint publisher
public class HelloWorldPublisher{

	public static void main(String[] args) {
	   Endpoint.publish("http://localhost:9999/ws/hello", new HelloWorldImpl());
    }

} 

运行端点发布器,您的“ hello world web 服务部署在 URL“http://localhost:9999/ws/hello”中。

4.测试一下

您可以通过这个 URL "http://localhost:9999/ws/hello?wsdl ”。

Web 服务客户端

好了,web 服务已正确部署,现在让我们看看如何创建 web 服务客户端来访问已发布的服务。

1.Java Web 服务客户端

无需工具,您可以创建一个 Java web 服务客户端,如下所示:

 package com.mkyong.client;

import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import com.mkyong.ws.HelloWorld;

public class HelloWorldClient{

	public static void main(String[] args) throws Exception {

	URL url = new URL("http://localhost:9999/ws/hello?wsdl");

        //1st argument service URI, refer to wsdl document above
	//2nd argument is service name, refer to wsdl document above
        QName qname = new QName("http://ws.mkyong.com/", "HelloWorldImplService");

        Service service = Service.create(url, qname);

        HelloWorld hello = service.getPort(HelloWorld.class);

        System.out.println(hello.getHelloWorldAsString("mkyong"));

    }

} 

输出

 Hello World JAX-WS mkyong 

2.通过 wsimport 工具的 Java Web 服务客户端

或者,您可以使用" wsimport 工具来解析发布的 wsdl 文件,并生成必要的客户端文件(存根)来访问发布的 web 服务。

Where is wsimport?
This wsimport tool is bundle with the JDK, you can find it at “JDK_PATH/bin” folder.

发出“ wsimport 命令。

 wsimport -keep http://localhost:9999/ws/hello?wsdl 

它将生成必要的客户端文件,这取决于所提供的 wsdl 文件。在这种情况下,它将生成一个接口和一个服务实现文件。

文件:HelloWorld.java

 package com.mkyong.ws;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;

/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.1.1 in JDK 6
 * Generated source version: 2.1
 * 
 */
@WebService(name = "HelloWorld", targetNamespace = "http://ws.mkyong.com/")
@SOAPBinding(style = SOAPBinding.Style.RPC)
public interface HelloWorld {

    /**
     * 
     * @param arg0
     * @return
     *     returns java.lang.String
     */
    @WebMethod
    @WebResult(partName = "return")
    public String getHelloWorldAsString(
        @WebParam(name = "arg0", partName = "arg0")
        String arg0);

} 

文件:HelloWorldImplService.java

 package com.mkyong.ws;

import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceFeature;

/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.1.1 in JDK 6
 * Generated source version: 2.1
 * 
 */
@WebServiceClient(name = "HelloWorldImplService", 
	targetNamespace = "http://ws.mkyong.com/", 
	wsdlLocation = "http://localhost:9999/ws/hello?wsdl")
public class HelloWorldImplService
    extends Service
{

    private final static URL HELLOWORLDIMPLSERVICE_WSDL_LOCATION;

    static {
        URL url = null;
        try {
            url = new URL("http://localhost:9999/ws/hello?wsdl");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        HELLOWORLDIMPLSERVICE_WSDL_LOCATION = url;
    }

    public HelloWorldImplService(URL wsdlLocation, QName serviceName) {
        super(wsdlLocation, serviceName);
    }

    public HelloWorldImplService() {
        super(HELLOWORLDIMPLSERVICE_WSDL_LOCATION, 
			new QName("http://ws.mkyong.com/", "HelloWorldImplService"));
    }

    /**
     * 
     * @return
     *     returns HelloWorld
     */
    @WebEndpoint(name = "HelloWorldImplPort")
    public HelloWorld getHelloWorldImplPort() {
        return (HelloWorld)super.getPort(
			new QName("http://ws.mkyong.com/", "HelloWorldImplPort"), 
			HelloWorld.class);
    }

    /**
     * 
     * @param features
     *  A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy.  
     *  Supported features not in the <code>features</code> parameter will have their default values.
     * @return
     *  returns HelloWorld
     */
    @WebEndpoint(name = "HelloWorldImplPort")
    public HelloWorld getHelloWorldImplPort(WebServiceFeature... features) {
        return (HelloWorld)super.getPort(
			new QName("http://ws.mkyong.com/", "HelloWorldImplPort"), 
			HelloWorld.class, 
			features);
    }

} 

现在,创建一个依赖于上面生成的文件的 Java web 服务客户机。

 package com.mkyong.client;

import com.mkyong.ws.HelloWorld;
import com.mkyong.ws.HelloWorldImplService;

public class HelloWorldClient{

	public static void main(String[] args) {

		HelloWorldImplService helloService = new HelloWorldImplService();
		HelloWorld hello = helloService.getHelloWorldImplPort();

		System.out.println(hello.getHelloWorldAsString("mkyong"));

    }

} 

这是输出

 Hello World JAX-WS mkyong 

3.Ruby Web 服务客户端

web 服务开发经常与其他编程语言混合使用。所以,这里有一个 Ruby web 服务客户端的例子,它被用来访问已发布的 JAX-WS 服务。

# package for SOAP-based services
require 'soap/wsdlDriver'

wsdl_url = 'http://localhost:9999/ws/hello?wsdl'

service = SOAP::WSDLDriverFactory.new(wsdl_url).create_rpc_driver

# Invoke service operations.
data1 = service.getHelloWorldAsString('mkyong')

# Output results.
puts "getHelloWorldAsString : #{data1}"

输出

 getHelloWorldAsString : Hello World JAX-WS mkyong 

跟踪 SOAP 流量

从上到下,展示了 SOAP 信封如何在客户机和服务器之间流动。再次参见#1 web 服务客户端:

 URL url = new URL("http://localhost:9999/ws/hello?wsdl");
    QName qname = new QName("http://ws.mkyong.com/", "HelloWorldImplService");
    Service service = Service.create(url, qname);

    HelloWorld hello = service.getPort(HelloWorld.class);

    System.out.println(hello.getHelloWorldAsString("mkyong")); 

Note
To monitor SOAP traffic is very easy, see this guide – “How to trace SOAP message in Eclipse IDE“.

1.申请一份 WSDL 档案

首先,客户端向服务端点发送 wsdl 请求,请参见下面的 HTTP 流量:

客户端发送请求:

 GET /ws/hello?wsdl HTTP/1.1
User-Agent: Java/1.6.0_13
Host: localhost:9999
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive 

服务器发送响应:

 HTTP/1.1 200 OK
Transfer-encoding: chunked
Content-type: text/xml;charset=utf-8

<?xml version="1.0" encoding="UTF-8"?>

<definitions 
	xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" 
	xmlns:tns="http://ws.mkyong.com/" 
	xmlns:xsd="http://www.w3.org/2001/XMLSchema" 

	targetNamespace="http://ws.mkyong.com/" 
	name="HelloWorldImplService">

	<types></types>

<message name="getHelloWorldAsString">
	<part name="arg0" type="xsd:string"></part>
</message>
<message name="getHelloWorldAsStringResponse">
	<part name="return" type="xsd:string"></part>
</message>

<portType name="HelloWorld">
	<operation name="getHelloWorldAsString" parameterOrder="arg0">
		<input message="tns:getHelloWorldAsString"></input>
		<output message="tns:getHelloWorldAsStringResponse"></output>
	</operation>
</portType>

<binding name="HelloWorldImplPortBinding" type="tns:HelloWorld">

	<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"></soap:binding>
	<operation name="getHelloWorldAsString">
		<soap:operation soapAction=""></soap:operation>
		<input>
			<soap:body use="literal" namespace="http://ws.mkyong.com/"></soap:body>
		</input>
		<output>
			<soap:body use="literal" namespace="http://ws.mkyong.com/"></soap:body>
		</output>
	</operation>

</binding>

<service name="HelloWorldImplService">
<port name="HelloWorldImplPort" binding="tns:HelloWorldImplPortBinding">
<soap:address location="http://localhost:9999/ws/hello"></soap:address>
</port>
</service>
</definitions> 

2.hello.getHelloWorldAsString()

第二次调用,客户端将方法调用请求放入 SOAP 信封,并将其发送到服务端点。在服务端点,调用请求的方法,将结果放入 SOAP 信封,并将其发送回客户端。

客户端发送请求:

 POST /ws/hello HTTP/1.1
SOAPAction: ""
Accept: text/xml, multipart/related, text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Content-Type: text/xml; charset=utf-8
User-Agent: Java/1.6.0_13
Host: localhost:9999
Connection: keep-alive
Content-Length: 224

<?xml version="1.0" ?>
	<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
		<S:Body>
			<ns2:getHelloWorldAsString xmlns:ns2="http://ws.mkyong.com/">
				<arg0>mkyong</arg0>
			</ns2:getHelloWorldAsString>
		</S:Body>
	</S:Envelope> 

服务器发送响应:

 HTTP/1.1 200 OK
Transfer-encoding: chunked
Content-type: text/xml; charset=utf-8

<?xml version="1.0" ?>
	<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
		<S:Body>
			<ns2:getHelloWorldAsStringResponse xmlns:ns2="http://ws.mkyong.com/">
				<return>Hello World JAX-WS mkyong</return>
			</ns2:getHelloWorldAsStringResponse>
		</S:Body>
	</S:Envelope> 

完成,任何意见,不胜感激。

下载源代码

Download It – JAX-WS-HelloWorld-RPC-Example.zip (14KB)Tags : hello world jax-ws web servicesfreestar.config.enabled_slots.push({ placementName: "mkyong_leaderboard_btf", slotId: "mkyong_leaderboard_btf" });

JAX-WS 教程

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/tutorials/jax-ws-tutorials/

jaxws tutorials

Java API for XML Web Services(JAX-WS),是一组用于创建 XML 格式(SOAP)的 Web 服务的 API。JAX-WS 提供了许多注释来简化 web 服务客户端和 web 服务提供者(端点)的开发和部署。

在本教程中,它提供了许多关于 JAX-WS 2.0 和 JAXWS 2.1 的分步示例和解释。

快乐学习 JAX🙂

快速启动

JAX-WS 2.x 的一些快速入门示例

jax-ws-disgram

图:JAX-WS 通讯-图片来源

  • JAX-WS hello world 示例-RPC 样式
    教程向您展示如何使用 JAX-WS,以及 Java、wsimport 和 Ruby 中的 web 服务客户端来创建 RPC 样式的 web 服务端点。
  • JAX-WS Hello World 示例-文档样式
    教程向您展示了如何使用 JAX-WS 创建文档样式的 web 服务端点,并展示了客户端和服务器之间的 SOAP 信封流。
  • 如何在 Eclipse IDE 中跟踪 SOAP 消息
    教程向您展示了如何在 Eclipse IDE 中启用这个“TCP/IP Monitor ”,并且还拦截 web 服务生成的 SOAP 消息。
  • JAX-WS : wsimport 工具示例
    WS import 工具用于解析现有的 web 服务描述语言(WSDL)文件,并生成 web 服务客户端访问已发布的 Web 服务所需的文件(JAX-WS 可移植工件)。
  • JAX-WS : wsgen 工具示例
    wsgen 工具用于解析现有的 web 服务实现类,并生成 web 服务部署所需的文件(JAX-WS 可移植工件)。

JAX-WS 附件

如何在 JAX-WS 2.x 中处理附件

  • 一个完整的基于 JAX-WS SOAP 的例子,展示了如何使用消息传输优化机制(MTOM)和 XML-二进制优化打包(XOP)技术在服务器和客户端之间发送二进制附件(图像)。

JAX-WS 处理器

SOAP handler 是一个 SOAP 消息拦截器,它能够拦截传入或传出的 SOAP 消息并操纵其值。

JAX-WS 集成

如何将 JAX WS 与 Web 应用和 Spring 框架集成?

Tomcat 中的 JAX-WS 安全性

如何在 Tomcat 中实现 JAX-WS 安全性?

JAX-WS 错误消息

JAX-WS 开发中的一些常见错误消息。

参考

  1. http://jax-ws.java.net/
  2. http://download.oracle.com/javaee/5/tutorial/doc/bnayn.html
  3. http://Java . sun . com/developer/technical articles/web services/high _ performance/
  4. http://Java . sun . com/developer/technical articles/J2SE/jax _ ws _ 2/
  5. http://blogs.sun.com/kamna/entry/using_jax_ws_handlers_to
  6. http://tomcat.apache.org/tomcat-6.0-doc/realm-howto.html
  7. http://www . IBM . com/developer works/web services/library/ws-doc style . html
  8. http://www . Oracle . com/technology/sample _ code/tech/Java/J2EE/jind demo/tutorials/web services . html
  9. http://www.coderanch.com/how-to/java/WebServicesFaq
  10. http://www . Oracle . com/tech network/articles/javase/index-137171 . html

JAXB hello world 示例

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/java/jaxb-hello-world-example/

java xml logo

Jakarta XML 绑定(JAXB;以前的 Java Architecture for XML Binding)是一个 XML 绑定框架,用于在 Java 对象和 XML 之间进行转换。

  1. XML 编组–将 Java 对象转换成 XML。
  2. XML 解组——将 XML 转换回 Java 对象。


本文将重点介绍 Java 11 ,JAXB 3 和 EclipseLink MOXy JAXB RI

目录

1。Java 6、7、8、Java 9、10、11 以及更高版本上的 JAXB

下面是 Jakarta XML 绑定的简史(JAXB 以前的 XML 绑定 Java 架构)。

  1. 随着基于 XML 的 web 服务的兴起,JAXB 成为了 Java 6 的一部分。
  2. 基于 JSON 的 web 服务或 REST web 结构的兴起,使得开发者从 XML 迁移到 JSON 和 REST。
  3. JAXB 仍然是 Java 7 和 Java 8 的一部分。
  4. Java 9 弃用了 Java EE 模块,包括 JAXB javax.xml.*,并将其标记为弃用以移除,这意味着 JAXB 仍然是 Java 9 的一部分,未来的 Java 版本将移除它们。
  5. JAXB javax.xml.*仍然被弃用,并且是 Java 10 的一部分。
  6. JAXB 仍然是 Java 9 和 Java 10 的一部分,但是被禁用或者不包含在默认的模块路径中;但是,我们仍然可以通过--add-modules显式启用它(不推荐)。推荐的解决方案是添加一个单独的 JAXB API 和 JAXB 实现。
  7. 微服务的兴起,开发者想要一个小巧轻便的 Java 运行时。
  8. Java 11 完全移除了 JAXB javax.xml.*。现在,我们需要添加一个单独的 JAXB API 和 JAXB 实现来使用 JAXB 特性。
  9. Oracle 向 Eclipse Foundation 提交了 Java EE,Java EE 更名为 Jakarta EE 是因为商标“Java”。JAXB javax.xml.*从 3.0 版本开始也重新打包到了jakarta.xml.*

延伸阅读

2。Java 11 和 JAXB RI 依赖关系

JAXB 是一个规范 JSR-222 ,下面是两个常见的 JAXB 实现:

下面是 Maven EclipseLink MOXy 依赖。

pom.xml

 <!-- JAXB API only -->
  <dependency>
      <groupId>jakarta.xml.bind</groupId>
      <artifactId>jakarta.xml.bind-api</artifactId>
      <version>3.0.0</version>
  </dependency>

  <!-- JAXB RI, EclipseLink MOXy -->
  <dependency>
      <groupId>org.eclipse.persistence</groupId>
      <artifactId>org.eclipse.persistence.moxy</artifactId>
      <version>3.0.0</version>
  </dependency> 

2.1 Jakarta XML 绑定

下面是 Maven Jakarta XML 绑定依赖。

pom.xml

 <!-- JAXB API only -->
  <dependency>
      <groupId>jakarta.xml.bind</groupId>
      <artifactId>jakarta.xml.bind-api</artifactId>
      <version>3.0.0</version>
  </dependency>

  <!-- JAXB RI, Jakarta XML Binding -->
  <dependency>
      <groupId>com.sun.xml.bind</groupId>
      <artifactId>jaxb-impl</artifactId>
      <version>3.0.0</version>
      <scope>runtime</scope>
  </dependency> 

如果我们仍然喜欢旧的 JAXB 包javax.xml.*,那么坚持使用 JAXB 版本 2.x。

pom.xml

 <dependency>
      <groupId>jakarta.xml.bind</groupId>
      <artifactId>jakarta.xml.bind-api</artifactId>
      <version>2.3.3</version>
  </dependency>

  <dependency>
      <groupId>com.sun.xml.bind</groupId>
      <artifactId>jaxb-ri</artifactId>
      <version>2.3.3</version>
  </dependency> 

  • 在 Java 6、7 和 8 中,JAXB 是 JDK 的一部分。
  • 在 Java 9、10、11 和更高版本中,我们需要添加单独的 JAXB API 和 JAXB RI 或实现库来使用 JAXB 特性。

3。JAXB hello world 示例

带有 JAXB 注释的类。

Fruit.java

 package com.mkyong.xml.jaxb.model;

import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlRootElement;

@XmlRootElement
// order of the fields in XML
// @XmlType(propOrder = {"price", "name"})
@XmlAccessorType(XmlAccessType.FIELD)
public class Fruit {

    @XmlAttribute
    int id;

    @XmlElement(name = "n")
    String name;

    String price;

    // getter, setter and toString...
} 

3.1 JAXB XML 编组——将 Java 对象转换成 XML

下面的 XML 编组 JAXB 示例将 Java 对象转换成 XML。

JaxbExampleFruit1.java

 package com.mkyong.xml.jaxb;

import com.mkyong.xml.jaxb.model.Fruit;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Marshaller;

import java.io.File;

public class JaxbExampleFruit1 {

    public static void main(String[] args) {

        JAXBContext jaxbContext = null;
        try {

            // Normal JAXB RI
            //jaxbContext = JAXBContext.newInstance(Fruit.class);

            // EclipseLink MOXy needs jaxb.properties at the same package with Fruit.class
            // Alternative, I prefer define this via eclipse JAXBContextFactory manually.
            jaxbContext = org.eclipse.persistence.jaxb.JAXBContextFactory
                    .createContext(new Class[]{Fruit.class}, null);

            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

            // output pretty printed
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            Fruit o = new Fruit();
            o.setId(1);
            o.setName("Banana");
            o.setPrice("9.99");

            // output to a xml file
            jaxbMarshaller.marshal(o, new File("C:\\test\\fruit.xml"));

            // output to console
            // jaxbMarshaller.marshal(o, System.out);

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

    }

} 

输出

C:\test\fruit.xml

 <?xml version="1.0" encoding="UTF-8"?>
<fruit id="1">
   <n>Banana</n>
   <price>9.99</price>
</fruit> 

3.2 JAXB XML 解组——将 XML 转换成 Java 对象

下面是 XML 解组的 JAXB 示例,将 XML 转换回 Java 对象。

JaxbExampleFruit2.java

 package com.mkyong.xml.jaxb;

import com.mkyong.xml.jaxb.model.Fruit;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Unmarshaller;

import java.io.File;

public class JaxbExampleFruit2 {

  public static void main(String[] args) {

      JAXBContext jaxbContext = null;
      try {

          // Normal JAXB RI
          //jaxbContext = JAXBContext.newInstance(Fruit.class);

          // EclipseLink MOXy needs jaxb.properties at the same package with Fruit.class
          // Alternative, I prefer define this via eclipse JAXBContextFactory manually.
          jaxbContext = org.eclipse.persistence.jaxb.JAXBContextFactory
                  .createContext(new Class[]{Fruit.class}, null);

          File file = new File("C:\\test\\fruit.xml");

          Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

          Fruit o = (Fruit) jaxbUnmarshaller.unmarshal(file);

          System.out.println(o);

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

  }

} 

输出

Terminal

 Fruit{id=1, name='Banana', price='9.99'} 

4。什么是@XmlAccessorType(XmlAccessType。场)

默认情况下,JAXB 实现将 getter/setter 对、公共字段和 JAXB 注释的非公共字段用于 XML 转换。

4.1 再次检查Fruit类,如果我们注释掉@XmlAccessorType(XmlAccessType.FIELD),并重新运行上面的 JAXB 程序。

Fruit.java

 @XmlRootElement
//@XmlAccessorType(XmlAccessType.FIELD)
public class Fruit {

    @XmlAttribute
    int id;

    @XmlElement(name = "n")
    String name;

    String price;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getPrice() {
        return price;
    }

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

    @Override
    public String toString() {
        return "Fruit{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price='" + price + '\'' +
                '}';
    } 

4.2 我们将得到下面的Class has two properties of the same name错误信息。

Terminal

 Class has two properties of the same name "id"
	this problem is related to the following location:
		at public int com.mkyong.xml.jaxb.model.Fruit.getId()
		at com.mkyong.xml.jaxb.model.Fruit
	this problem is related to the following location:
		at int com.mkyong.xml.jaxb.model.Fruit.id
		at com.mkyong.xml.jaxb.model.Fruit

Class has two properties of the same name "name"
	this problem is related to the following location:
		at public java.lang.String com.mkyong.xml.jaxb.model.Fruit.getName()
		at com.mkyong.xml.jaxb.model.Fruit
	this problem is related to the following location:
		at java.lang.String com.mkyong.xml.jaxb.model.Fruit.name
		at com.mkyong.xml.jaxb.model.Fruit 

JAXB 将把Fruit.getId()Fruit.id(因为我们用@XmlAttribute@XmlElement标注)视为同一个属性;为了解决这个问题,我们在类上添加了一个@XmlAccessorType(XmlAccessType.FIELD),告诉 JAXB 只将Fruit.id作为属性。


eclipse link MOXy JAXB 不存在上述问题。

5。javax.xml.和 jakarta.xml.

的区别

Eclipse foundation 将 Java EE javax.xml.*更名为 Jakarta EE jakarta.xml.*

下面是版本 2 和 3 中的一些 JAXB APIs。

 // Jakarta EE
// @Since 3.0.0, rebrand to jakarta.xml
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Marshaller;

// Java EE
// old APIs JAXB version 2.*
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller; 

【JAXB 版本 2 的 5.1 Java EE,javax . XML . *

在 JAXB 版本 2 中,API 使用旧的 Java EE 包javax.xml.*

pom.xml

 <dependency>
      <groupId>javax.xml.bind</groupId>
      <artifactId>jaxb-api</artifactId>
      <version>2.3.1</version>
  </dependency>

  <!-- JAXB RI -->
  <dependency>
      <groupId>org.eclipse.persistence</groupId>
      <artifactId>org.eclipse.persistence.moxy</artifactId>
      <version>2.7.8</version>
  </dependency> 

5.2 Jakarta EE,jakarta.xml.*适用于 JAXB 版本 3

在 JAXB 版本 3.x 和更高版本中,API 被重新打包到 Jakarta EE 包jakarta.xml.*

pom.xml

 <!-- JAXB API -->
  <dependency>
      <groupId>jakarta.xml.bind</groupId>
      <artifactId>jakarta.xml.bind-api</artifactId>
      <version>3.0.0</version>
  </dependency>

  <!-- JAXB RI -->
  <dependency>
      <groupId>org.eclipse.persistence</groupId>
      <artifactId>org.eclipse.persistence.moxy</artifactId>
      <version>3.0.0</version>
  </dependency> 

6。JAXB 示例、列表、时间和 CDATA 适配器

下面的 JAXB 例子涉及以下内容:

  1. 一个Company.class包含一个Staff.class列表,带有用于 XML 转换的 JAXB 注释。
  2. 使用@XmlJavaTypeAdapter转换 Java 8 ZonedDateTime
  3. 对于特殊字符的 XML CDATA,@XmlCDATA只在 EclipseLink MOXy JAXB RI 中可用。

6.1 JAXB 域类

两个带有 JAXB 注释的域类。

Staff.java

 package com.mkyong.xml.jaxb.model;

import com.mkyong.xml.jaxb.adaptor.TimeZoneAdaptor;

// @Since 3.0
import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.eclipse.persistence.oxm.annotations.XmlCDATA;

// Java 8?
//import com.sun.xml.internal.txw2.annotation.XmlCDATA;
// jaxb 2
//import javax.xml.bind.annotation.*;

import java.time.ZonedDateTime;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Staff {

  @XmlAttribute
  int id;

  String name;

  String Salary;

  @XmlCDATA
  String bio;

  @XmlJavaTypeAdapter(TimeZoneAdaptor.class)
  ZonedDateTime joinDate;

  //getters, setters
} 

Company.java

 package com.mkyong.xml.jaxb.model;

//import javax.xml.bind.annotation.*;

// @Since 3.0.0
import jakarta.xml.bind.annotation.*;

import java.util.List;

@XmlRootElement
@XmlType(propOrder = {"name", "list"})
@XmlAccessorType(XmlAccessType.FIELD)
public class Company {

  @XmlElement(name = "staff")
  List<Staff> list;

  String name;

  // getters, and setters
} 

6.2 JAXB 适配器

我们可以使用@XmlJavaTypeAdapterZonedDateTime(或其他类型)与String相互转换。

TimeZoneAdaptor.java

 package com.mkyong.xml.jaxb.adaptor;

// @Since 3.0.0
import jakarta.xml.bind.annotation.adapters.XmlAdapter;
//import javax.xml.bind.annotation.adapters.XmlAdapter;

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class TimeZoneAdaptor extends XmlAdapter<String, ZonedDateTime> {

    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;

    @Override
    public ZonedDateTime unmarshal(String v) throws Exception {
        ZonedDateTime parse = ZonedDateTime.parse(v, dateTimeFormatter);
        return parse;
    }

    @Override
    public String marshal(ZonedDateTime v) throws Exception {
        return dateTimeFormatter.format(v);
    }
} 

6.3 JAXB 和 CDATA

对于 XML 文档中的一些特殊字符,比如<&,我们需要 CDATA

我们选择 EclipseLink MOXy JAXB RI 是因为有一个内置的@XmlCDATA自动用CDATA将文本换行。

Staff.java

 import org.eclipse.persistence.oxm.annotations.XmlCDATA;

//...

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Staff {

  //...
  @XmlCDATA
  String bio; 

6.4 运行 JAXB

下面的 JAXB 示例尝试将对象列表转换为 XML 文档。

JaxbExample.java

 package com.mkyong.xml.jaxb;

import com.mkyong.xml.jaxb.model.Company;
import com.mkyong.xml.jaxb.model.Staff;

// @Since 3.0.0, rebrand to jakarta.xml
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Marshaller;

// old APIs 2.3.*,
//import javax.xml.bind.JAXBContext;
//import javax.xml.bind.JAXBException;
//import javax.xml.bind.Marshaller;

import java.io.File;
import java.time.ZonedDateTime;
import java.util.Arrays;

public class JaxbExample {

    public static void main(String[] args) {

        JAXBContext jaxbContext = null;
        try {

            //jaxbContext = JAXBContext.newInstance(Company.class);

            // EclipseLink MOXy needs jaxb.properties at the same package with Company.class or Staff.class
            // Alternative, I prefer define this via eclipse JAXBContextFactory manually.
            jaxbContext = org.eclipse.persistence.jaxb.JAXBContextFactory
                    .createContext(new Class[] {Company.class}, null);

            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

            // output pretty printed
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            //jaxbMarshaller.marshal(createCompanyObject(), new File("C:\\test\\company.xml"));

            jaxbMarshaller.marshal(createCompanyObject(), System.out);

            // XML Unmarshalling
            /*File file = new File("C:\\test\\company.xml");
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            Company o = (Company) jaxbUnmarshaller.unmarshal(file);
            System.out.println(o);*/

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

    }

    private static Company createCompanyObject() {

        Company comp = new Company();
        comp.setName("ABCDEFG Enterprise");

        Staff o1 = new Staff();
        o1.setId(1);
        o1.setName("mkyong");
        o1.setSalary("8000 & Bonus");
        o1.setBio("<h1>support</h1>");
        o1.setJoinDate(ZonedDateTime.now().minusMonths(12));

        Staff o2 = new Staff();
        o2.setId(2);
        o2.setName("yflow");
        o2.setSalary("9000");
        o2.setBio("<h1>developer & database</h1>");
        o2.setJoinDate(ZonedDateTime.now().minusMonths(6));

        comp.setList(Arrays.asList(o1, o2));

        return comp;
    }
} 

输出

Terminal

 <?xml version="1.0" encoding="UTF-8"?>
<company>
 <name>ABCDEFG Enterprise</name>
 <staff id="1">
    <name>mkyong</name>
    <Salary>8000 &amp; Bonus</Salary>
    <bio><![CDATA[<h1>support</h1>]]></bio>
    <joinDate>2020-04-21T12:19:28.5450719+08:00</joinDate>
 </staff>
 <staff id="2">
    <name>yflow</name>
    <Salary>9000</Salary>
    <bio><![CDATA[<h1>developer & database</h1>]]></bio>
    <joinDate>2020-10-21T12:19:28.5450719+08:00</joinDate>
 </staff>
</company> 

7 .。JAXB 提示

一些常见的 JAXB 问题和技巧。

7.1 XML 漂亮打印

默认情况下,JAXB 以紧凑模式输出 XML。

 <?xml version="1.0" encoding="UTF-8"?><fruit id="1">
  <n>Banana</n><price>9.99</price></fruit> 

为了让 JAXB 以漂亮的打印或格式化模式输出 XML,我们可以将属性Marshaller.JAXB_FORMATTED_OUTPUT设置为true

 // default false
  jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 

输出

 <?xml version="1.0" encoding="UTF-8"?>
<fruit id="1">
   <n>Banana</n>
   <price>9.99</price>
</fruit> 

7.2 更改 XML 编码

JAXB 默认 XML 编码为encoding="UTF8",我们可以通过属性Marshaller.JAXB_ENCODING配置指定的 XML 编码。

 // change XML encoding
  jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, "ISO-8859-1"); 

输出

 <?xml version="1.0" encoding="ISO-8859-1"?> 

7.3 删除 XML 声明

将属性Marshaller.JAXB_FRAGMENT设置为true,它将删除开始的 XML 声明。

 // default false
  // remove <?xml version="1.0" encoding="UTF-8"?>
  jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); 

输出

 <fruit id="1">
 <n>Banana</n>
 <price>9.99</price>
</fruit> 

7.4 改变字段的顺序

我们可以使用@XmlType propOrder来改变写入 XML 文档的字段的顺序。

再次复习Fruit课。

Fruit.java

 @XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Fruit {

    @XmlAttribute
    int id;

    @XmlElement(name = "n")
    String name;

    String price;

    //...
} 

输出

 <?xml version="1.0" encoding="UTF-8"?>
<fruit id="1">
   <n>Banana</n>
   <price>9.99</price>
</fruit> 

我们可以使用@XmlType propOrder来控制字段的顺序;例如,下面的例子想要首先显示price

Fruit.java

 package com.mkyong.xml.jaxb.model;

import jakarta.xml.bind.annotation.XmlAccessType;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlType;

@XmlRootElement
@XmlType(propOrder = {"price", "name"})
@XmlAccessorType(XmlAccessType.FIELD)
public class Fruit {

  @XmlAttribute
  int id;

  @XmlElement(name = "n")
  String name;

  String price;

  //...
} 

输出

 <?xml version="1.0" encoding="UTF-8"?>
<fruit id="1">
   <price>9.99</price>
   <n>Banana</n>
</fruit> 

7.5 隐藏指定的映射字段

我们可以使用@XmlTransient来隐藏或阻止特定字段转换成 XML。

Fruit.java

 import jakarta.xml.bind.annotation.XmlTransient;

//...

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Fruit {

    @XmlAttribute
    int id;

    @XmlElement(name = "n")
    String name;

    // Prevents the mapping
    @XmlTransient
    String price; 

输出

 <?xml version="1.0" encoding="UTF-8"?>
<fruit id="1">
  <n>Banana</n>
</fruit> 

7.6 没有找到 JAXB-API 的实现

我们需要提供一个 JAXB RI 或实现,参考这篇文章

相关错误

8。下载源代码

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

$ cd java-xml

$ CD src/main/Java/com/mkyong/XML/JAXB/

9。参考文献

JDBC 可调用语句–PostgreSQL 存储函数

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/jdbc/jdbc-callablestatement-postgresql-stored-function/

一个 JDBC 的例子向你展示了如何从 PostgreSQL 数据库中调用一个存储函数。

PS 用 PostgreSQL 11 和 Java 8 测试

pom.xml

 <dependency>
		<groupId>org.postgresql</groupId>
		<artifactId>postgresql</artifactId>
		<version>42.2.5</version>
	</dependency> 

1.呼叫功能

1.1 创建一个存储函数并通过 JDBC 调用它。

FunctionReturnString.java

 package com.mkyong.jdbc.callablestatement;

import java.sql.*;

public class FunctionReturnString {

    public static void main(String[] args) {

        String createFunction = "CREATE OR REPLACE FUNCTION hello(p1 TEXT) RETURNS TEXT "
                + " AS $$ "
                + " BEGIN "
                + " RETURN 'hello ' || p1; "
                + " END; "
                + " $$ "
                + " LANGUAGE plpgsql";

        String runFunction = "{ ? = call hello( ? ) }";

        try (Connection conn = DriverManager.getConnection(
                "jdbc:postgresql://127.0.0.1:5432/test", "postgres", "password");
             Statement statement = conn.createStatement();
             CallableStatement callableStatement = conn.prepareCall(runFunction)) {

            // create or replace stored function
            statement.execute(createFunction);

            //----------------------------------

            // output
            callableStatement.registerOutParameter(1, Types.VARCHAR);

            // input
            callableStatement.setString(2, "mkyong");

            // Run hello() function
            callableStatement.executeUpdate();

            // Get result
            String result = callableStatement.getString(1);

            System.out.println(result);

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

    }
} 

输出

 hello mkyong 

1.2 SQL 版本。

 CREATE OR REPLACE FUNCTION hello(p1 TEXT) RETURNS TEXT 
AS $$
BEGIN
    RETURN 'hello ' || p1;
END;
$$
LANGUAGE plpgsql;

-- run it 
select hello('mkyong');
-- output: hello mkyong 

2.函数返回 SETOF

2.1 对于作为SETOF返回数据的函数,我们应该使用普通的StatementPreparedStatement,而不是CallableStatement

P.S 表 pg_roles 是包含数据库角色的系统表

FunctionReturnResultSet.java

 package com.mkyong.jdbc.callablestatement;

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

public class FunctionReturnResultSet {

    public static void main(String[] args) {

        List<String> users = new ArrayList<>();

        String createFunction = "CREATE OR REPLACE FUNCTION getRoles() RETURNS SETOF pg_roles "
                + " AS 'select * from pg_roles' LANGUAGE sql;";

        String runFunction = "select * from getRoles();";

        try (Connection conn = DriverManager.getConnection(
                "jdbc:postgresql://127.0.0.1:5432/test", "postgres", "password");
             Statement statement = conn.createStatement()) {

            // create a function returns as SETOF
            statement.execute(createFunction);

            // run it
            ResultSet resultSet = statement.executeQuery(runFunction);
            while (resultSet.next()) {
                users.add(resultSet.getString("rolname"));
            }

            System.out.println("Database roles...");
            users.forEach(x -> System.out.println(x));

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

    }
} 

输出

 Database roles...
pg_signal_backend
pg_read_server_files
postgres
pg_write_server_files
pg_execute_server_program
pg_read_all_stats
pg_monitor
pg_read_all_settings
pg_stat_scan_tables 

2.2 SQL 版本。

 CREATE OR REPLACE FUNCTION getRoles() RETURNS SETOF pg_roles 
AS 'select * from pg_roles' LANGUAGE sql;

-- run it 
select * from getRoles(); 

3.函数返回光标

3.1 JDBC +参考光标示例。

FunctionReturnRefCursor.java

 package com.mkyong.jdbc.callablestatement;

import java.sql.*;

public class FunctionReturnRefCursor {

    public static void main(String[] args) {

        String createFunction = "CREATE OR REPLACE FUNCTION getUsers(mycurs OUT refcursor) "
                + " RETURNS refcursor "
                + " AS $$ "
                + " BEGIN "
                + "     OPEN mycurs FOR select * from pg_user; "
                + " END; "
                + " $$ "
                + " LANGUAGE plpgsql";

        String runFunction = "{? = call getUsers()}";

        try (Connection conn = DriverManager.getConnection(
                "jdbc:postgresql://127.0.0.1:5432/test", "postgres", "password");
             Statement statement = conn.createStatement();
             CallableStatement cs = conn.prepareCall(runFunction);
        ) {

            // We must be inside a transaction for cursors to work.
            conn.setAutoCommit(false);

            // create function
            statement.execute(createFunction);

            // register output
            cs.registerOutParameter(1, Types.REF_CURSOR);

            // run function
            cs.execute();

            // get refcursor and convert it to ResultSet
            ResultSet resultSet = (ResultSet) cs.getObject(1);
            while (resultSet.next()) {
                System.out.println(resultSet.getString("usename"));
                System.out.println(resultSet.getString("passwd"));
            }

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

    }
} 

输出–该数据库包含一个用于测试的用户🙂

 postgres
******** 

3.2 SQL 版本。

 CREATE OR REPLACE FUNCTION getUsers(mycurs OUT refcursor) RETURNS refcursor 
	AS $$
	BEGIN 
		OPEN mycurs FOR select * from pg_user;
	END;
	$$
	LANGUAGE plpgsql; 

下载源代码

$ git clone https://github.com/mkyong/java-jdbc.git

参考

JDBC 可调用语句–存储过程游标示例

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/jdbc/jdbc-callablestatement-stored-procedure-cursor-example/

对于 Oracle 存储过程返回的游标参数,您可以

  1. 通过 JDBC 注册CallableStatement.registerOutParameter(index,OracleTypes.CURSOR)
  2. 通过callableStatement.getObject(index)取回。

查看代码片段

 //getDBUSERCursor is a stored procedure
String getDBUSERCursorSql = "{call getDBUSERCursor(?,?)}";
callableStatement = dbConnection.prepareCall(getDBUSERCursorSql);
callableStatement.setString(1, "mkyong");
callableStatement.registerOutParameter(2, OracleTypes.CURSOR);

// execute getDBUSERCursor store procedure
callableStatement.executeUpdate();

// get cursor and cast it to ResultSet
rs = (ResultSet) callableStatement.getObject(2);

// loop it like normal
while (rs.next()) {
	String userid = rs.getString("USER_ID");
	String userName = rs.getString("USERNAME");
} 

JDBC 可调用语句光标示例

关于输出光标参数,参见完整的 JDBC CallableStatement示例。

1.存储过程

一个 Oracle 存储过程,有一个 IN 和一个 OUT 游标参数。后来,称之为经 JDBC。

 CREATE OR REPLACE PROCEDURE getDBUSERCursor(
	   p_username IN DBUSER.USERNAME%TYPE,
	   c_dbuser OUT SYS_REFCURSOR)
IS
BEGIN

  OPEN c_dbuser FOR
  SELECT * FROM DBUSER WHERE USERNAME LIKE p_username || '%';

END;
/ 

2.通过 CallableStatement 调用存储过程

JDBC 示例调用上述存储过程,将返回的光标转换为结果集,并按顺序遍历记录。

文件:JDBCCallableStatementCURSORExample.java

 package com.mkyong.jdbc;

import java.sql.CallableStatement;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

import oracle.jdbc.OracleTypes;

public class JDBCCallableStatementCURSORExample {

	private static final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver";
	private static final String DB_CONNECTION = "jdbc:oracle:thin:@localhost:1521:MKYONG";
	private static final String DB_USER = "user";
	private static final String DB_PASSWORD = "password";

	public static void main(String[] argv) {

		try {

			callOracleStoredProcCURSORParameter();

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		}

	}

	private static void callOracleStoredProcCURSORParameter()
			throws SQLException {

		Connection dbConnection = null;
		CallableStatement callableStatement = null;
		ResultSet rs = null;

		String getDBUSERCursorSql = "{call getDBUSERCursor(?,?)}";

		try {
			dbConnection = getDBConnection();
			callableStatement = dbConnection.prepareCall(getDBUSERCursorSql);

			callableStatement.setString(1, "mkyong");
			callableStatement.registerOutParameter(2, OracleTypes.CURSOR);

			// execute getDBUSERCursor store procedure
			callableStatement.executeUpdate();

			// get cursor and cast it to ResultSet
			rs = (ResultSet) callableStatement.getObject(2);

			while (rs.next()) {
				String userid = rs.getString("USER_ID");
				String userName = rs.getString("USERNAME");
				String createdBy = rs.getString("CREATED_BY");
				String createdDate = rs.getString("CREATED_DATE");

				System.out.println("UserName : " + userid);
				System.out.println("UserName : " + userName);
				System.out.println("CreatedBy : " + createdBy);
				System.out.println("CreatedDate : " + createdDate);
			}

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		} finally {

			if (rs != null) {
				rs.close();
			}

			if (callableStatement != null) {
				callableStatement.close();
			}

			if (dbConnection != null) {
				dbConnection.close();
			}

		}

	}

	private static Connection getDBConnection() {

		Connection dbConnection = null;

		try {

			Class.forName(DB_DRIVER);

		} catch (ClassNotFoundException e) {

			System.out.println(e.getMessage());

		}

		try {

			dbConnection = DriverManager.getConnection(
				DB_CONNECTION, DB_USER,DB_PASSWORD);
			return dbConnection;

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		}

		return dbConnection;

	}

} 

完成了。

参考

  1. http://www.oradev.com/ref_cursor.jsp
  2. http://download . Oracle . com/javase/6/docs/API/Java/SQL/callable statement . html
  3. http://docsrv . SCO . com/JDK _ guide/JDBC/getstart/callable statement . doc . html
  4. http://on Java . com/pub/a/on Java/2003/08/13/stored _ procedures . html

JDBC 可调用语句–参数示例中的存储过程

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/jdbc/jdbc-callablestatement-stored-procedure-in-parameter-example/

代码片段向您展示了如何通过 JDBC CallableStatement调用 Oracle 存储过程,以及如何从 Java 向存储过程传递参数。

 //insertDBUSER is stored procedure
String insertStoreProc = "{call insertDBUSER(?,?,?,?)}";
callableStatement = dbConnection.prepareCall(insertStoreProc);
callableStatement.setInt(1, 1000);
callableStatement.setString(2, "mkyong");
callableStatement.setString(3, "system");
callableStatement.setDate(4, getCurrentDate());
callableStatement.executeUpdate(); 

JDBC 可调用语句示例

参见完整的 JDBC CallableStatement例子。

1.存储过程

Oracle 数据库中的存储过程。后来,称之为经 JDBC。

 CREATE OR REPLACE PROCEDURE insertDBUSER(
	   p_userid IN DBUSER.USER_ID%TYPE,
	   p_username IN DBUSER.USERNAME%TYPE,
	   p_createdby IN DBUSER.CREATED_BY%TYPE,
	   p_date IN DBUSER.CREATED_DATE%TYPE)
IS
BEGIN

  INSERT INTO DBUSER ("USER_ID", "USERNAME", "CREATED_BY", "CREATED_DATE") 
  VALUES (p_userid, p_username,p_createdby, p_date);

  COMMIT;

END;
/ 

2.通过 CallableStatement 调用存储过程

JDBC 通过CallableStatement调用存储过程的例子。

文件:JDBCCallableStatementINParameterExample.java

 package com.mkyong.jdbc;

import java.sql.CallableStatement;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;

public class JDBCCallableStatementINParameterExample {

	private static final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver";
	private static final String DB_CONNECTION = "jdbc:oracle:thin:@localhost:1521:MKYONG";
	private static final String DB_USER = "user";
	private static final String DB_PASSWORD = "password";

	public static void main(String[] argv) {

		try {

			callOracleStoredProcINParameter();

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		}

	}

	private static void callOracleStoredProcINParameter() throws SQLException {

		Connection dbConnection = null;
		CallableStatement callableStatement = null;

		String insertStoreProc = "{call insertDBUSER(?,?,?,?)}";

		try {
			dbConnection = getDBConnection();
			callableStatement = dbConnection.prepareCall(insertStoreProc);

			callableStatement.setInt(1, 1000);
			callableStatement.setString(2, "mkyong");
			callableStatement.setString(3, "system");
			callableStatement.setDate(4, getCurrentDate());

			// execute insertDBUSER store procedure
			callableStatement.executeUpdate();

			System.out.println("Record is inserted into DBUSER table!");

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		} finally {

			if (callableStatement != null) {
				callableStatement.close();
			}

			if (dbConnection != null) {
				dbConnection.close();
			}

		}

	}

	private static Connection getDBConnection() {

		Connection dbConnection = null;

		try {

			Class.forName(DB_DRIVER);

		} catch (ClassNotFoundException e) {

			System.out.println(e.getMessage());

		}

		try {

			dbConnection = DriverManager.getConnection(
				DB_CONNECTION, DB_USER,DB_PASSWORD);
			return dbConnection;

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		}

		return dbConnection;

	}

	private static java.sql.Date getCurrentDate() {
		java.util.Date today = new java.util.Date();
		return new java.sql.Date(today.getTime());
	}

} 

完成了。当执行上述 JDBC 示例时,将通过存储过程"insertDBUSER"向数据库中插入一条新记录。

参考

  1. http://download . Oracle . com/javase/6/docs/API/Java/SQL/callable statement . html
  2. http://docsrv . SCO . com/JDK _ guide/JDBC/getstart/callable statement . doc . html
  3. http://on Java . com/pub/a/on Java/2003/08/13/stored _ procedures . html

callablestatement jdbc store procedure

JDBC 可调用语句–存储过程输出参数示例

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/jdbc/jdbc-callablestatement-stored-procedure-out-parameter-example/

一个 JDBC CallableStatement例子来调用一个接受输入和输出参数的存储过程。

使用 Java 8 和 Oracle database 19c 进行测试

pom.xml

 <dependency>
		<groupId>com.oracle</groupId>
		<artifactId>ojdbc</artifactId>
		<version>8</version>
		<scope>system</scope>
		<systemPath>path.to/ojdbc8.jar</systemPath>
	</dependency> 

1.JDBC 可赎回声明

1.1 接受 IN 和 OUT 参数的 PL/SQL 存储过程。

 CREATE OR REPLACE PROCEDURE get_employee_by_id(
	   p_id IN EMPLOYEE.ID%TYPE,
       o_name OUT EMPLOYEE.NAME%TYPE,
	   o_salary OUT EMPLOYEE.SALARY%TYPE,
	   o_date OUT EMPLOYEE.CREATED_DATE%TYPE)
    AS
    BEGIN

    SELECT NAME , SALARY, CREATED_DATE INTO o_name, o_salary, o_date from EMPLOYEE WHERE ID = p_id;

    END; 

1.2 JDBC 调用上述存储过程的例子。

StoreProcedureOutParameter.java

 package com.mkyong.jdbc.callablestatement;

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

public class StoreProcedureOutParameter {

    public static void main(String[] args) {

        String createSP = "CREATE OR REPLACE PROCEDURE get_employee_by_id( "
                + " p_id IN EMPLOYEE.ID%TYPE, "
                + " o_name OUT EMPLOYEE.NAME%TYPE, "
                + " o_salary OUT EMPLOYEE.SALARY%TYPE, "
                + " o_date OUT EMPLOYEE.CREATED_DATE%TYPE) "
                + " AS "
                + " BEGIN "
                + "     SELECT NAME, SALARY, CREATED_DATE INTO o_name, o_salary, o_date from EMPLOYEE WHERE ID = p_id; "
                + " END;";

        String runSP = "{ call get_employee_by_id(?,?,?,?) }";

        try (Connection conn = DriverManager.getConnection(
                "jdbc:oracle:thin:@localhost:1521:orcl", "system", "Password123");
             Statement statement = conn.createStatement();
             CallableStatement callableStatement = conn.prepareCall(runSP)) {

            // create or replace stored procedure
            statement.execute(createSP);

            callableStatement.setInt(1, 3);

            callableStatement.registerOutParameter(2, java.sql.Types.VARCHAR);
            callableStatement.registerOutParameter(3, Types.DECIMAL);
            callableStatement.registerOutParameter(4, java.sql.Types.DATE);

            // run it
            callableStatement.executeUpdate();

            // java.sql.SQLException: operation not allowed: Ordinal binding and Named binding cannot be combined!
            /*String name = callableStatement.getString("NAME");
            BigDecimal salary = callableStatement.getBigDecimal("SALARY");
            Timestamp createdDate = callableStatement.getTimestamp("CREATED_DATE");*/

            String name = callableStatement.getString(2);
            BigDecimal salary = callableStatement.getBigDecimal(3);
            Timestamp createdDate = callableStatement.getTimestamp(4);

            System.out.println("name: " + name);
            System.out.println("salary: " + salary);
            System.out.println("createdDate: " + createdDate);

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

    }
} 

下载源代码

$ git clone https://github.com/mkyong/java-jdbc.git

参考

callablestatement jdbc oracle stored procedure

不再需要 JDBC Class.forName()

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/jdbc/jdbc-class-forname-is-no-longer-required/

自从 Java 1.6,JDBC 4.0 API,它提供了自动发现java.sql.Driver的新特性,这意味着不再需要Class.forName。只需将任何 JDBC 4.x 驱动程序放到项目类路径中,Java 就能够检测到它。

例如,PostgreSQL 的 JDBC 驱动程序:

pom.xml

 <dependency>
		<groupId>org.postgresql</groupId>
		<artifactId>postgresql</artifactId>
		<version>42.2.5</version>
	</dependency> 

这很有效:

 package com.mkyong.jdbc;

import java.sql.*;

public class JDBCExample {

    public static void main(String[] args) {

        try {

            // this is optional @since 1.6
            // Class.forName("org.postgresql.Driver");

            // auto close connection
            try (Connection conn =
                         DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/test",
                                 "postgres", "password")) {

                Statement statement = conn.createStatement();
                //...

            }

        } catch (Exception e) {
            System.err.println("Something went wrong!");
            e.printStackTrace();
        }

    }

} 

参考

JDBC——如何打印数据库中的所有表名?

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/jdbc/jdbc-how-to-print-all-table-names-from-a-database/

一个 JDBC 的例子,连接到一个 PostgreSQL,并打印出默认数据库中的所有表格postgres

pom.xml

 <dependencies>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.2.5</version>
        </dependency>
    </dependencies> 

P.S 用 Java 8 和 postgresql jdbc 驱动程序 42.2.5 测试

PrintAllTables.java

 package com.mkyong.jdbc;

import java.sql.*;

public class PrintAllTables {

    public static void main(String[] argv) {

        System.out.println("PostgreSQL JDBC Connection Testing ~");

        try {

            Class.forName("org.postgresql.Driver");

        } catch (ClassNotFoundException e) {
            System.err.println("Unable to find the PostgreSQL JDBC Driver!");
            e.printStackTrace();
            return;
        }

        // default database: postgres
        // JDK 7, auto close connection with try-with-resources
        try (Connection connection =
                     DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/postgres",
                             "postgres", "password")) {

            DatabaseMetaData metaData = connection.getMetaData();

            try (ResultSet rs = metaData.getTables(null, null, "%", null)) {

                ResultSetMetaData rsMeta = rs.getMetaData();
                int columnCount = rsMeta.getColumnCount();

                while (rs.next()) {

                    System.out.println("\n----------");
                    System.out.println(rs.getString("TABLE_NAME"));
                    System.out.println("----------");

                    for (int i = 1; i <= columnCount; i++) {
                        String columnName = rsMeta.getColumnName(i);
                        System.out.format("%s:%s\n", columnName, rs.getString(i));
                    }

                }
            }

        } catch (SQLException e) {
            System.err.println("Something went wrong!");
            e.printStackTrace();
            return;
        }

    }

} 

输出

 ----------
pg_aggregate_fnoid_index
----------
table_cat:null
table_schem:pg_catalog
table_name:pg_aggregate_fnoid_index
table_type:SYSTEM INDEX
remarks:null

----------
pg_am_name_index
----------
table_cat:null
table_schem:pg_catalog
table_name:pg_am_name_index
table_type:SYSTEM INDEX
remarks:null

----------
pg_am_oid_index
----------
table_cat:null
table_schem:pg_catalog
table_name:pg_am_oid_index
table_type:SYSTEM INDEX
remarks:null

----------
pg_amop_fam_strat_index
----------
table_cat:null
table_schem:pg_catalog
table_name:pg_amop_fam_strat_index
table_type:SYSTEM INDEX
remarks:null

----------
pg_amop_oid_index
----------
table_cat:null
table_schem:pg_catalog
table_name:pg_amop_oid_index
table_type:SYSTEM INDEX
remarks:null

----------
pg_amop_opr_fam_index
----------
table_cat:null
table_schem:pg_catalog
table_name:pg_amop_opr_fam_index
table_type:SYSTEM INDEX
remarks:null

//...

----------
pg_stat_progress_vacuum
----------
table_cat:null
table_schem:pg_catalog
table_name:pg_stat_progress_vacuum
table_type:SYSTEM VIEW
remarks:null

----------
pg_stat_replication
----------
table_cat:null
table_schem:pg_catalog
table_name:pg_stat_replication
table_type:SYSTEM VIEW
remarks:null

----------
pg_stat_ssl
----------
table_cat:null
table_schem:pg_catalog
table_name:pg_stat_ssl
table_type:SYSTEM VIEW
remarks:null

//... 

参考

JDBC 编制的报表-批量更新

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/jdbc/jdbc-preparedstatement-example-batch-update/

一个 JDBC PreparedStatement例子向数据库发送一批 SQL 命令(创建、插入、更新)。

BatchUpdate.java

 package com.mkyong.jdbc.preparestatement;

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

public class BatchUpdate {

    public static void main(String[] args) {

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

            // commit all or rollback all, if any errors
            conn.setAutoCommit(false); // default true

            psDDL.execute();

            // Run list of insert commands
            psInsert.setString(1, "mkyong");
            psInsert.setBigDecimal(2, new BigDecimal(10));
            psInsert.setTimestamp(3, Timestamp.valueOf(LocalDateTime.now()));
            psInsert.addBatch();

            psInsert.setString(1, "kungfu");
            psInsert.setBigDecimal(2, new BigDecimal(20));
            psInsert.setTimestamp(3, Timestamp.valueOf(LocalDateTime.now()));
            psInsert.addBatch();

            psInsert.setString(1, "james");
            psInsert.setBigDecimal(2, new BigDecimal(30));
            psInsert.setTimestamp(3, Timestamp.valueOf(LocalDateTime.now()));
            psInsert.addBatch();

            int[] rows = psInsert.executeBatch();

            System.out.println(Arrays.toString(rows));

            // Run list of update commands
            psUpdate.setBigDecimal(1, new BigDecimal(999.99));
            psUpdate.setString(2, "mkyong");
            psUpdate.addBatch();

            psUpdate.setBigDecimal(1, new BigDecimal(888.88));
            psUpdate.setString(2, "james");
            psUpdate.addBatch();

            int[] rows2 = psUpdate.executeBatch();

            System.out.println(Arrays.toString(rows2));

            conn.commit();

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

    }

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

    private static final String SQL_UPDATE = "UPDATE EMPLOYEE SET SALARY=? WHERE NAME=?";

    private static final String SQL_CREATE = "CREATE TABLE EMPLOYEE"
            + "("
            + " ID serial,"
            + " NAME varchar(100) NOT NULL,"
            + " SALARY numeric(15, 2) NOT NULL,"
            + " CREATED_DATE timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,"
            + " PRIMARY KEY (ID)"
            + ")";

} 

这个批处理示例使用了事务,如果出现错误,要么全部提交,要么全部回滚。

 conn.setAutoCommit(false);

	// SQL 

	conn.commit(); 

PS 用 PostgreSQL 11 和 Java 8 测试

pom.xml

 <dependency>
		<groupId>org.postgresql</groupId>
		<artifactId>postgresql</artifactId>
		<version>42.2.5</version>
	</dependency> 

下载源代码

$ git clone https://github.com/mkyong/java-jdbc.git

参考

JDBC 在条件中准备了 SQL 语句

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/jdbc/jdbc-preparedstatement-sql-in-condition/

Java JDBC PreparedStatement示例创建一个 SQL IN 条件。

1.PreparedStatement +数组

在 JDBC,我们可以在查询中使用createArrayOf创建一个PreparedStatement

 @Override
    public List<Integer> getPostIdByTagId(List<Integer> tagIds) {

        List<Integer> result = new ArrayList<>();

        String sql = "SELECT tr.object_id as post_id FROM wp_term_relationships tr " +
                " JOIN wp_term_taxonomy tt JOIN wp_terms t " +
                " ON tr.term_taxonomy_id = tt.term_taxonomy_id " +
                " AND tt.term_id = t.term_id " +
                " WHERE t.term_id IN (?) AND tt.taxonomy= 'post_tag'";

        try (Connection connection = dataSource.getConnection();
             PreparedStatement ps = connection.prepareStatement(sql)) {

            Array tagIdsInArray = connection.createArrayOf("integer", tagIds.toArray());
            ps.setArray(1, tagIdsInArray);

            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    result.add(rs.getInt("post_id"));
                }
            }

        } catch (SQLException e) {
            logger.error("Unknown error : {}", e);
        }

        return result;

    } 

但是,这种array型并不是标准的 JDBC 选项。如果我们用 MYSQL 运行这个,它将提示以下错误消息:

 java.sql.SQLFeatureNotSupportedException 

MySQL 不支持array类型,测试用

pom.xml

 <dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>5.1.47</version>
	</dependency> 

2 准备好的报表+连接

这个版本可以在 MySQL 和任何支持 SQL 的数据库中运行,不需要魔法,只需要手工加入和替换(?)

 @Override
    public List<Integer> getPostIdByTagId(List<Integer> tagIds) {

        List<Integer> result = new ArrayList<>();

        String sql = "SELECT tr.object_id as post_id FROM wp_term_relationships tr " +
                " JOIN wp_term_taxonomy tt JOIN wp_terms t " +
                " ON tr.term_taxonomy_id = tt.term_taxonomy_id " +
                " AND tt.term_id = t.term_id " +
                " WHERE t.term_id IN (?) AND tt.taxonomy= 'post_tag'";

        String sqlIN = tagIds.stream()
			.map(x -> String.valueOf(x))
			.collect(Collectors.joining(",", "(", ")"));

        sql = sql.replace("(?)", sqlIN);

        try (Connection connection = dataSource.getConnection();
             PreparedStatement ps = connection.prepareStatement(sql)) {

            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    result.add(rs.getInt("post_id"));
                }
            }

        } catch (SQLException e) {
            logger.error("Unknown error : {}", e);
        }

        return result;

    } 

参考

JDBC 准备报表示例-创建表格

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/jdbc/jdbc-preparestatement-example-create-a-table/

这里有一个例子来告诉你如何通过 JDBC PrepareStatement 在数据库中创建一个表。要发出 create 语句,调用PrepareStatement.executeUpdate()方法,如下所示:

 PreparedStatement preparedStatement = dbConnection.prepareStatement(createTableSQL);
// execute create SQL stetement
preparedStatement.executeUpdate(); 

完整示例…

 package com.mkyong.jdbc;

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JDBCPreparedStatementCreateExample {

	private static final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver";
	private static final String DB_CONNECTION = "jdbc:oracle:thin:@localhost:1521:MKYONG";
	private static final String DB_USER = "user";
	private static final String DB_PASSWORD = "password";

	public static void main(String[] argv) {

		try {

			createTable();

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		}

	}

	private static void createTable() throws SQLException {

		Connection dbConnection = null;
		PreparedStatement preparedStatement = null;

		String createTableSQL = "CREATE TABLE DBUSER1("
				+ "USER_ID NUMBER(5) NOT NULL, "
				+ "USERNAME VARCHAR(20) NOT NULL, "
				+ "CREATED_BY VARCHAR(20) NOT NULL, "
				+ "CREATED_DATE DATE NOT NULL, " + "PRIMARY KEY (USER_ID) "
				+ ")";

		try {
			dbConnection = getDBConnection();
			preparedStatement = dbConnection.prepareStatement(createTableSQL);

			System.out.println(createTableSQL);

			// execute create SQL stetement
			preparedStatement.executeUpdate();

			System.out.println("Table \"dbuser\" is created!");

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		} finally {

			if (preparedStatement != null) {
				preparedStatement.close();
			}

			if (dbConnection != null) {
				dbConnection.close();
			}

		}

	}

	private static Connection getDBConnection() {

		Connection dbConnection = null;

		try {

			Class.forName(DB_DRIVER);

		} catch (ClassNotFoundException e) {

			System.out.println(e.getMessage());

		}

		try {

			dbConnection = DriverManager.getConnection(
                            DB_CONNECTION, DB_USER,DB_PASSWORD);
			return dbConnection;

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		}

		return dbConnection;

	}

} 

结果

创建一个名为“DBUSER”的表。

 CREATE TABLE DBUSER(
   USER_ID NUMBER(5) NOT NULL, 
   USERNAME VARCHAR(20) NOT NULL, 
   CREATED_BY VARCHAR(20) NOT NULL, 
   CREATED_DATE DATE NOT NULL, 
   PRIMARY KEY (USER_ID) 
)
Table "dbuser" is created! 

create jdbc preparedstatement table (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190225101344/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

JDBC 编制报表示例-删除记录

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/jdbc/jdbc-preparestatement-example-delete-a-record/

这里有一个例子,向您展示如何通过 JDBC PreparedStatement 从表中删除记录。要发出 delete 语句,调用PreparedStatement.executeUpdate()方法,如下所示:

 String deleteSQL = "DELETE DBUSER WHERE USER_ID = ?";
PreparedStatement preparedStatement = dbConnection.prepareStatement(deleteSQL);
preparedStatement.setInt(1, 1001);
// execute delete SQL stetement
preparedStatement.executeUpdate(); 

完整示例…

 package com.mkyong.jdbc;

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JDBCPreparedStatementSelectExample {

	private static final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver";
	private static final String DB_CONNECTION = "jdbc:oracle:thin:@localhost:1521:MKYONG";
	private static final String DB_USER = "user";
	private static final String DB_PASSWORD = "password";

	public static void main(String[] argv) {

		try {

			deleteRecordFromTable();

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		}

	}

	private static void deleteRecordFromTable() throws SQLException {

		Connection dbConnection = null;
		PreparedStatement preparedStatement = null;

		String deleteSQL = "DELETE DBUSER WHERE USER_ID = ?";

		try {
			dbConnection = getDBConnection();
			preparedStatement = dbConnection.prepareStatement(deleteSQL);
			preparedStatement.setInt(1, 1001);

			// execute delete SQL stetement
			preparedStatement.executeUpdate();

			System.out.println("Record is deleted!");

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		} finally {

			if (preparedStatement != null) {
				preparedStatement.close();
			}

			if (dbConnection != null) {
				dbConnection.close();
			}

		}

	}

	private static Connection getDBConnection() {

		Connection dbConnection = null;

		try {

			Class.forName(DB_DRIVER);

		} catch (ClassNotFoundException e) {

			System.out.println(e.getMessage());

		}

		try {

			dbConnection = DriverManager.getConnection(
                            DB_CONNECTION, DB_USER,DB_PASSWORD);
			return dbConnection;

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		}

		return dbConnection;

	}

} 

结果

从表中删除“用户 id=1001”的记录。

delete jdbc preparestatement (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190223065002/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

JDBC 准备报表–插入一行

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/jdbc/jdbc-preparestatement-example-insert-a-record/

一个 JDBC PreparedStatement向数据库中插入一行的例子。

RowInsert.java

 package com.mkyong.jdbc.preparestatement.row;

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

public class RowInsert {

    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()));

            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();
        }

    }

} 

表定义。

 CREATE TABLE EMPLOYEE
(
    ID serial,
    NAME varchar(100) NOT NULL,
    SALARY numeric(15, 2) NOT NULL,
    CREATED_DATE timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP
    PRIMARY KEY (ID)
); 

PS 用 PostgreSQL 11 和 Java 8 测试

pom.xml

 <dependency>
		<groupId>org.postgresql</groupId>
		<artifactId>postgresql</artifactId>
		<version>42.2.5</version>
	</dependency> 

下载源代码

$ git clone https://github.com/mkyong/java-jdbc.git

参考

JDBC 准备报表–选择行列表

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/jdbc/jdbc-preparestatement-example-select-list-of-the-records/

一个从数据库中选择一列行的 JDBC PreparedStatement例子。

RowSelect.java

 package com.mkyong.jdbc.preparestatement.row;

import com.mkyong.jdbc.model.Employee;

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

public class RowSelect {

    private static final String SQL_SELECT = "SELECT * FROM EMPLOYEE";

    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_SELECT)) {

            ResultSet resultSet = preparedStatement.executeQuery();

            while (resultSet.next()) {

                long id = resultSet.getLong("ID");
                String name = resultSet.getString("NAME");
                BigDecimal salary = resultSet.getBigDecimal("SALARY");
                Timestamp createdDate = resultSet.getTimestamp("CREATED_DATE");

                Employee obj = new Employee();
                obj.setId(id);
                obj.setName(name);
                obj.setSalary(salary);
                // Timestamp -> LocalDateTime
                obj.setCreatedDate(createdDate.toLocalDateTime());

                System.out.println(obj);
            }

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

    }

} 

Employee.java

 package com.mkyong.jdbc.model;

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

public class Employee {

    private Long id;
    private String name;
    private BigDecimal salary;
    private LocalDateTime createdDate;

    //...
} 

表定义。

 CREATE TABLE EMPLOYEE
(
    ID serial,
    NAME varchar(100) NOT NULL,
    SALARY numeric(15, 2) NOT NULL,
    CREATED_DATE timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP
    PRIMARY KEY (ID)
); 

PS 用 PostgreSQL 11 和 Java 8 测试

pom.xml

 <dependency>
		<groupId>org.postgresql</groupId>
		<artifactId>postgresql</artifactId>
		<version>42.2.5</version>
	</dependency> 

下载源代码

$ git clone https://github.com/mkyong/java-jdbc.git

参考

Tags : jdbc preparedstatement select

JDBC 编制报表示例-更新记录

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/jdbc/jdbc-preparestatement-example-update-a-record/

这里有一个例子,向您展示如何通过 JDBC PreparedStatement 更新表中的记录。要发出更新语句,调用PreparedStatement.executeUpdate()方法,如下所示:

 String updateTableSQL = "UPDATE DBUSER SET USERNAME = ? WHERE USER_ID = ?";
PreparedStatement preparedStatement = dbConnection.prepareStatement(updateTableSQL);
preparedStatement.setString(1, "mkyong_new_value");
preparedStatement.setInt(2, 1001);
// execute insert SQL stetement
preparedStatement .executeUpdate(); 

完整示例…

 package com.mkyong.jdbc;

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JDBCPreparedStatementUpdateExample {

	private static final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver";
	private static final String DB_CONNECTION = "jdbc:oracle:thin:@localhost:1521:MKYONG";
	private static final String DB_USER = "user";
	private static final String DB_PASSWORD = "password";

	public static void main(String[] argv) {

		try {

			updateRecordToTable();

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		}

	}

	private static void updateRecordToTable() throws SQLException {

		Connection dbConnection = null;
		PreparedStatement preparedStatement = null;

		String updateTableSQL = "UPDATE DBUSER SET USERNAME = ? "
				                  + " WHERE USER_ID = ?";

		try {
			dbConnection = getDBConnection();
			preparedStatement = dbConnection.prepareStatement(updateTableSQL);

			preparedStatement.setString(1, "mkyong_new_value");
			preparedStatement.setInt(2, 1001);

			// execute update SQL stetement
			preparedStatement.executeUpdate();

			System.out.println("Record is updated to DBUSER table!");

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		} finally {

			if (preparedStatement != null) {
				preparedStatement.close();
			}

			if (dbConnection != null) {
				dbConnection.close();
			}

		}

	}

	private static Connection getDBConnection() {

		Connection dbConnection = null;

		try {

			Class.forName(DB_DRIVER);

		} catch (ClassNotFoundException e) {

			System.out.println(e.getMessage());

		}

		try {

			dbConnection = DriverManager.getConnection(
                            DB_CONNECTION, DB_USER,DB_PASSWORD);
			return dbConnection;

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		}

		return dbConnection;

	}

} 

结果

用户名“用户标识= 1001”被更新为新值“mkyong_new_value”。

jdbc preparedstatement update (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190223075356/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

JDBC 报表示例-批量更新

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/jdbc/jdbc-statement-example-batch-update/

这里有一个例子告诉你如何通过 JDBC Statement在批处理中插入几条记录。

 dbConnection.setAutoCommit(false);

statement = dbConnection.createStatement();
statement.addBatch(insertTableSQL1);
statement.addBatch(insertTableSQL2);
statement.addBatch(insertTableSQL3);

statement.executeBatch();

dbConnection.commit(); 

Note
Batch Update is not limit to Insert statement, it’s apply for Update and Delete statement as well.

参见完整的 JDBC 批量更新示例……

 package com.mkyong.jdbc;

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

public class JDBCBatchUpdateExample {

	private static final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver";
	private static final String DB_CONNECTION = "jdbc:oracle:thin:@localhost:1521:MKYONG";
	private static final String DB_USER = "user";
	private static final String DB_PASSWORD = "password";
	private static final DateFormat dateFormat = new SimpleDateFormat(
			"yyyy/MM/dd HH:mm:ss");

	public static void main(String[] argv) {

		try {

			batchInsertRecordsIntoTable();

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		}

	}

	private static void batchInsertRecordsIntoTable() throws SQLException {

		Connection dbConnection = null;
		Statement statement = null;

		String insertTableSQL1 = "INSERT INTO DBUSER"
				+ "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) " + "VALUES"
				+ "(101,'mkyong','system', " + "to_date('"
				+ getCurrentTimeStamp() + "', 'yyyy/mm/dd hh24:mi:ss'))";

		String insertTableSQL2 = "INSERT INTO DBUSER"
				+ "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) " + "VALUES"
				+ "(102,'mkyong','system', " + "to_date('"
				+ getCurrentTimeStamp() + "', 'yyyy/mm/dd hh24:mi:ss'))";

		String insertTableSQL3 = "INSERT INTO DBUSER"
				+ "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) " + "VALUES"
				+ "(103,'mkyong','system', " + "to_date('"
				+ getCurrentTimeStamp() + "', 'yyyy/mm/dd hh24:mi:ss'))";

		try {
			dbConnection = getDBConnection();
			statement = dbConnection.createStatement();

			dbConnection.setAutoCommit(false);

			statement.addBatch(insertTableSQL1);
			statement.addBatch(insertTableSQL2);
			statement.addBatch(insertTableSQL3);

			statement.executeBatch();

			dbConnection.commit();

			System.out.println("Records are inserted into DBUSER table!");

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		} finally {

			if (statement != null) {
				statement.close();
			}

			if (dbConnection != null) {
				dbConnection.close();
			}

		}

	}

	private static Connection getDBConnection() {

		Connection dbConnection = null;

		try {

			Class.forName(DB_DRIVER);

		} catch (ClassNotFoundException e) {

			System.out.println(e.getMessage());

		}

		try {

			dbConnection = DriverManager.getConnection(
				DB_CONNECTION, DB_USER,DB_PASSWORD);
			return dbConnection;

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		}

		return dbConnection;

	}

	private static String getCurrentTimeStamp() {

		java.util.Date today = new java.util.Date();
		return dateFormat.format(today.getTime());

	}

} 

结果

通过批量更新过程将 3 条记录插入数据库。

为什么需要使用批量更新?

上述批量更新与正常的executeUpdate()方法相同,如下所示:

 statement.executeUpdate(insertTableSQL1);
statement.executeUpdate(insertTableSQL2);
statement.executeUpdate(insertTableSQL3); 

但是如果您想要插入许多记录,批量更新有性能优势,因为executeBatch()减少了 JDBC 调用数据库的次数。

batch update jdbc statement (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190223082432/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

JDBC 语句示例–创建表格

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/jdbc/jdbc-statement-example-create-a-table/

这里有一个例子向你展示如何通过 JDBC 语句在数据库中创建一个表。要发出 create 语句,调用 S tatement.execute()方法,如下所示:

 Statement statement = dbConnection.createStatement();
// execute create SQL stetement
statement.execute(createTableSQL); 

完整示例…

 package com.mkyong.jdbc;

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCStatementCreateExample {

	private static final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver";
	private static final String DB_CONNECTION = "jdbc:oracle:thin:@localhost:1521:MKYONG";
	private static final String DB_USER = "user";
	private static final String DB_PASSWORD = "password";

	public static void main(String[] argv) {

		try {

			createDbUserTable();

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		}

	}

	private static void createDbUserTable() throws SQLException {

		Connection dbConnection = null;
		Statement statement = null;

		String createTableSQL = "CREATE TABLE DBUSER("
				+ "USER_ID NUMBER(5) NOT NULL, "
				+ "USERNAME VARCHAR(20) NOT NULL, "
				+ "CREATED_BY VARCHAR(20) NOT NULL, "
				+ "CREATED_DATE DATE NOT NULL, " + "PRIMARY KEY (USER_ID) "
				+ ")";

		try {
			dbConnection = getDBConnection();
			statement = dbConnection.createStatement();

			System.out.println(createTableSQL);
                        // execute the SQL stetement
			statement.execute(createTableSQL);

			System.out.println("Table \"dbuser\" is created!");

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		} finally {

			if (statement != null) {
				statement.close();
			}

			if (dbConnection != null) {
				dbConnection.close();
			}

		}

	}

	private static Connection getDBConnection() {

		Connection dbConnection = null;

		try {

			Class.forName(DB_DRIVER);

		} catch (ClassNotFoundException e) {

			System.out.println(e.getMessage());

		}

		try {

			dbConnection = DriverManager.getConnection(
					DB_CONNECTION, DB_USER,DB_PASSWORD);
			return dbConnection;

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		}

		return dbConnection;

	}

} 

结果

这是结果。

 CREATE TABLE DBUSER(
  USER_ID NUMBER(5) NOT NULL, 
  USERNAME VARCHAR(20) NOT NULL, 
  CREATED_BY VARCHAR(20) NOT NULL, 
  CREATED_DATE DATE NOT NULL, 
  PRIMARY KEY (USER_ID) 
)
Table "user" is created! 

create jdbc statement table (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190223082437/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

JDBC 语句示例-删除记录

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/jdbc/jdbc-statement-example-delete-a-record/

下面的例子展示了如何通过 JDBC 语句从表中删除记录。要发出 delete 语句,调用Statement.executeUpdate()方法,如下所示:

 Statement statement = dbConnection.createStatement();
// execute the delete SQL stetement
statement.executeUpdate(deleteTableSQL); 

完整示例…

 package com.mkyong.jdbc;

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCStatementDeleteExample {

	private static final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver";
	private static final String DB_CONNECTION = "jdbc:oracle:thin:@localhost:1521:MKYONG";
	private static final String DB_USER = "user";
	private static final String DB_PASSWORD = "password";

	public static void main(String[] argv) {

		try {

			deleteRecordFromDbUserTable();

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		}

	}

	private static void deleteRecordFromDbUserTable() throws SQLException {

		Connection dbConnection = null;
		Statement statement = null;

		String deleteTableSQL = "DELETE DBUSER WHERE USER_ID = 1";

		try {
			dbConnection = getDBConnection();
			statement = dbConnection.createStatement();

			System.out.println(deleteTableSQL);

			// execute delete SQL stetement
			statement.execute(deleteTableSQL);

			System.out.println("Record is deleted from DBUSER table!");

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		} finally {

			if (statement != null) {
				statement.close();
			}

			if (dbConnection != null) {
				dbConnection.close();
			}

		}

	}

	private static Connection getDBConnection() {

		Connection dbConnection = null;

		try {

			Class.forName(DB_DRIVER);

		} catch (ClassNotFoundException e) {

			System.out.println(e.getMessage());

		}

		try {

			dbConnection = DriverManager.getConnection(
                             DB_CONNECTION, DB_USER,DB_PASSWORD);
			return dbConnection;

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		}

		return dbConnection;

	}

} 

结果

从表中删除“用户标识=1”的记录。

 DELETE DBUSER WHERE USER_ID = 1
Record is deleted from DBUSER table! 

delete jdbc statement (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190224154912/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

JDBC 声明示例-插入一条记录

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/jdbc/jdbc-statement-example-insert-a-record/

下面的例子展示了如何通过 JDBC 语句向表中插入记录。要发出 insert 语句,调用Statement.executeUpdate()方法,如下所示:

 Statement statement = dbConnection.createStatement();
// execute the insert SQL stetement
statement.executeUpdate(insertTableSQL); 

完整示例…

 package com.mkyong.jdbc;

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

public class JDBCStatementInsertExample {

	private static final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver";
	private static final String DB_CONNECTION = "jdbc:oracle:thin:@localhost:1521:MKYONG";
	private static final String DB_USER = "user";
	private static final String DB_PASSWORD = "password";
	private static final DateFormat dateFormat = new SimpleDateFormat(
			"yyyy/MM/dd HH:mm:ss");

	public static void main(String[] argv) {

		try {

			insertRecordIntoDbUserTable();

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		}

	}

	private static void insertRecordIntoDbUserTable() throws SQLException {

		Connection dbConnection = null;
		Statement statement = null;

		String insertTableSQL = "INSERT INTO DBUSER"
				+ "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) " + "VALUES"
				+ "(1,'mkyong','system', " + "to_date('"
				+ getCurrentTimeStamp() + "', 'yyyy/mm/dd hh24:mi:ss'))";

		try {
			dbConnection = getDBConnection();
			statement = dbConnection.createStatement();

			System.out.println(insertTableSQL);

			// execute insert SQL stetement
			statement.executeUpdate(insertTableSQL);

			System.out.println("Record is inserted into DBUSER table!");

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		} finally {

			if (statement != null) {
				statement.close();
			}

			if (dbConnection != null) {
				dbConnection.close();
			}

		}

	}

	private static Connection getDBConnection() {

		Connection dbConnection = null;

		try {

			Class.forName(DB_DRIVER);

		} catch (ClassNotFoundException e) {

			System.out.println(e.getMessage());

		}

		try {

			dbConnection = DriverManager.getConnection(
                               DB_CONNECTION, DB_USER,DB_PASSWORD);
			return dbConnection;

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		}

		return dbConnection;

	}

	private static String getCurrentTimeStamp() {

		java.util.Date today = new java.util.Date();
		return dateFormat.format(today.getTime());

	}

} 

结果

一条记录被插入到名为“DBUSER”的表中。

 INSERT INTO DBUSER(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) 
VALUES(1,'mkyong','system', to_date('2011/04/04 13:59:03', 'yyyy/mm/dd hh24:mi:ss'))
Record is inserted into DBUSER table! 

insert jdbc statement (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190214232530/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

JDBC 语句示例–选择记录列表

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/jdbc/jdbc-statement-example-select-list-of-the-records/

下面的例子展示了如何通过 JDBC 语句从表中选择全部记录,并通过 ResultSet 对象显示所有记录。要发出选择查询,调用Statement.executeQuery方法,如下所示:

 String selectTableSQL = "SELECT USER_ID, USERNAME from DBUSER";
Statement statement = dbConnection.createStatement();
ResultSet rs = statement.executeQuery(selectTableSQL);
while (rs.next()) {
	String userid = rs.getString("USER_ID");
	String username = rs.getString("USERNAME");	
} 

完整示例……

 package com.mkyong.jdbc;

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCStatementSelectExample {

	private static final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver";
	private static final String DB_CONNECTION = "jdbc:oracle:thin:@localhost:1521:MKYONG";
	private static final String DB_USER = "user";
	private static final String DB_PASSWORD = "password";

	public static void main(String[] argv) {

		try {

			selectRecordsFromDbUserTable();

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		}

	}

	private static void selectRecordsFromDbUserTable() throws SQLException {

		Connection dbConnection = null;
		Statement statement = null;

		String selectTableSQL = "SELECT USER_ID, USERNAME from DBUSER";

		try {
			dbConnection = getDBConnection();
			statement = dbConnection.createStatement();

			System.out.println(selectTableSQL);

			// execute select SQL stetement
			ResultSet rs = statement.executeQuery(selectTableSQL);

			while (rs.next()) {

				String userid = rs.getString("USER_ID");
				String username = rs.getString("USERNAME");

				System.out.println("userid : " + userid);
				System.out.println("username : " + username);

			}

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		} finally {

			if (statement != null) {
				statement.close();
			}

			if (dbConnection != null) {
				dbConnection.close();
			}

		}

	}

	private static Connection getDBConnection() {

		Connection dbConnection = null;

		try {

			Class.forName(DB_DRIVER);

		} catch (ClassNotFoundException e) {

			System.out.println(e.getMessage());

		}

		try {

			dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER,
					DB_PASSWORD);
			return dbConnection;

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		}

		return dbConnection;

	}

} 

结果

从表“DBUSER”中检索并显示记录列表。

jdbc select statement (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190214234159/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

JDBC 报表示例-更新记录

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/jdbc/jdbc-statement-example-update-a-record/

下面的例子展示了如何通过 JDBC 语句更新表中的记录。要发出更新语句,调用Statement.executeUpdate()方法,如下所示:

 Statement statement = dbConnection.createStatement();
// execute the update SQL stetement
statement.executeUpdate(updateTableSQL); 

完整示例…

 package com.mkyong.jdbc;

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCStatementUpdateExample {

	private static final String DB_DRIVER = "oracle.jdbc.driver.OracleDriver";
	private static final String DB_CONNECTION = "jdbc:oracle:thin:@localhost:1521:MKYONG";
	private static final String DB_USER = "user";
	private static final String DB_PASSWORD = "password";

	public static void main(String[] argv) {

		try {

			updateRecordIntoDbUserTable();

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		}

	}

	private static void updateRecordIntoDbUserTable() throws SQLException {

		Connection dbConnection = null;
		Statement statement = null;

		String updateTableSQL = "UPDATE DBUSER"
				+ " SET USERNAME = 'mkyong_new' "
				+ " WHERE USER_ID = 1";

		try {
			dbConnection = getDBConnection();
			statement = dbConnection.createStatement();

			System.out.println(updateTableSQL);

			// execute update SQL stetement
			statement.execute(updateTableSQL);

			System.out.println("Record is updated to DBUSER table!");

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		} finally {

			if (statement != null) {
				statement.close();
			}

			if (dbConnection != null) {
				dbConnection.close();
			}

		}

	}

	private static Connection getDBConnection() {

		Connection dbConnection = null;

		try {

			Class.forName(DB_DRIVER);

		} catch (ClassNotFoundException e) {

			System.out.println(e.getMessage());

		}

		try {

			dbConnection = DriverManager.getConnection(
                              DB_CONNECTION, DB_USER,DB_PASSWORD);
			return dbConnection;

		} catch (SQLException e) {

			System.out.println(e.getMessage());

		}

		return dbConnection;

	}

} 

结果

用户名“用户标识= 1”被更新为新值“mkyong_new”。

 UPDATE DBUSER SET USERNAME = 'mkyong_new'  WHERE USER_ID = 1
Record is updated into DBUSER table! 

jdbc statement update (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190306165036/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

JDBC 交易示例

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/jdbc/jdbc-transaction-example/

JDBC 事务确保一组 SQL 语句作为一个单元执行,要么成功执行所有语句,要么不执行任何语句(回滚所有更改)。

1.没有 JDBC 交易

1.1 插入两行并更新一行的 JDBC 示例。

TransactionExample.java

 package com.mkyong.jdbc;

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

public class TransactionExample {

    public static void main(String[] args) {

        try (Connection conn = DriverManager.getConnection(
                "jdbc:postgresql://127.0.0.1:5432/test", "postgres", "password");
             Statement statement = conn.createStatement();
             PreparedStatement psInsert = conn.prepareStatement(SQL_INSERT);
             PreparedStatement psUpdate = conn.prepareStatement(SQL_UPDATE)) {

            statement.execute(SQL_TABLE_DROP);
            statement.execute(SQL_TABLE_CREATE);

            // Run list of insert commands
            psInsert.setString(1, "mkyong");
            psInsert.setBigDecimal(2, new BigDecimal(10));
            psInsert.setTimestamp(3, Timestamp.valueOf(LocalDateTime.now()));
            psInsert.execute();

            psInsert.setString(1, "kungfu");
            psInsert.setBigDecimal(2, new BigDecimal(20));
            psInsert.setTimestamp(3, Timestamp.valueOf(LocalDateTime.now()));
            psInsert.execute();

            // Run list of update commands

            // below line caused error, test transaction
            // org.postgresql.util.PSQLException: No value specified for parameter 1.
            psUpdate.setBigDecimal(2, new BigDecimal(999.99));

			//psUpdate.setBigDecimal(1, new BigDecimal(999.99));
            psUpdate.setString(2, "mkyong");
            psUpdate.execute();

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

    }

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

    private static final String SQL_UPDATE = "UPDATE EMPLOYEE SET SALARY=? WHERE NAME=?";

    private static final String SQL_TABLE_CREATE = "CREATE TABLE EMPLOYEE"
            + "("
            + " ID serial,"
            + " NAME varchar(100) NOT NULL,"
            + " SALARY numeric(15, 2) NOT NULL,"
            + " CREATED_DATE timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,"
            + " PRIMARY KEY (ID)"
            + ")";

    private static final String SQL_TABLE_DROP = "DROP TABLE EMPLOYEE";

} 

输出,更新失败,并抛出一个异常,最后,插入 2 行,但更新被跳过。

 org.postgresql.util.PSQLException: No value specified for parameter 1.
	at org.postgresql.core.v3.SimpleParameterList.checkAllParametersSet(SimpleParameterList.java:257)
	at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:292)
	at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:441)
	at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:365)
	at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:143)
	at org.postgresql.jdbc.PgPreparedStatement.execute(PgPreparedStatement.java:132)
	at com.mkyong.jdbc.TransactionExample.main(TransactionExample.java:41) 

output

2.使用 JDBC 交易

2.1 要启用事务,请将自动提交设置为 false。

 conn.setAutoCommit(false); // default true
// start transaction block

// insert
// update 
// if any errors within the start and end block, 
// rolled back all changes, none of the statements are executed.

// end transaction block
conn.commit(); 

2.2 JDBC 交易的例子相同。

TransactionExample.java

 package com.mkyong.jdbc;

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

public class TransactionExample {

    public static void main(String[] args) {

        try (Connection conn = DriverManager.getConnection(
                "jdbc:postgresql://127.0.0.1:5432/test", "postgres", "password");
             Statement statement = conn.createStatement();
             PreparedStatement psInsert = conn.prepareStatement(SQL_INSERT);
             PreparedStatement psUpdate = conn.prepareStatement(SQL_UPDATE)) {

            statement.execute(SQL_TABLE_DROP);
            statement.execute(SQL_TABLE_CREATE);

            // start transaction block
            conn.setAutoCommit(false); // default true

            // Run list of insert commands
            psInsert.setString(1, "mkyong");
            psInsert.setBigDecimal(2, new BigDecimal(10));
            psInsert.setTimestamp(3, Timestamp.valueOf(LocalDateTime.now()));
            psInsert.execute();

            psInsert.setString(1, "kungfu");
            psInsert.setBigDecimal(2, new BigDecimal(20));
            psInsert.setTimestamp(3, Timestamp.valueOf(LocalDateTime.now()));
            psInsert.execute();

            // Run list of update commands

            // error, test roolback
            // org.postgresql.util.PSQLException: No value specified for parameter 1.
            psUpdate.setBigDecimal(2, new BigDecimal(999.99));
            //psUpdate.setBigDecimal(1, new BigDecimal(999.99));
            psUpdate.setString(2, "mkyong");
            psUpdate.execute();

            // end transaction block, commit changes
            conn.commit();

            // good practice to set it back to default true
            conn.setAutoCommit(true);

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

    }

    //...

} 

输出,则不执行任何语句,insert 语句将回滚。

 org.postgresql.util.PSQLException: No value specified for parameter 1.
	at org.postgresql.core.v3.SimpleParameterList.checkAllParametersSet(SimpleParameterList.java:257)
	at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:292)
	at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:441)
	at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:365)
	at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:143)
	at org.postgresql.jdbc.PgPreparedStatement.execute(PgPreparedStatement.java:132)
	at com.mkyong.jdbc.TransactionExample.main(TransactionExample.java:41) 

output

3.额外…

修复parameter 1错误并查看预期结果。

 //psUpdate.setBigDecimal(2, new BigDecimal(999.99));

	psUpdate.setBigDecimal(1, new BigDecimal(999.99));
	psUpdate.setString(2, "mkyong");
	psUpdate.execute(); 

输出

 2 rows are inserted and 1 row is updated. 

output

下载源代码

$ git clone https://github.com/mkyong/java-jdbc.git
$ cd postgresql

参考

Tags : jdbc postgresql transaction

Java JDBC 教程

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/tutorials/jdbc-tutorials/

jdbc logo

Java 数据库连接(JDBC) API 使 Java 应用程序能够与数据库进行交互。

1.入门指南

2.声明

这个Statement没有缓存,适用于简单和静态的 SQL 语句,比如 CREATE 或 DROP。在Statement中,我们在 SQL 中构造条件或参数的方式容易出现 SQL 注入,记住要避开引号和特殊字符。

  • statement.execute(sql)–通常用于 DDL,如创建或删除
  • statement.executeUpdate(sql)–通常用于 DML,如插入、更新、删除
  • statement.executeQuery(sql)–运行选择查询并返回一个ResultSet
  • statement.executeBatch()–批量运行 SQL 命令

文章:

3.准备报表

PreparedStatement扩展了Statement,通过预编译和缓存 SQL 语句来提供更好的性能,适用于需要多次执行的 SQL 语句。此外,它提供了许多setXxx()来通过转义引号和特殊字符来保护 SQL 注入。

  • preparedStatement.execute()–通常用于 DDL,如创建或删除
  • preparedStatement.executeUpdate()–通常用于 DML,如插入、更新、删除
  • preparedStatement.executeQuery()–运行选择查询并返回一个ResultSet
  • preparedStatement.executeBatch()–批量运行 SQL 命令

文章:

4.可调用语句

CallableStatement扩展了PreparedStatement,用于执行数据库中的存储过程或函数。

  • conn.prepareCall(sql)

甲骨文数据库

PostgreSQL

5.交易

 conn.setAutoCommit(false); // default true
// start transaction block

// SQL statements

// end transaction block
conn.commit();
conn.setAutoCommit(true); 

6.Spring JDBC 数据库访问

JdbcTemplate例子。

常见问题

参考

甲骨文

MySQL 的实现

PostgreSQL

在 BeanExpressionContext 类型的对象上找不到 jobParameters

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/spring-batch/jobparameters-cannot-be-found-on-object-of-type-beanexpressioncontext/

创建一个简单的 Spring 批处理作业,将数据写入 csv 文件。csv 文件名取决于作业参数的传递,由 Spring EL 解释。

job-sample.xml

 <bean id="csvFileItemWriter" class="org.springframework.batch.item.file.FlatFileItemWriter">

  <!-- write to this csv file -->
  <property name="resource" 
      value="file:outputs/csv/domain.done.#{jobParameters['pid']}.csv" />

  <property name="appendAllowed" value="false" />
  <property name="lineAggregator">
      <bean
	class="org.springframework.batch.item.file.transform.DelimitedLineAggregator">
	<property name="delimiter" value="," />
	<property name="fieldExtractor">
	    <bean class="org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor">
		<property name="names" value="id, domainName" />
	    </bean>
	</property>
      </bean>
  </property>
</bean> 

作业上方的单元测试:

 public class TestSampleJob extends AbstractTestNGSpringContextTests {

    @Autowired
    private JobLauncherTestUtils jobLauncherTestUtils;

    @Test
    public void launchJob() throws Exception {

    	JobParameters jobParameters = 
    	    new JobParametersBuilder().addString("pid", "10").toJobParameters();

        JobExecution jobExecution = jobLauncherTestUtils.launchJob(jobParameters);
        Assert.assertEquals(jobExecution.getStatus(), BatchStatus.COMPLETED);

    }
} 

问题

它会提示“找不到作业参数”错误消息:

 Caused by: org.springframework.expression.spel.SpelEvaluationException: 
	EL1008E:(pos 0): Field or property 'jobParameters' cannot be found on object 
	of type 'org.springframework.beans.factory.config.BeanExpressionContext'
	at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:208)
	at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:72)
	at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:52) 

解决办法

在“步骤”开始之前,jobParameters bean 实际上不能被实例化。要修复它,需要使用范围为“Step”的后期绑定。

job-sample.xml

 <bean id="csvFileItemWriter" 
	class="org.springframework.batch.item.file.FlatFileItemWriter" scope="step">
	<!-- ...... -->
  </bean> 

参考

  1. 春季批量-步骤范围

spring batch

jQuery–访问受限 URI 被拒绝–解决方案

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-access-to-restricted-uri-denied-solution/

问题

这个 jQuery 错误消息是由加载跨域内容引起的。

 Error: [Exception... "Access to restricted URI denied"  
code: "1012" nsresult: "0x805303f4 (NS_ERROR_DOM_BAD_URI)" 

这意味着你正在加载一些不属于或不在你的网站上的内容(不同的域名)。参见这个 jQuery 例子,按需加载跨域(yahoo.com)内容。

 <html>
<head>

<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<style type="text/css">
	#content{
		border:1px solid blue;
		margin:16px;
		padding:16px;
	}
</style>

</head>
<body>
  <div id="msg"></div>

  <div id="content">
  </div>

  <br/>
  <button id="load">Load yahoo.com</button>

<script type="text/javascript">

$('#load').click(function(){
	$('#msg').text("Loading......");
	$('#content').load("http://www.yahoo.com", function() {
 		$('#msg').text("");
	});
});

</script>

</body>
</html> 

然而,这不起作用,当你点击“加载”按钮时,它什么也不做,只是提示一个“访问受限 URI 被拒绝”的错误信息。由于 JavaScript 安全限制,严格不允许跨域加载内容

解决办法

这里有一个肮脏的解决方法——用服务器端语言获取跨域内容。例如,创建一个名为“proxy.php”的单行 php 文件。

proxy.php

 <?php echo file_get_contents($_GET['url']);?> 

在 jQuery 端,将 load 函数改为

 $('#load').click(function(){
	$('#msg').text("Loading......");
	$('#content').load("proxy.php?url=http://www.yahoo.com", function() {
 		$('#msg').text("");
	});
});
</script> 

Try Demo

现在,当你点击“加载”按钮,它会加载跨域(yahoo.com)的内容到你的网页上点播。

jquery uri (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190225225008/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

jQuery–相邻兄弟选择器示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-adjacent-sibling-selector-example/

jQuery 相邻兄弟选择器(X + Y) 用于选择与“X”元素的兄弟元素“Y”匹配的紧接着的或下一个元素。

举个例子,

 <div class="class1"></div>
<p>I'm class1 sibling #1</p>
<p>I'm class1 sibling #2</p>
<p>I'm class1 sibling #3</p> 

是兄弟姐妹关系。“ $(.class1 + p) ”语句将只选择值为“ I'm class1 sibling #1 ”的< p >元素,其余的< p >元素将被忽略。

jQuery 示例

在这个例子中,只有值为"I ' m form siblings # 1–DIV"的

标签将被匹配,因为它是表单>元素<的紧接其后的或下一个兄弟。

 <html>
<head>
<title>jQuery adjacent sibling selector example</title>

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

 <style type="text/css">
  div { padding:8px 0px 8px 8px; }
 </style>

</head>

<script type="text/javascript">

$(document).ready(function(){

	$("form + div").css("border", "2px solid red");

});

</script>
<body>

<h1>jQuery adjacent sibling selector example</h1>

<form>

	<label>TextBox 1 (Child) : </label><input name="textbox1">

	<div class="level1">
		<label>TextBox 2 (GrandChild) : </label><input name="textbox2">
	</div>

	<div class="level1">
	   <div class="level2">
	    <label>TextBox 3 (Great GrandChild) : </label><input name="textbox3">
	   </div>
	</div>

	<label>TextBox 4 (Child) : </label><input name="textbox4">

</form>

<div> I'm form siblings #1 - DIV</div>

<p> I'm form siblings #2 - P </p>

<div> I'm form siblings #3 - DIV </div>

<p> I'm form siblings #4 - P </p>

</body>
</html> 

http://web.archive.org/web/20190224162730if_/http://www.mkyong.com/wp-content/uploads/jQuery/jQuery-adjacent-sibling-selector.html

Try Demojquery jquery selector (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190224162730/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

jQuery after()和 insertAfter()示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-after-and-insertafter-example/

jQuery after()insertAfter() 方法都在执行相同的任务,在匹配的元素后添加文本或 html 内容。主要的区别在于语法。

举个例子,

 <div class="greyBox">I'm a ipman</div>
<div class="greyBox">I'm a ipman 2</div> 

1.$('选择器')。后('新内容');

 $('.greyBox').after("<div class='redBox'>Iron man</div>"); 

2.$('新内容')。insertAfter(“选择器”);

 $("<div class='redBox'>Iron man</div>").insertAfter('.greyBox'); 

结果

以上两种方法做的是同样的任务,但是语法不同,在()或 insertAfter() 之后的新内容将变成

 <div class="greyBox">
   I'm a ipman
</div>
<div class='redBox'>Iron man</div>

<div class="greyBox">
   I'm a ipman 2
</div>
<div class='redBox'>Iron man</div> 

你自己试试

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

<style type="text/css">
	.greyBox{
		padding:8px;
		background: grey;
		margin-bottom:8px;
		width:300px;
		height:100px;
	}
	.redBox{
		padding:8px;
		background: red;
		margin-bottom:8px;
		width:200px;
		height:50px;
	}
</style>

</head>
<body>
  <h1>jQuery after() and insertAfter() example</h1>

  <div class="greyBox">Ip man</div>

  <div class="greyBox">Ip man 2</div>

  <p>
  <button id="after">after()</button>
  <button id="insertAfter">insertAfter()</button>
  <button id="reset">reset</button>
  </p>

<script type="text/javascript">

    $("#after").click(function () {

	  $('.greyBox').after("<div class='redBox'>Iron man</div>");

    });

	$("#insertAfter").click(function () {

	  $("<div class='redBox'>Iron man</div>").insertAfter('.greyBox');

    });

	$("#reset").click(function () {
	  location.reload();
    });

</script>
</body>
</html> 

http://web.archive.org/web/20220826132030if_/https://www.mkyong.com/wp-content/uploads/jQuery/jQuery-after-insertAfter-example.html

Try Demo

jQuery append()和 appendTo()示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-append-and-appendto-example/

jQuery append()appendTo() 方法都在执行相同的任务,在匹配元素的内容之后添加一个文本或 html 内容。主要的区别在于语法。

举个例子,

 <div class="box">I'm a big box</div>
<div class="box">I'm a big box 2</div> 

1.$('选择器')。append(“新文本”);

 $('.box').append("<div class='newbox'>I'm new box by prepend</div>"); 

2.$('新文本')。appendTo(' selector ');

 $("<div class='newbox'>I'm new box by appendTo</div>").appendTo('.box'); 

结果

以上两种方法做的是同样的任务,但是语法不同, append()appendTo() 之后的新内容将变成

 <div class="box">
   I'm a big box
   <div class='newbox'>I'm new box by prepend</div>
</div>

<div class="box">
   I'm a big box 2
   <div class='newbox'>I'm new box by prepend</div>
</div> 

你自己试试

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

<style type="text/css">
	.box{
		padding:8px;
		border:1px solid blue;
		margin-bottom:8px;
		width:300px;
		height:100px;
	}
	.newbox{
		padding:8px;
		border:1px solid red;
		margin-bottom:8px;
		width:200px;
		height:50px;
	}
</style>

</head>
<body>
  <h1>jQuery append() and appendTo example</h1>

  <div class="box">I'm a big box</div>

  <div class="box">I'm a big box 2</div>

  <p>
  <button id="append">append()</button>
  <button id="appendTo">appendTo()</button>
  <button id="reset">reset</button>
  </p>

<script type="text/javascript">

    $("#append").click(function () {

	  $('.box').append("<div class='newbox'>I'm new box by append</div>");

    });

	$("#appendTo").click(function () {

	  $("<div class='newbox'>I'm new box by appendTo</div>").appendTo('.box');

    });

	$("#reset").click(function () {
	  location.reload();
    });

</script>
</body>
</html> 

http://web.archive.org/web/20220826132030if_/https://www.mkyong.com/wp-content/uploads/jQuery/jQuery-append-appendTo-example.html

Try Demo

jQuery–属性选择器示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-attribute-selector-examples/

在 jQuery 中,属性选择器包含在方括号[]中。以下是支持的属性选择器:

1.具有属性[A]

选择所有具有“A”属性的元素。

示例
$(' a[rel]')–选择与具有 rel 属性的< a >匹配的所有元素。

2.属性值等于[A=B]

选择 A 属性的值恰好等于 b 的所有元素。

示例
$(' a[rel = nofollow]')–选择与< a >匹配的所有元素,这些元素的 rel 属性值正好等于' no follow '。

3.属性值不等于[A!=B]

选择所有不具有值正好等于 b 的 A 属性的元素。

例句
$('a[rel!= nofollow]')–选择与< a >匹配的所有元素,这些元素没有值正好等于“no follow”的 rel 属性。

4.属性值以[A^=B]开头

选择所有 A 属性的值以 b 开头的元素。

示例
$('a[rel^=nof]')–选择与< a >匹配的所有元素,这些元素的 rel 属性的值以“nof”开头。

5.属性值结束[A$=B]

选择所有具有 A 属性且值以 b 结尾的元素。

示例
$(' a[rel $ = low]')–选择与< a >匹配的所有元素,这些元素的 rel 属性值以' low '结尾。

6.属性值包含[A*=B]

选择所有具有 A 属性的元素,该属性的值包含子字符串 b。

示例
$(' a[href * = yahoo.com]')–选择与< a >匹配的所有元素,这些元素的 href 属性值包含' Yahoo . com '。

7.属性值包含前缀[A|=B]

选择 A 属性值等于 B 或以 B 开头后跟连字符(-)的所有元素。

示例
$(' a[lang | = en]')–选择与< a >匹配的所有元素,这些元素的阿郎属性值等于' en '或' en-'。

8.属性值包含–由空格[A~=B]分隔

选择所有 A 属性的值等于 B 并以空格分隔的元素。

示例
$(' div[class ~ = jQuery]')–选择与< div >匹配的所有元素,这些元素的 class 属性值等于' jQuery ',用空格分隔。例如,“HellojQuery”匹配,“Hello-jQuery”和“Hello jQuery”不匹配。

播放它

点击按钮来玩属性选择器。

 <html>
<head>
<title>jQuery attribute selector example</title>

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

<style type="text/css">
	div, a{
		padding:16px;
	}

	#msg{
		padding:8px;
		hright:100px;
	}
</style>
</head>

<body>

<h1>jQuery attribute selector example</h1>

<div id="msg"></div>

<div>
    <a rel="nofollow" href="http://www.google.com" lang="en-US">
    Google - <a rel="nofollow" href="http://www.google.com" lang="en-US">
    </a>
</div>

<div>
    <a href="http://www.yahoo.com" lang="en">
     Yahoo - <a href="http://www.yahoo.com" lang="en" >
    </a>
</div>

<div>
    <a href="http://www.abc-yahoo.com" lang="-en">
     Yahoo - <a href="http://www.abc-yahoo.com" lang="-en">
    </a>
</div>

<div class="Hello-jQuery">
	class = "Hello-jQuery"
</div>

<div class="Hello jQuery">
	class = "Hello jQuery"
</div>

<div class="HellojQuery">
	class = "HellojQuery"
</div>

<br/><br/>
<button>a[rel]</button>
<button>a[rel=nofollow]</button>
<button>a[rel!=nofollow]</button>
<button>a[rel^=nof]</button>
<button>a[rel$=low]</button>

<button>a[href*=yahoo.com]</button>
<button>a[lang|=en]</button>
<button>div[class~=jQuery]</button>

<button id="reset">Reset It</button>

<script type="text/javascript">
    $("button").click(function () {

	  var str = $(this).text();	
	  $('a').css("border", "0px solid #000000");
	  $(str).css("border", "1px solid #ff0000");
	  $('#msg').html("<h2>Attribute Selector : " + str + "</h2>");
    });

	$("#reset").click(function () {
      location.reload();
    });

</script>

</body>
</html> 

http://web.archive.org/web/20190304032448if_/http://www.mkyong.com/wp-content/uploads/jQuery/jQuery-attribute-selector.html

Try Demojquery jquery attribute

jQuery before()和 insertBefore()示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-before-and-insertbefore-example/

jQuery before()insertBefore() 方法都在执行相同的任务,在匹配的元素之前添加文本或 html 内容。主要的区别在于语法。

举个例子,

 <div class="prettyBox">I'm a ipman</div>
<div class="prettyBox">I'm a ipman 2</div> 

1.$('选择器')。之前(“新内容”);

 $('.prettyBox').before("<div class='newPrettybox'>Iron man</div>"); 

2.$('新内容')。insertBefore(“选择器”);

 $("<div class='newPrettybox'>Iron man</div>").insertBefore('.prettyBox'); 

结果

以上两种方法做的是同样的任务,但是语法不同,新的内容在之后()或者 insertBefore() 之后会变成

 <div class='newPrettybox'>Iron man</div>
<div class="prettyBox">
   I'm a ipman
</div>

<div class='newPrettybox'>Iron man</div>
<div class="prettyBox">
   I'm a ipman 2
</div> 

你自己试试

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

<style type="text/css">
	.prettyBox{
		padding:8px;
		background: grey;
		margin-bottom:8px;
		width:300px;
		height:100px;
	}
	.newPrettybox{
		padding:8px;
		background: red;
		margin-bottom:8px;
		width:200px;
		height:50px;
	}
</style>

</head>
<body>
  <h1>jQuery before() and insertBefore() example</h1>

  <div class="prettyBox">Ip man</div>

  <div class="prettyBox">Ip man 2</div>

  <p>
  <button id="before">before()</button>
  <button id="insertBefore">insertBefore()</button>
  <button id="reset">reset</button>
  </p>

<script type="text/javascript">

    $("#before").click(function () {

	  $('.prettyBox').before("<div class='newPrettybox'>Iron man</div>");

    });

	$("#insertBefore").click(function () {

	  $("<div class='newPrettybox'>Iron man</div>").insertBefore('.prettyBox');

    });

	$("#reset").click(function () {
	  location.reload();
    });

</script>
</body>
</html> 

http://web.archive.org/web/20220826132030if_/https://www.mkyong.com/wp-content/uploads/jQuery/jQuery-before-insertBefore-example.html

Try Demo

jQuery bind()和 unbind()示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-bind-and-unbind-example/

jQuery bind() 函数用于将事件处理程序附加到元素上,而 unbind() 用于将现有的事件处理程序从元素上分离。

例子

演示用的简单 html 代码。

 <div id="BoxId">
	Mouseover Me, Click Me or Double Click Me
</div>
<span></span> 

1.绑定()

jQuery 完全支持 JavaScript 事件类型,如“click”、“dblclick”或自定义事件名称。

将单击事件绑定到 Id 为“BoxId”的元素。

 $("#BoxId").bind("click", (function () {
	$('span').text("Single Clicked");
})); 

将双击事件绑定到 Id 为“BoxId”的元素。

 $("#BoxId").bind("dblclick", (function () {
	$('span').text("Double Clicked");
})); 

2.bind() +事件对象

jQuery 附带了许多事件对象,要获得关于用户环境的更多信息,请查看这里的 jQuery 事件对象细节

将带有事件对象参数的“mouseover”事件绑定到 Id 为“BoxId”的元素。

 $("#BoxId").bind("mouseover", (function (event) {
	$('span').text('The mouse cursor is at ('
	+ event.pageX + ', ' + event.pageY + ')');
})); 

3.bind() +事件数据

这意味着向 bind()函数传递一个自定义参数数据。

绑定一个单击事件,并将自定义消息作为参数传递给 Id 为“BoxId”的元素。在函数内部,您可以借助 event.data 访问参数信息。

 var name = 'Message pass by jQuery event data';
$("#BoxId").bind("click", {msg: name},(function (event) {
	$('span').text("Single Clicked - " + event.data.msg);
})); 

4.bind() +多个事件

要将多个事件绑定在一起,您可以用空格分隔每个事件。

将单击和双击事件绑定到 Id 为“BoxId”的元素。

 $("#BoxId").bind("click dblclick", (function () {
	$('span').text("Single Clicked");
})); 

或者,也可以像下面这样编码:(在 jQuery 1.4 中受支持)。

 $("#BoxId").bind({
	click : function(){
		$('span').text("Single Clicked");
	},
	dblclick : function(){
		$('span').text("Double Clicked");
	}
}); 

5.解除绑定()

解除现有事件的绑定或分离相当容易,只需要指定附加的事件类型。

从 Id 为“BoxId”的元素中分离“click”和“dblclick”事件。

 $('#BoxId').unbind("click");
$('#BoxId').unbind("dblclick"); 

你自己试试

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

<style type="text/css">
	.ClassA{
		padding:8px;
		border:1px solid blue;
	}
	span{
		color:#CC6633;
	}
</style>

</head>
<body>
  <h1>jQuery bind() and unbind() example</h1>

  <div id="BoxId">
	Mouseover Me, Click Me or Double Click Me
  </div>
  <span></span>
  <p>
  <button id="bindButton">bind()</button>
  <button id="bindMessageButton">bind(message)</button>
  <button id="unbindButton">unbind()</button>
  </p>

<script type="text/javascript">

    $("#BoxId").bind("click", (function () {
		$('span').text("Single Clicked");
    }));

    $("#BoxId").bind("dblclick", (function () {
		$('span').text("Double Clicked");
    }));

   //Event object
   $("#BoxId").bind("mouseover", (function (event) {
		$('span').text('The mouse cursor is at ('
                 + event.pageX + ', ' + event.pageY + ')');
    }));

    //Passing event data
    $("#bindMessageButton").bind("click", (function () {
		var name = 'Message pass by jQuery event data';
		$("#BoxId").bind("click", {msg: name},(function (event) {
			$('span').text("Single Clicked - " + event.data.msg);
     }));
    }));

    $("#unbindButton").bind("click",(function () {
		$('#BoxId').unbind("click");
		$('#BoxId').unbind("dblclick");
		$('#BoxId').unbind("mouseover");
		$('span').text("");
    }));

    //added since version 1.4
    $("#bindButton").bind("click",(function () {

		$("#BoxId").bind({
			click : function(){
				$('span').text("Single Clicked");
			},
			dblclick : function(){
				$('span').text("Double Clicked");
			},
			mouseover : function(event){
				$('span').text('The mouse cursor is at ('
                                + event.pageX + ', ' + event.pageY + ')');
			}
		});
    }));

</script>
</body>
</html> 

http://web.archive.org/web/20190210095257if_/http://www.mkyong.com/wp-content/uploads/jQuery/jQuery-bind-unbind-example.html

Try Demojquery jquery event handler

jQuery–子代和同级选择器示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-child-and-sibling-selectors-example/

jQuery 子代和兄弟选择器可以分为四种选择器,后代选择器(A B)、子代选择器(A > B)、相邻兄弟选择器(A + B)和一般兄弟选择器(A ~ B)。让我们通过一个例子来理解两者之间的不同。

首先,你必须明白什么是孩子和兄弟姐妹。让我们看看这个例子,

 <h1>Child and Sibling Selectors example</h1>
<div class="person1">
	<div class="child">
		<div class="grandchild">
			<div class="great-grandchild">
				I'm the great grandchild.
			</div>
			I'm the grandchild.
		</div>
		I'm the first child.
	</div>

	<div class="child">
		I'm the second child.
	</div>

	<div class="child">
		I'm the third child.
	</div>
	I'm person1
</div>
<p class="person2">I'm person2</p>
<p class="person3">I'm person3</p> 

jquery-child-sibling-example

元素下的所有元素都是它的子元素。并且“人员 1”、“人员 2”和“人员 3”是兄弟姐妹关系。

1.后代选择器

后代选择器用于选择与“B”匹配的所有元素,即子元素、孙元素、曾孙元素、曾曾孙元素..(任何深度级别)的“A”元素。

 $(".person1 div").css("border", "2px solid red"); 

jquery-child-sibling-example-descendant-selector ## 2.子选择器(A > B)

子选择器用于选择与“A”元素的子元素“B”匹配的所有元素。

 $(".person1 > div").css("border", "2px solid red"); 

jquery-child-sibling-example-child-selector ## 3.相邻兄弟选择器(A + B)

相邻兄弟选择器用于选择与“A”元素的兄弟“B”匹配的紧接的或下一个元素。

 $(".person1 + p").css("border", "2px solid red"); 

jquery-child-sibling-example-Adjacent-sibling

4.通用兄弟选择器(A ~ B)

通用同级选择器用于选择与“A”元素同级的“B”匹配的所有元素。

 $(".person1 ~ p").css("border", "2px solid red"); 

jquery-child-sibling-example-general-sibling

希望您现在对 jQuery 选择器有了更多的了解。

jquery jquery selector

jQuery–子选择器示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-child-selector-example/

jQuery 子选择器(X > Y) 用于选择与“X”元素的子元素“Y”匹配的所有元素。

举个例子,

  • $(' form>input ')–选择所有由< input >匹配的元素,这些元素是由< form >匹配的元素的子元素,只有子元素匹配,孙子、曾孙不匹配。

jQuery 示例

在本例中,只有“文本框 1”和“文本框 4”匹配(表单元素的子元素),而“文本框 2”(孙元素)和“文本框 3”(曾孙元素)不匹配。

 <html>
<head>
<title>jQuery child selector example</title>

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

 <style type="text/css">
  div { padding:8px 0px 8px 8px; }
 </style>

</head>

<script type="text/javascript">

$(document).ready(function(){

	$("form > input").css("border", "2px solid red");

});

</script>
<body>

<h1>jQuery child selector example</h1>

<form>

	<label>TextBox 1 (Child) : </label><input name="textbox1">

	<div class="level1">
		<label>TextBox 2 (GrandChild) : </label><input name="textbox2">
	</div>

	<div class="level1">
	   <div class="level2">
	    <label>TextBox 3 (Great GrandChild) : </label><input name="textbox3">
	   </div>
	</div>

	<label>TextBox 4 (Child) : </label><input name="textbox4">

</form>

<div> I'm form siblings #1 - DIV</div>

<p> I'm form siblings #2 - P </p>

<div> I'm form siblings #3 - DIV </div>

<p> I'm form siblings #4 - P </p>

</body>
</html> 

http://web.archive.org/web/20220618072947if_/https://www.mkyong.com/wp-content/uploads/jQuery/jQuery-child-selector.html

Try Demo

jQuery children()示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-children-example/

在 jQuery 中, children() 用于查找匹配元素的子元素,只是向下移动了一层

例如,深度为三级的 div 元素包含一个类名“child”和“orphan”。

 <div class="A1">
	<div class="child">A1-1</div>
	<div class="child">A1-2</div>
	<div class="orphan">A1-3</div>
	<div class="child">A1-4</div>

	<div class="A2">
		<div class="child">A2-1</div>
		<div class="child">A2-2</div>

		<div class="A3">
			<div class="child">A3-1</div>
			<div class="child">A3-2</div>
		</div>
	</div>

</div> 

1.$('.A1 ')。儿童()

 $('.A1').children().css('background','red'); 

匹配元素包含一个类名为“ A1 ”,以及所有的A1单级子级”。

A2 和 A3 孩子将被忽略。

2.$('.A1 ')。孩子(’。孩子’)

 $('.A1').children('.child').css('background','red'); 

匹配包含类名“ A1 ”的元素,并搜索包含类名“child”的“ A1 ”子元素。在本例中,除了类名为“孤儿”的孩子外,所有 A1 的“单级孩子”都将被选择

jQuery children()示例

 <html>
<head>

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

<style type="text/css">
	div{
		padding:8px;
		border:1px solid;
	}
</style>

</head>

<body>

<h1>jQuery children() example</h1>

<script type="text/javascript">

  $(document).ready(function(){

    $("#buttonChildren1").click(function () {

	$('div').css('background','white');

	$('.A1').children().css('background','red');

    });

    $("#buttonChildren2").click(function () {

	$('div').css('background','white');

	$('.A1').children('.child').css('background','red');

    });

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

<div class="A1">
	<div class="child">A1-1</div>
	<div class="child">A1-2</div>
	<div class="orphan">A1-3</div>
	<div class="child">A1-4</div>

	<div class="A2">
		<div class="child">A2-1</div>
		<div class="child">A2-2</div>

		<div class="A3">
			<div class="child">A3-1</div>
			<div class="child">A3-2</div>
		</div>
	</div>

</div>

<br/>
<br/>
<br/>

<input type='button' value='.A1 children()' id='buttonChildren1'>
<input type='button' value='.A1 children(child)' id='buttonChildren2'>

</body>
</html> 

http://web.archive.org/web/20190215032140if_/http://www.mkyong.com/wp-content/uploads/jQuery/jQuery-children-example.html

Try Demojquery jquery traversing

jQuery click()和 dblclick()示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-click-and-dblclick-example/

jQuery click()dblclick() 事件是最常用的鼠标事件:

  1. click()–当鼠标单击匹配的元素时触发。
  2. dblclick()–当鼠标双击匹配的元素时触发。

你自己试试

 <html>
<head>

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

<style type="text/css">
	#singleClick, #doubleClick{
		float:left;
		padding:8px;
		margin:16px;
		border:1px solid blue;
		width:150px;
		height:150px;
		background-color:#999966;
	}

</style>

</head>

<body>

<h1>jQuery click() and dblclick() example</h1>

<div id="singleClick">
	Single Click Me
</div>

<div id="doubleClick">
	Double Clicks Me
</div>

<script type="text/javascript">

$('#singleClick').click(function(){
	$('#singleClick').slideUp();
});

$('#doubleClick').dblclick(function(){
	$('#doubleClick').fadeOut();
});

</script>

</body>
</html> 

http://web.archive.org/web/20190304032700if_/http://www.mkyong.com/wp-content/uploads/jQuery/jQuery-click-dblclick-example.html

Try Demojquery mouse movement (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190304032700/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

jQuery clone()示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-clone-example/

jQuery clone() 用于创建匹配元素的副本。它还支持一个布尔参数来指示是否需要将事件处理程序和数据与匹配的元素一起复制。

1.克隆 html 元素

例如,您将克隆以下 html 代码。

 <div class="smallBox">
	I'm a small box
	<div class="smallInnerBox">I'm a small small inner box</div>
 </div> 

使用 clone()创建上述元素的副本,并将复制的元素放在包含类名“smallBox”的 div 标签之后。

 $('.smallBox').clone().insertAfter(".smallBox"); 

结果是:

 <div class="smallBox">
	I'm a small box
	<div class="smallInnerBox">I'm a small small inner box</div>
 </div>
  <div class="smallBox">
	I'm a small box
	<div class="smallInnerBox">I'm a small small inner box</div>
 </div> 

2.克隆事件处理程序

下一个示例将是克隆按钮单击事件,您将复制包含 id“clone button 1”的按钮。

 <button id="cloneButton1">clone()</button>

<script type="text/javascript">
    $("#cloneButton1").click(function () {

	  $('.smallBox').clone().insertAfter(".smallBox");

    });
</script> 

如果使用默认的 clone()或 clone(false)方法,它将只复制按钮元素,而不复制 click()事件处理程序。

 $('#cloneButton1').clone().insertAfter("#cloneButton1"); 

要复制 click()事件处理程序以及匹配的元素,应该使用 clone(true)。

 $('#cloneButton1').clone(true).insertAfter("#cloneButton1"); 

你自己试试

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

<style type="text/css">
	.smallBox{
		padding:8px;
		border:1px solid blue;
		margin:8px;
	}
	.smallInnerBox{
		padding:8px;
		border:1px solid green;
		margin:8px;
	}
</style>

</head>
<body>
  <h1>jQuery clone() example</h1>

  <div class="smallBox">
	I'm a small box
	<div class="smallInnerBox">I'm a small small inner box</div>
   </div>

  <p>
  <button id="cloneButton1">clone()</button>
  <button id="cloneButton2">clone() button (default)</button>
  <button id="cloneButton3">clone(true) button</button>
  <button id="reset">reset</button>
  </p>

<script type="text/javascript">

    $("#reset").click(function () {
	  location.reload();
    });

    $("#cloneButton1").click(function () {

	  $('.smallBox').clone().insertAfter(".smallBox");

    });

    $("#cloneButton2").click(function () {

	  $('#cloneButton1').clone(false).insertAfter("#cloneButton1");

    });

    $("#cloneButton3").click(function () {

	  $('#cloneButton1').clone(true).insertAfter("#cloneButton1");

    });

</script>
</body>
</html> 

http://web.archive.org/web/20220826132030if_/https://www.mkyong.com/wp-content/uploads/jQuery/jQuery-clone-example.html

Try Demo

jQuery–包含选择器示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-contains-selector-example/

jQuery contains(text)选择器用于选择包含指定文本的所有元素。

例句
1。\((' p:contains(paragraph 1)')–选择与包含文本“paragraph 1”的< p >匹配的所有元素。 2。\)(' p:contains(mkyong)')–选择与包含文本“mkyong”的< p >匹配的所有元素。
3。$(' Li:contains(three)')–选择与包含文本“three”的< li >匹配的所有元素。

播放它

点击按钮来玩容器选择器。

 <html>
<head>
<title>jQuery contains selector example</title>

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

<style type="text/css">
	#msg{
		padding:8px;
		hright:100px;
	}
</style>
</head>

<body>

<h1>jQuery contains selector example</h1>

<div id="msg"></div>

<ul>
	<li>One</li>
	<li>two</li>
	<li>three</li>
	<li>four</li>
	<li>five</li>
</ul>

<p>
	This is a paragraph 1 - google.com
</p>

<p>
	This is a paragraph 2 - mkyong.com
</p>

<br/><br/>
<button>p:contains(paragraph 1)</button>
<button>p:contains(mkyong)</button>
<button>li:contains(three)</button>

<script type="text/javascript">
    $("button").click(function () {

	  var str = $(this).text();	
	  $('p, li').css("border", "0px solid #000000");
	  $(str).css("border", "1px solid #ff0000");
	  $('#msg').html("<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script><h2>Button clicked : " + str + "</h2>");
    });

</script>

</body>
</html> 

http://web.archive.org/web/20190223073152if_/http://www.mkyong.com/wp-content/uploads/jQuery/jQuery-contains-selector.html

Try Demojquery jquery selector (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190223073152/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

jQuery–后代选择器示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-descendant-selector-example/

jQuery descender selector(X Y)用于选择与“Y”匹配的所有元素,包括子元素、孙元素、曾孙元素、曾曾孙元素..(任何深度级别)的“X”元素。

举个例子,

  • $(' # container div ')–选择与< div >匹配的所有元素,这些元素是 id 为 container 的元素的后代。
  • $(' form input ')–选择由<输入>匹配的所有元素,这些元素是由<表单>匹配的元素的后代。

jQuery 示例

在本例中,它使用 jQuery 后代选择器向作为

元素后代的所有字段添加一个“红色边框”。
 <html>
<head>
<title>jQuery descendant selector example</title>

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

 <style type="text/css">
  div { padding:8px 0px 8px 8px; }
 </style>

</head>

<script type="text/javascript">

$(document).ready(function(){

	$("form input").css("border", "2px solid red");

});

</script>
<body>

<h1>jQuery child selector example</h1>

<form>

	<label>TextBox 1 (Child) : </label><input name="textbox1">

	<div class="level1">
		<label>TextBox 2 (GrandChild) : </label><input name="textbox2">
	</div>

	<div class="level1">
	   <div class="level2">
   	     <label>TextBox 3 (Great GrandChild) : </label><input name="textbox3">
	   </div>
	</div>

	<label>TextBox 4 (Child) : </label><input name="textbox4">

</form>

<div> I'm form siblings #1 - DIV</div>

<p> I'm form siblings #2 - P </p>

<div> I'm form siblings #3 - DIV </div>

<p> I'm form siblings #4 - P </p>

</body>
</html> 

http://web.archive.org/web/20220618072947if_/https://www.mkyong.com/wp-content/uploads/jQuery/jQuery-descendant-selector.html

Try Demo

jQuery empty()和 remove()示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-empty-and-remove-example/

jQuery empty()remove() 都是用来移除匹配的元素,只是前者是用来移除匹配元素的子元素;而后者用于完全移除所有匹配的元素。

例子

2 个 div 标签–“BBox”是“ABox”的子元素。

 <div class="ABox">
	I'm a A box
	<div class="BBox">I'm a B box</div>
</div> 

1.空()

empty()将只移除“ABox”内容和“BBox”子元素。

 $('.ABox').empty(); 

新的结果将是:

 <div class="ABox">
</div> 

2.移除()

remove()将完全删除所有“ABox”和“BBox”元素。

 $('.ABox').remove(); 

新的结果将是:

 //nothing left 

你自己试试

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

<style type="text/css">
	.ABox{
		padding:8px;
		border:1px solid blue;
	}
	.BBox{
		padding:8px;
		border:1px solid red;
	}
</style>

</head>
<body>
  <h1>jQuery empty() and remove() example</h1>

  <div class="ABox">
	I'm a A box
	<div class="BBox">I'm a B box</div>
   </div>

  <p>
  <button id="empty">empty()</button>
  <button id="remove">remove()</button>
  <button id="reset">reset</button>
  </p>

<script type="text/javascript">

    $("#reset").click(function () {
	  location.reload();
    });

    $("#empty").click(function () {

	  $('.ABox').empty();

    });

    $("#remove").click(function () {

	  $('.ABox').remove();

    });

</script>
</body>
</html> 

http://web.archive.org/web/20220826132007if_/https://www.mkyong.com/wp-content/uploads/jQuery/jQuery-empty-remove-example.html

Try Demo

jQuery–空选择器示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-empty-selector-example/

在 jQuery 中,“ empty ”选择器用于选择所有没有子元素的元素(包括其中的任何文本)。

例子

 <div class="div-class1">
   This is div-class1
</div>

<div class="div-class2" /> 

$(':empty ')–匹配“ div-class2 ”,不匹配“ div-class1 ”。

jQuery 示例

一个简单的例子展示了 jQuery“empty”选择器的用法。

 <html>
<head>
<title>jQuery empty example</title>

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

<style type="text/css">
	div{
		padding:8px;
		border:1px solid;
	}
</style>
</head>

<body>

<h1>jQuery empty example</h1>

<div class="div-class1">
	This is div-class1
</div>

<div class="div-class2" />

<div class="div-class3">
	This is div-class3
	<div class="div-class3-1">
		This is div-class3-1
	</div>	
</div>

<br/><br/>

<button>:empty</button>

<script type="text/javascript">
    $("button").click(function () {
      var str = $(this).text();
      $("*").css("background", "white");
      $(str).css("background", "coral");
    });
</script>

</body>
</html> 

http://web.archive.org/web/20190304031949if_/http://www.mkyong.com/wp-content/uploads/jQuery/jQuery-empty-example.html

Try Demojquery jquery selector (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190304031949/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

jQuery fadeIn()、fadeOut()和 fadeTo()示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-fadein-fadeout-and-fadeto-example/

jQuery 提供了三种简便的方法来轻松创建渐变效果。

  1. fade in()–以淡入效果显示匹配的元素。
  2. fade out()–隐藏具有淡出/透明效果的匹配元素。
  3. fade to()–将匹配的元素淡化到一定的不透明度。

以上三种方法都支持持续时间作为参数:慢速、快速或精确的毫秒。如果省略此参数,则应用默认的 400 毫秒。

你自己试试

 <html>
<head>

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

<style type="text/css">
	.fadeOutbox, .fadeInbox, .fadeTobox{
		float:left;
		padding:8px;
		margin:16px;
		border:1px solid red;
		width:200px;
		height:50px;
		background-color:#000000;
		color:white;
	}
	.clear{
		clear:both;
	}
</style>

</head>

<body>

<h1>jQuery fadeIn(), fadeOut() and fadeTo() example</h1>

<div class="clear">
	<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script><h2>fadeOut() example</h2>

	<div class="fadeOutbox">
		Click me - fadeOut()
	</div>

	<div class="fadeOutbox">
		Click me - fadeOut()
	</div>
</div>

<div class="clear">
	<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script><h2>fadeIn() example</h2>

	<div class="fadeInbox">
		Click me - fadeIn()
	</div>

	<div class="fadeInbox">
		Click me - fadeIn()
	</div>
</div>

<div class="clear">
	<h2>fadeTo() example</h2>

	<div class="fadeTobox">
		Click me - fadeTo()
	</div>

	<div class="fadeTobox">
		Click me - fadeTo()
	</div>
</div>

<div class="clear">
	<button id=reset>Reset</button>
</div>

<script type="text/javascript">

$(".fadeOutbox").click(function () {
   $(this).fadeOut('slow');
});

$(".fadeInbox").click(function () {
   $(this).hide().fadeIn(2000);
});

$(".fadeTobox").click(function () {
   $(this).fadeTo('fast',0.2);
});

$("#reset").click(function(){
	location.reload();
});
</script>

</body>
</html> 

http://web.archive.org/web/20190216193440if_/http://www.mkyong.com/wp-content/uploads/jQuery/jQuery-fadeIn-faceOut-fadeTo-example.html

Try Demojquery jquery effects (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190216193440/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

jQuery filter()示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-filter-example/

jQuery filter 函数是一个有用的特性,通过使用匹配的选择器或函数的测试,可以从一组匹配的元素中提取元素。

1.过滤器(选择器)

在一组匹配的元素中,只获取与 filter()选择器匹配的元素。

举个例子,

 $("div").filter("#div1").css('background-color', 'blue'); 

匹配所有 div 元素,并选择包含 id“div 1”的 div 元素,并将元素的背景色更改为蓝色。

2.过滤器(功能)

在一组匹配的元素中,获取通过函数测试的元素。该函数在内部传递一个索引参数,该参数表示匹配元素的索引,从 0 开始计数。

举个例子,

 $('div').filter(function(index) {
	if(index==2 || index==3){ //0 index based
		return true;
	}
}).css('background-color', 'blue'); 

匹配所有 div 元素,使用函数过滤,只选择第三(2)和第四(3)个 div 元素。

 $('div').filter(function(index) {
	return $("b", this).length == 1;
}).css('background-color', 'blue'); 

匹配所有 div 元素,用函数过滤选择包含标签的 div 元素。

jQuery filter()示例

 <html>
<head>
<title>jQuery filter example</title>

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

</head>

<body>

<h1>jQuery filter example</h1>

<script type="text/javascript">

  $(document).ready(function(){

    $("#filterSelector").click(function () {

	$('div').css('background-color', 'white');

	$("div").filter("#div1").css('background-color', 'blue');

    });

    $("#filterFunction").click(function () {

	$('div').css('background-color', 'white');

	$('div').filter(function(index) {
		if(index==2 || index==3){ //0 index based
			return true;
		}
	}).css('background-color', 'blue');

    });

    $("#filterFunction2").click(function () {

	$('div').css('background-color', 'white');

	$('div').filter(function(index) {
		return $("b", this).length == 1;
	}).css('background-color', 'blue');

    });

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

<div id="div1">
	<b>This is div 1 with 'b' tag</b>
</div>
<div id="div2">
	This is div 2
</div>
<div id="div3">
	<b>This is div 3 with 'b' tag</b>
</div>
<div id="div4">
	This is div 4
</div>

<br/>
<br/>
<br/>

<input type='button' value='filter(selector)' id='filterSelector'>
<input type='button' value='filter(index)' id='filterFunction'>
<input type='button' value='filter(index)+b' id='filterFunction2'>
</body>
</html> 

http://web.archive.org/web/20190306103218if_/http://www.mkyong.com/wp-content/uploads/jQuery/jQuery-filter-example.html

Try Demojquery jquery traversing

jQuery find()示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-find-example/

使用 jQuery,您可以使用find()来搜索匹配元素的所有后代(子元素、孙元素、曾孙元素……任何深度级别)。

例如,div元素有三层深度。

 <div id="A1">

	<div class="child">A1-1</div>
	<div class="child">A1-2</div>

	<div id="A2">

		<div class="child">A2-1</div>
		<div class="child">A2-2</div>

		<div id="A3">

			<div class="child">A3-1</div>
			<div class="child">A3-2</div>

		</div>

	</div>

</div> 

1.$('#A1 ')。查找('。孩子’)

 $('#A1').find('.child').css('background','red'); 

找到包含 id 为“A1”的元素,以及包含类名“”的子元素,然后将其背景更改为红色。

2.$('#A2 ')。查找('。孩子’)

 $('#A2').find('.child').css('background','red'); 

找到包含 id 为“A2”的元素,以及包含类名“”的子元素,然后将其背景更改为红色。

3.jQuery find()示例

播放这个例子。

HTML example

 <html>
<head>

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

<style type="text/css">
	div{
		padding:8px;
		border:1px solid;
	}
</style>

</head>

<body>

<h1>jQuery find() example</h1>

<script type="text/javascript">

  $(document).ready(function(){

    $("#button1").click(function () {

	$('div').css('background','white');

	$('#A1').find('.child').css('background','red');

    });

    $("#button2").click(function () {

	$('div').css('background','white');

	$('#A2').find('.child').css('background','red');

    });

    $("#button3").click(function () {

	$('div').css('background','white');

	$('#A3').find('.child').css('background','red');

    });

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

<div id="A1">A1
	<div class="child">A1-1</div>
	<div class="child">A1-2</div>

	<div id="A2">A2
		<div class="child">A2-1</div>
		<div class="child">A2-2</div>

		<div id="A3">A3
			<div class="child">A3-1</div>
			<div class="child">A3-2</div>
		</div>
	</div>

</div>

<br/>
<br/>
<br/>

<input type='button' value='find #A1' id='button1'>
<input type='button' value='find #A2' id='button2'>
<input type='button' value='find #A3' id='button3'>

</body>
</html> 

http://web.archive.org/web/20190224153456if_/http://www.mkyong.com/wp-content/uploads/jQuery/jQuery-find-example.html

参考

  1. jQuery find() API 文档

jquery jquery traversing

jQuery–第一个孩子和最后一个孩子选择器示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-first-child-last-child-selector-example/

:first-child 用于选择作为其父元素的第一个子元素的所有元素,这是:n-child(1)的简写。

例子

  1. $(' Li:first-child ')–选择与
  2. 匹配的所有元素,这些元素是其父元素的第一个子元素。
  3. $(tr:first-child ')–选择与匹配的所有元素,这些元素是其父元素的第一个子元素。

:last-child 用于选择作为其父元素的最后一个子元素的所有元素。

例子

  1. $(' Li:last-child ')–选择与
  2. 匹配的所有元素,这些元素是其父元素的最后一个子元素。
  3. $(tr:last-child ')–选择与匹配的所有元素,这些元素是其父元素的最后一个子元素。

jQuery 示例

一个简单的例子,演示了如何使用 first child 和 last child 函数来动态添加" li "背景色。

 <html>
<head>
<title>jQuery first child and last child example</title>

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

<body>

<h1>jQuery first child and last child example</h1>

<ul>
	<li>li #1</li>
	<li>li #2</li>
	<li>li #3</li>
	<li>li #4</li>
	<li>li #5</li>
</ul>

<button>li:first-child</button>
<button>li:last-child</button>

<script type="text/javascript">
    $("button").click(function () {
      var str = $(this).text();
      $("li").css("background", "white");
      $(str).css("background", "coral");
    });
</script>

</body>
</html> 

http://web.archive.org/web/20190214222610if_/http://www.mkyong.com/wp-content/uploads/jQuery/jQuery-first-child-last-child.html

Try Demojquery jquery selector (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190214222610/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

jQuery 表单事件示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-form-events-examples/

jQuery 提供了五个常见的表单事件来处理表单元素的动作。

1.焦点()

当元素处于焦点时激发。

 $("input,select,textarea").focus(function () {
	//do something
}); 

2.模糊()

当元素失去焦点时激发。

 $("input,select,textarea").blur(function () {
	//do something
}); 

3.更改()

当元素值改变时触发,例如更新复选框,单选按钮或文本框值。

 $("input,select,textarea").change(function () {
	//do something
}); 

4.选择()

突出显示元素内的文本时触发,仅限于 textbox 或 textarea。

 $("input,textarea").focus(function () {
	//do something
}); 

5.提交()

试图提交表单时触发,仅绑定到表单元素。

 $("form").focus(function () {
	//do something
}); 

你自己试试

 <html>
<head>

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

<style type="text/css">
	div{
		padding:16px;
	}
	.focus, .blur, .change, .select{
		color:white;
		border:1px solid red;
		background-color:blue;
		padding:8px;
		margin:8px;
	}
</style>
</head>

<body>

<h1>jQuery form events - focus(), change(), blur(), select(), submit() example</h1>

<form name="testing" action="#">
<div>
   TextBox : <input type="textbox" size="50"></input>
</div>
<div>
   <label style="float:left">TextArea : </label> 
   <textarea cols="30" rows="5"></textarea>
</div>
<div>
   Radio : <input name="sex" type="radio" value="Male" checked>Male</input>
	     <input name="sex" type="radio" value="Female">Female</input>
</div>
<div>
   CheckBox : <input type="checkbox" name="checkme">Check Me</input>
</div>

<div>
   Country : <select id="country">
		  <option value="China">China</option>
	 	  <option value="United State">United State</option>
		 </select>
</div>

<div>
	<input type="submit"></input> <input type="reset"></input>
</div>

</form>

<script type="text/javascript">

    $("input,select,textarea").focus(function () {

	  $(this).after("<span class='focus'> focus() triggered! </span>");
	  $("span").filter('.focus').fadeOut(4000);

    });

    $("input,select,textarea").blur(function () {

	  $(this).after("<span class='blur'> blur() triggered! </span>");
	  $("span").filter('.blur').fadeOut(4000);

    });

    $("input,select,textarea").change(function () {

	  $(this).after("<span class='change'> change() triggered! </span>");
	  $("span").filter('.change').fadeOut(4000);

    });

    $("input,textarea").select(function () {

	  $(this).after("<span class='select'> select() triggered! </span>");
	  $("span").filter('.select').fadeOut(4000);

    });

    $("form").submit(function () {

	 	alert('Form submitted!');

    });	
</script>

</body>
</html> 

http://web.archive.org/web/20190309091101if_/http://www.mkyong.com/wp-content/uploads/jQuery/jQuery-form-events.html

Try Demoform event jquery

jQuery 表单选择器示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-form-selectors-example/

jQuery 附带了许多表单选择器,可以更容易、更有效地访问表单元素。下面是一个简单的 jQuery 表单选择器参考。

1. TextBox – $(‘input:text’)

选择文本框

 $('input:text'); 

获取文本框值

 $('input:text').val(); 

设置文本框值

 $('input:text').val("New Text"); 

2.密码-$('输入:密码')

要选择密码

 $('input:password'); 

获取密码值

 $('input:password').val(); 

要设置密码值

 $('input:text').val("New Text"); 

3.textarea-$(' textarea ')

要选择文本区域

 $('textarea'); 

获取 textarea 值

 $('textarea').val(); 

要设置 textarea 值

 $('textarea').val("New Text in Textarea"); 

4.单选按钮-$('输入:单选')

要选择单选按钮

 $('input:radio'); 

获取选中的单选按钮选项

 $('input:radio[name=radiobutton-name]:checked').val(); 

选择第一个单选按钮选项

 $('input:radio[name=radiobutton-name]:nth(0)').attr('checked',true);
or
$('input:radio[name=radiobutton-name]')[0].checked = true; 

更多详情…

5.复选框-$('输入:复选框')

要选择复选框

 $('input:checkbox'); 

检查复选框是否被选中

 $('input:checkbox[name=checkboxname]').is(':checked'); 

要选中复选框

 $('input:checkbox[name=checkboxname]').attr('checked',true); 

取消选中复选框

 $('input:checkbox[name=checkboxname]').attr('checked',false); 

更多详情…

6.上传文件-$('输入:文件')

要选择文件

 $('input:file'); 

获取文件值

 $('input:file').val(); 

7.隐藏值–$('输入:隐藏')

要选择隐藏值

 $('input:hidden'); 

为了得到隐藏的值

 $('input:hidden').val(); 

要设置隐藏值

 $('input:hidden').val("New Text"); 

8.选择(下拉框)–$('选择')

选择下拉框

 $('select')
or
$('#dropdown-id') 

获取选定的下拉框值

 $('#dropdown-id').val(); 

将下拉框值设置为“中国”

 $("#dropdown-id").val("China"); 

更多详情…

9.提交按钮-$('输入:提交')

要选择提交按钮

 $('input:submit'); 

10.重置按钮-$('输入:重置')

要选择复位按钮

 $('input:reset'); 

jQuery 表单选择器

 <html>
<head>
<title>jQuery form selector example</title>

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

<style type="text/css">
	div{
		padding:16px;
	}
</style>
</head>

<body>

<h1>jQuery form selector example</h1>

<h2>Message = <label id="msg"></label></h2>

<form name="testing" action="#">
  <div>
	TextBox : <input type="textbox" value="This is message from textbox" />
  </div>
  <div>
	Password : <input type="password" value="This is message from password" />
  </div>
  <div>
	TextArea : <textarea>This is message from textarea</textarea>
  </div>
  <div>
	Radio : <input name="sex" type="radio" value="Male" checked>Male</input>
	        <input name="sex" type="radio" value="Female">Female</input>
  </div>
  <div>
	CheckBox : <input type="checkbox" name="checkme">Check Me</input>
  </div>
  <div>
	File : <input type="file"></input>
  </div>
  <div>
	Hidden : <input type="hidden" value="This is message from hidden"/>
  </div>
  <div>
	Country : <select id="country">
			<option value="China">China</option>
			<option value="United State">United State</option>
		     </select>
  </div>
  <div>
	<input type="submit"></input> <input type="reset"></input>
  </div>	
</form>

<button id="text">input:text</button>
<button id="password">input:password</button>
<button id="textarea">textarea</button>
<button id="radio">input:radio</button>
<button id="checkbox">input:checkbox</button>
<button id="file">input:file</button>
<button id="hidden">input:hidden</button>
<button id="select">select</button>
<button id="submit">input:submit</button>
<button id="reset">input:reset</button>

<script type="text/javascript">
    $("#text, #password, #hidden, 
          #textarea, #file, #submit, #reset").click(function () {
	  var str = $(this).text();
	  $('input, textarea, select').css("background", "#ffffff");
	  $(str).css("background", "#ff0000");
	  $('#msg').html($(str).val())
    });

    $("#radio").click(function () {
	  $('input, textarea, select').css("background", "#ffffff");
	  $('#msg').html($('input:radio[name=sex]:checked').val());
    });

    $("#checkbox").click(function () {
	  var str = $(this).text();
	  $('input, textarea, select').css("background", "#ffffff");

	  if($('input:checkbox[name=checkme]').is(':checked')){
	  	$('#msg').html("Checkbox is checked");
	  }else{
	  	$('#msg').html("Checkbox is uncheck");
	  }	  
    });

    $("#select").click(function () {
	  $('input, textarea, select').css("background", "#ffffff");
	  $('#msg').html($('#country').val());
    });

</script>

</body>
</html> 

http://web.archive.org/web/20190227163628if_/http://www.mkyong.com/wp-content/uploads/jQuery/jQuery-form-selector.html

Try Demojquery jquery selector

jQuery–一般同级选择器示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-general-sibling-selector-example/

jQuery 通用同级选择器(X ~ Y) 用于选择与“X”元素的同级“Y”匹配的所有元素。

举个例子,

 <div class="class1"></div>
<p>I'm class1 sibling #1</p>
<p>I'm class1 sibling #2</p>
<p>I'm class1 sibling #3</p> 

是兄弟关系。“ $(.class1 ~ p) ”语句将选择所有的< p >元素。

jQuery 示例

在本例中,值为"I ' m form siblings # 1–DIV"的

标记和值为"I ' m form siblings # 3–DIV"的< div >标记都匹配,因为它们是表单>的<的兄弟元素。

 <html>
<head>
<title>jQuery general sibling selector example</title>

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

 <style type="text/css">
  div { padding:8px 0px 8px 8px; }
 </style>

</head>

<script type="text/javascript">

$(document).ready(function(){

	$("form ~ div").css("border", "2px solid red");

});

</script>
<body>

<h1>jQuery general sibling selector example</h1>

<form>

	<label>TextBox 1 (Child) : </label><input name="textbox1">

	<div class="level1">
		<label>TextBox 2 (GrandChild) : </label><input name="textbox2">
	</div>

	<div class="level1">
	 <div class="level2">
	   <label>TextBox 3 (Great GrandChild) : </label><input name="textbox3">
	 </div>
	</div>

	<label>TextBox 4 (Child) : </label><input name="textbox4">

</form>

<div> I'm form siblings #1 - DIV</div>

<p> I'm form siblings #2 - P </p>

<div> I'm form siblings #3 - DIV </div>

<p> I'm form siblings #4 - P </p>

</body>
</html> 

http://web.archive.org/web/20190225110643if_/http://www.mkyong.com/wp-content/uploads/jQuery/jQuery-general-sibling-selector.html

Try Demojquery jquery selector (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190225110643/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

jQuery Hello World

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-hello-world/

jQuery 是一个快速而简洁的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互,有助于快速的 web 开发。jQuery 旨在改变您编写 JavaScript 的方式。

jQuery 是新技术?肯定不是,我认为 jQuery 是一种简化客户端 web 开发的新方法,就像 HTML 遍历 DOM 和 Ajax 操作一样。iQuery 是由一个年轻的孩子 John Resig 创建的,请访问他的网站,看看这个 jQuery 家伙长什么样~

让我们通过一个 jQuery Hello World 示例来理解它是如何工作的。

1.下载 jQuery 库

jQuery 只是一个 20+kb 的小 JavaScript 文件(如 jquery-1.2.6.min.js),你可以从 jQuery 官网下载。。

2.HTML + jQuery

创建一个简单的 HTML 文件(test.html),并将下载的 jQuery 库作为普通的 JavaScript 文件包含在内。js)。

 <html>
<head>
<title>jQuery Hello World</title>

<script type="text/javascript" src="jquery-1.2.6.min.js"></script>

</head>

<body>

<script type="text/javascript">

$(document).ready(function(){
 $("#msgid").html("This is Hello World by JQuery");
});

</script>

This is Hello World by HTML

<div id="msgid">
</div>

</body>
</html> 

3.演示

$()表示一个 jQuery 语法,下面的脚本表示当 DOM 元素准备好或完全加载时,执行 jQuery 脚本来动态创建一个消息,并将其附加到 html 标记 id“msgid”。

 $(document).ready(function(){
 $("#msgid").html("This is Hello World by JQuery");
}); 

jQuery–如何获取带有 CSS 类名和 id 的元素

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-how-to-get-element-with-css-class-name-and-id/

在 jQuery 中,可以很容易地获得带有 CSS 类名和 id 的元素。

举个例子,

1.ID: #id

  • $(' # idA ')–选择 id 为' idA '的所有元素,而不考虑其标记名。
  • $(' div # idA ')–选择 id 为' idA '的所有 div 元素。

2.类别:。类名

  • $('。classA))–选择类名为“class a”的所有元素,而不考虑其标记名。
  • $(' div . classA ')–选择类名为' class a '的所有 div 元素。

完整示例

 <html>
<head>
<title>jQuery Get element with class name and id</title>

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

</head>

<script type="text/javascript">

$(document).ready(function(){

    var $element = $('.classABC').html();
    alert($element);

    var $element = $('#idABC').html();
    alert($element);

});

</script>
<body>

<h1>jQuery Get element with class name and id</h1>

	<div class="classABC">
		This is belong to 'div class="classABC"' 
	</div>

	<div id="idABC">
		This is belong to 'div id="idABC"'
	</div>

</body>
</html> 

Try Demo

jQuery——如何获得标记名

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-how-to-get-the-tag-name/

要获得元素标记名,可以使用标记名函数。有两种方法可以使用它:

1) .get(0).tagName

选择一个类名为“classTag1”的元素,并使用。获取(0)。标记名函数显示其标记名。

 $('.classTag1').get(0).tagName; 

页:1。[0].tagName

2.选择一个类名为“classTag1”的元素,并使用。[0].标记名函数显示其标记名。

 $('.classTag1')[0].tagName; 

例子

 <html>
<head>
<title>jQuery Get Tag Name</title>

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

</head>

<script type="text/javascript">

$(document).ready(function(){

    var $tag = $('p')[0].tagName; //'P'
    alert($tag);

    var $tag = $('.classTag1')[0].tagName; //'DIV'
    alert($tag);

    var $tag = $('#idTag1')[0].tagName; //'DIV'
    alert($tag);

    var $tag = $('p').get(0).tagName; //'P'
    alert($tag);

    var $tag = $('.classTag1').get(0).tagName; //'DIV'
    alert($tag);

    var $tag = $('#idTag1').get(0).tagName; //'DIV'
    alert($tag);	

});

</script>
<body>

<h1>jQuery Get Tag Name</h1>

    <p>
    	This is paragrah 1
    </p>

	<div class="classTag1">
		This is class='classTag1'
	</div>

	<div id="idTag1">
		This is id='idTag1'
	</div>

</body>
</html> 

Try Demo

jQuery——如何获取标签值或元素内容

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-how-to-get-the-tag-value-or-element-content/

在 jQuery 中,您可以从选定的标记中获取标记值或元素内容。

举个例子,

1.选择标记名“p”并显示其标记值。

 $('p').html(); 

2.选择类名为“class1”的元素并显示其值。不管标签名称如何。

 $('.class1').html(); 

3.选择 id 为“id1”的元素并显示其值。不管标签名称如何。

 $('#id1').html(); 

jQuery 示例

 <html>
<head>
<title>jQuery Get Tag Value</title>

<script type="text/javascript" src="jquery-1.3.2.js"></script>

</head>

<script type="text/javascript">

$(document).ready(function(){
    var $temp = $('p').html();
    alert($temp);

    var $temp = $('.class1').html();
    alert($temp);

    var $temp = $('#id1').html();
    alert($temp);

});

</script>
<body>

<h1>jQuery Get Tag Value</h1>

    <p>
    	This is paragrah 1
    </p>

	<div class="class1">
		This is class='class1'
	</div>

	<div id="id1">
		This is id='id1'
	</div>

</body>
</html> 

Try Demo

jQuery html()示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-html-example/

jQuery html() 用于获取匹配元素的第一个元素的 html 内容;而html(‘新 html 内容’)用于替换或设置所有匹配元素的 html 内容。

例如,包含相同类名“AClass”的两个 div 元素。

 <div class="AClass">ABC 1</div>
<div class="AClass">ABC 2</div> 

1.$('.a 类)。html()

这将只得到“ ABC 1 ”,第二个匹配的元素“ABC 2”将被忽略。

2.$('.a 类)。html(' 这是新文本【T1 ')

这将替换所有匹配元素的 html 内容。

 <div class="AClass"><b>This is new text</b></div>
<div class="AClass"><b>This is new text</b></div> 

jQuery html()示例

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

<style type="text/css">
	.htmlClass{
		padding:8px;
		border:1px solid blue;
		margin-bottom:8px;
	}
</style>

</head>
<body>
  <h1>jQuery html() example</h1>

  <div class="htmlClass">I'm going to replate by something ....</div>

  <div class="htmlClass">I'm going to replate by something 2....</div>

  <p>
  <button id="getHtml">html()</button>
  <button id="setHtml">html('xxx')</button>
  <button id="reset">reset</button>
  </p>

  <script type="text/javascript">

    $("#getHtml").click(function () {

	  alert($('.htmlClass').html());

    });

    $("#setHtml").click(function () {

	  $('.htmlClass').html('<b>This is a new text</b>');

    });

    $("#reset").click(function () {
	  location.reload();
    });

</script>
</body>
</html> 

http://web.archive.org/web/20220826132030if_/https://www.mkyong.com/wp-content/uploads/jQuery/jQuery-html-example.html

Try Demo

JQuery 在 WordPress-Solution 中不工作

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-is-not-working-in-wordpress-solution/

由于 WordPress 2 . x 版,jQuery 是一个内置的 Javascript 库,没有必要明确地将 jQuery 库包含到 WordPress 中。

问题

jQuery 在 WordPress 插件编写中不工作?当您尝试测试一个简单的 jQuery 效果时,如下所示

 $(document).ready(function(){
  alert('test');
}); 

它只是不工作,没有警告消息框弹出。相同的脚本在单个 HTML 页面中正常运行。这是怎么回事?jQuery 和 WordPress 之间有互操作性问题吗?

解决办法

在 WordPress 中, $() 语法总是被其他脚本库使用,并导致冲突问题和无法调用 jQuery 函数。你应该使用 jQuery() 来代替…

 jQuery(document).ready(function(){
  alert('test');
}); 

或者,您可以使用 noConflict()

 $j=jQuery.noConflict();

// Use jQuery via $j(...)
$j(document).ready(function(){
  alert('test');
}); 

P . Sjquery . no conflict();【http://wordpress.org/support/topic/141394】—

永远不要在 WordPress 插件中使用 jQuery 便捷函数 $() 。你必须使用 jQuery()jQuery.noConflict() 在 jQuery 和 WordPress 之间工作。

jQuery 键盘事件示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-keyboard-events-example/

jQuery 附带了三个键盘事件来捕获键盘活动——keyup()keydown()keypress()

  1. keyup()-当用户释放键盘上的一个键时触发。
  2. keydown()-当用户按下键盘上的一个键时触发。
  3. keypress()–当用户按下键盘上的一个键时激发。

一般来说, keydown() 类似于 keypress() 事件。实际上,按键()按键()事件之间几乎没有区别。

1.重复键

如果您按住某个键,keydown()事件会被触发一次,但是 keypress()事件会一直触发,直到您放开该键。

2.编辑关键点

键盘修饰键( ctrl、shift、alt… )将触发 keydown()事件,但不会触发 keypress()事件。

3.key code-ascii 代码

比如 A = 65,a= 97,请参考这个 ASCII 表图表

  1. keydown()和 keyup()将显示 a = 65,A = 65(不区分大小写-小写和大写将显示相同的值)。
  2. keypresss()将显示 a= 97,A=65(区分大小写-小写和大写将显示不同的值)。

如果您想在中捕获真正的字符键,请使用 keypress()事件。

FireFox 中不显示键码?

event.keyCode 在 FireFox 中不工作,但在 IE 中工作正常。要在 Firefox 中获得 event.keyCode ,你应该使用 event.which 来代替,jQuery 也推荐它。所以更好的方法应该是

 var keycode = (event.keyCode ? event.keyCode : event.which); 

你自己试试

 <html>
<head>

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

<style type="text/css">
	span{
		padding:8px;
		margin:8px;
		color:blue;
	}
	div{
		padding:8px;
		margin:8px;
	}
</style>

</head>
<body>
  <h1>jQuery keyup(), keydown() and keypress() example</h1>

<label>TextBox : </label>
<input id="textbox" type="text" size="50" />

<div>
<label>1\. keyup() Message :</label> <span id="msg-keyup"></span>
</div>

<div>
<label>2\. keydown() Message :</label><span id="msg-keydown"></span>
</div>

<div>
<label>3\. keypress() Message :</label><span id="msg-keypress"></span>
</div>

<script type="text/javascript">

$('#textbox').keyup(function(event){
	$('#msg-keyup').html('keyup() is triggered!, keyCode = ' 
              + event.keyCode + ' which = ' + event.which)
});

$('#textbox').keydown(function(event){
	$('#msg-keydown').html('keydown() is triggered!, keyCode = ' 
              + event.keyCode + ' which = ' + event.which)
});

$('#textbox').keypress(function(event){
	$('#msg-keypress').html('keypress() is triggered!, keyCode = ' 
              + event.keyCode + ' which = ' + event.which)
});

</script>
</body>
</html> 

http://web.archive.org/web/20190303105502if_/http://www.mkyong.com/wp-content/uploads/jQuery/jQuery-keyboard-events-example.html

Try Demojquery keyboard event

jQuery mousemove()示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-mousemove-example/

当鼠标在匹配的元素中移动时,触发 mousemove() 事件,当鼠标在匹配的元素周围移动每一个像素时,保持触发该事件。

比如一个 300 x 200 的大 div 框,id 为“bigbigbox”。

 <style type="text/css">
	#bigbigbox{
		margin:16px 16px 16px 48px;
		border:1px groove blue;
		background-color : #BBBBBB;
		width:300px;
		height:200px;
	}
	#msg{
		color:#800000;
	}
</style>

<div id="bigbigbox"></div> 

mousemove() 事件绑定到这个大盒子上。

 $('#bigbigbox').mousemove(function(event) {
  var msg = 'mousemove() position - x : ' + event.pageX + ', y : ' + event.pageY;
}); 

当鼠标在 div " bigbigbox 元素中移动时, mousemove() 事件被触发,您可以使用事件。PageXevent.pageY 跟踪鼠标在框内的位置。

用例?

在哪里应用这个 mousemove() 事件?知道的请建议一些:)

你自己试试

 <html>
<head>

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

<style type="text/css">
	#bigbigbox{
		margin:16px 16px 16px 48px;
		border:1px groove blue;
		background-color : #BBBBBB;
		width:300px;
		height:200px;
	}
	#msg{
		color:#800000;
	}
</style>

</head>
<body>
  <h1>jQuery mousemove example</h1>

  <div id="bigbigbox"></div>

  <p id="msg"></p>

<script type="text/javascript">

var i=0;
$('#bigbigbox').mousemove(function(event) {
  var msg = 'mousemove() position - x : ' + event.pageX + ', y : '
                + event.pageY + ' [counter] : ' + i++;
  $('#msg').text(msg);
});

</script>
</body>
</html> 

http://web.archive.org/web/20190210095225if_/http://www.mkyong.com/wp-content/uploads/jQuery/jQuery-mousemove-example.html

Try Demojquery mouse movement (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190210095225/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

jQuery mouseup()和 mousedown()示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-mouseup-and-mousedown-example/

jQuery mouseup()mousedown() 事件都是不言自明的,用于验证鼠标按钮被按下或释放。

你自己试试

 <html>
<head>

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

<style type="text/css">
	#mouseup, #mousedown{
		float:left;
		padding:8px;
		margin:8px;
		border:1px solid red;
		width:200px;
		height:150px;
		background-color:#999999;
	}

</style>

</head>

<body>

<h1>jQuery mouseup() and mousedown() examples</h1>

<div id="mouseup">
	<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script><h2>mouseup</h2>
	 Fire when mouse over this element and released the mouse button.
</div>

<div id="mousedown">
	<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script><h2>mousedown</h2>
	Fire when mouse over this element and pressed on the mouse button.
</div>

<script type="text/javascript">

$('#mouseup').mouseup(function(){
	$('#mouseup').slideUp();
});

$('#mousedown').mousedown(function(){
	$('#mousedown').fadeOut();
});

</script>

</body>
</html> 

http://web.archive.org/web/20190214232535if_/http://www.mkyong.com/wp-content/uploads/jQuery/jQuery-mouseup-mousedown-example.html

Try Demojquery mouse event (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190214232535/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

jQuery next()示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-next-example/

next()函数用于获取匹配元素集中紧随其后的兄弟元素。只有下面的同级元素被选择,它的子元素将被忽略。

这个 next()函数允许通过“选择器”对其进行过滤。例如,next('div ')用于获取紧随其后的仅是

元素的兄弟元素。

jQuery next()示例

 <html>
<head>
<style type="text/css">
  div,p { 
  	width:110px; 
	height:40px; 
	margin:2px 8px 64px 8px;
        float:left; 
	border:1px blue solid; 
  }
 </style>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
</head>
<body>
  <h1>jQuery next() example</h1>

  <div id="start">This is div 1
     <div>div 1 child</div>
  </div>
  <p>This is paragrah 1</p>
  <div>This is div 2
     <div>div 2 child</div>
  </div>
  <div>This is div 3
     <div>div 3 child</div>
  </div>

  <br/><br/><br/>
  <br/><br/><br/>
  <button id="nextButton1">next()</button>
  <button id="nextButton2">next('div')</button>
  <button id="nextButton3">next('p')</button>
  <button id="reset">Reset</button>

<script type="text/javascript">

    var $currElement = $("#start");
    $currElement.css("background", "red");

    $("#nextButton1").click(function () {

	  if(!$currElement.next().length){
	  	alert("No element found!");
		return false;	
	  }

	  $currElement = $currElement.next();

      $("div,p").css("background", "");
      $currElement.css("background", "red");
    });

    $("#nextButton2").click(function () {

	  if(!$currElement.next('div').length){
	  	alert("No element found!");
		return false;	
	  }

	  $currElement = $currElement.next('div');

      $("div,p").css("background", "");
      $currElement.css("background", "red");
    });

    $("#nextButton3").click(function () {

	  if(!$currElement.next('p').length){
	  	alert("No element found!");
		return false;	
	  }

	  $currElement = $currElement.next('p');

      $("div,p").css("background", "");
      $currElement.css("background", "red");
    });

	$("#reset").click(function () {
	  location.reload();
    });

</script>
</body>
</html> 

http://web.archive.org/web/20190310093115if_/http://www.mkyong.com/wp-content/uploads/jQuery/jQuery-next-example.html

Try Demojquery jquery traversing (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190310093115/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

jQuery–非选择器示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-not-selector-example/

在 jQuery 中,使用“而不是来选择所有与选择器不匹配的元素。

例子

  1. $('p:不是(。class-p1)')–选择由

    匹配的、没有“class-P1”类名的所有元素。

  2. $(' Li:NOT(:only-child)')–选择与

  3. 匹配的所有元素,这些元素不是其父元素的唯一子元素。

  4. $(' Li:NOT(:first-child)')–选择所有与匹配但不是其父元素的第一个子元素的元素。

jQuery 示例

一个简单的例子展示了 jQuery 的“not”选择器的用法,点击按钮来玩转它。

 <html>
<head>
<title>jQuery not example</title>

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

<body>

<h1>jQuery not example</h1>

<ul class="class-ul">
	<li>class-ul - #1</li>
	<li>class-ul - #2</li>
	<li>class-ul - #3</li>
	<li>class-ul - #4</li>
	<li>class-ul - #5</li>
</ul>

<ul id="id1">
	<li>id1 - #1</li>
</ul>

<p class="class-p1">
	class - #p1
</p>

<p class="class-p2">
	class - #p2
</p>

<button>p:not(.class-p1)</button>
<button>li:not(:only-child)</button>
<button>li:not(:first-child)</button>

<script type="text/javascript">
    $("button").click(function () {
      var str = $(this).text();
      $("li,p").css("background", "white");
      $(str).css("background", "coral");
    });
</script>

</body>
</html> 

http://web.archive.org/web/20190224163755if_/http://www.mkyong.com/wp-content/uploads/jQuery/jQuery-not-example.html

Try Demojquery jquery selector (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190224163755/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

jQuery–唯一子选择器示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-only-child-selector-example/

唯一子元素用于选择所有作为其父元素唯一子元素的元素。

例子

  1. $(':only-child ')–选择作为其父元素的唯一子元素的所有元素。
  2. $(' Li:only-child ')–选择与
  3. 匹配的所有元素,这些元素是其父元素的唯一子元素。

jQuery 示例

在这个例子中,当按钮被点击时,只有<li>DEF #1</li>将被匹配并动态改变其背景颜色,因为它是其父的唯一子。

 <html>
<head>
<title>jQuery only child example</title>

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

<body>

<h1>jQuery only child example</h1>

<ul>
	<li>ABC #1</li>
	<li>ABC #2</li>
	<li>ABC #3</li>
	<li>ABC #4</li>
	<li>ABC #5</li>
</ul>

<ul>
	<li>DEF #1</li>
</ul>

<ul>
	<li>GHI #1</li>
	<li>GHI #2</li>
</ul>

<button>li:only-child</button>

<script type="text/javascript">
    $("button").click(function () {
      var str = $(this).text();
      $("li").css("background", "white");
      $(str).css("background", "coral");
    });
</script>

</body>
</html> 

http://web.archive.org/web/20190224163435if_/http://www.mkyong.com/wp-content/uploads/jQuery/jQuery-only-child.html

Try Demojquery jquery selector (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190224163435/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

jQuery prepend()和 prependTo()示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-prepend-and-prependto-example/

jQuery prepend()prependTo() 方法都在执行相同的任务,在匹配元素的内容之前添加一个文本或 html 内容。主要的区别在于语法。

举个例子,

 <div class="box">I'm a big box</div>
<div class="box">I'm a big box 2</div> 

1.$('选择器')。前置(“新文本”);

 $('.box').prepend("<div class='newbox'>I'm new box by prepend</div>"); 

2.$('新文本')。前置 to(' selector ');

 $("<div class='newbox'>I'm new box by prependTo</div>").prependTo('.box'); 

结果

上面两种方法做的是同样的任务,但是语法不同,在 prepend()prependTo() 之后的新内容将变成
这是一个非常通用的工具。对于任何你想要一个滑动条的网站来说,这就是方法。如果你看看任何一个大网站,比如像 www.o2.co.uk/这样的网站或者一个电影网站,你很可能会看到一个正在使用的网站。这是一个很好的方式,让图像旋转看起来很聪明,并抓住观众的眼睛。它给你的网站增加了一个不同的维度,这将使它真正脱颖而出。

 <div class="box">
   <div class='newbox'>I'm new box by prepend</div>
   I'm a big box
</div>

<div class="box">
   <div class='newbox'>I'm new box by prepend</div>
   I'm a big box 2
</div> 

你自己试试

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

<style type="text/css">
	.box{
		padding:8px;
		border:1px solid blue;
		margin-bottom:8px;
		width:300px;
		height:100px;
	}
	.newbox{
		padding:8px;
		border:1px solid red;
		margin-bottom:8px;
		width:200px;
		height:50px;
	}
</style>

</head>
<body>
  <h1>jQuery prepend() and prependTo example</h1>

  <div class="box">I'm a big box</div>

  <div class="box">I'm a big box 2</div>

  <p>
  <button id="prepend">prepend()</button>
  <button id="prependTo">prependTo()</button>
  <button id="reset">reset</button>
  </p>

<script type="text/javascript">

    $("#prepend").click(function () {

	  $('.box').prepend("<div class='newbox'>I'm new box by prepend</div>");

    });

    $("#prependTo").click(function () {

	  $("<div class='newbox'>I'm new box by prependTo</div>").prependTo('.box');

    });

    $("#reset").click(function () {
	  location.reload();
    });

</script>
</body>
</html> 

http://web.archive.org/web/20220826132030if_/https://www.mkyong.com/wp-content/uploads/jQuery/jQuery-prepend-prependTo-example.html

Try Demo

jQuery prev()示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-prev-example/

prev()函数用于获取匹配元素集中的前一个兄弟元素。只有前一个同级的元素被选择,它的子元素将被忽略。

这个 prev()函数允许通过“选择器”对其进行过滤。例如,prev('div ')用于获取仅是

元素的前一个兄弟元素。

jQuery prev()示例

 <html>
<head>
<style type="text/css">
  div,p { 
  	width:110px; 
	height:40px; 
	margin:2px 8px 2px 8px;
        float:left; 
	border:1px blue solid; 
  }
 </style>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
</head>
<body>
  <h1>jQuery prev() example</h1>

  <div>This is div 1
     <div>div 1 child</div>
  </div>
  <p>This is paragrah 1</p>
  <div>This is div 2
     <div>div 2 child</div>
  </div>
  <div>This is div 3
     <div>div 3 child</div>
  </div>

  <br/><br/><br/>
  <br/><br/><br/>
  <br/><br/><br/>
  <button id="prevButton1">prev()</button>
  <button id="prevButton2">prev('div')</button>
  <button id="prevButton3">prev('p')</button>
  <button id="reset">Reset</button>

<script type="text/javascript">

    var $currElement = $("#start");
    $currElement.css("background", "red");

    $("#prevButton1").click(function () {

	  if(!$currElement.prev().length){
	  	alert("No element found!");
		return false;	
	  }

	  $currElement = $currElement.prev();

      $("div,p").css("background", "");
      $currElement.css("background", "red");
    });

    $("#prevButton2").click(function () {

	  if(!$currElement.prev('div').length){
	  	alert("No element found!");
		return false;	
	  }

	  $currElement = $currElement.prev('div');

      $("div,p").css("background", "");
      $currElement.css("background", "red");
    });

    $("#prevButton3").click(function () {

	  if(!$currElement.prev('p').length){
	  	alert("No element found!");
		return false;	
	  }

	  $currElement = $currElement.prev('p');

      $("div,p").css("background", "");
      $currElement.css("background", "red");
    });

    $("#reset").click(function () {
	  location.reload();
    });

</script>
</body>
</html> 

http://web.archive.org/web/20190214224036if_/http://www.mkyong.com/wp-content/uploads/jQuery/jQuery-prev-example.html

Try Demojquery jquery traversing (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190214224036/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

jQuery resize()示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-resize-example/

jQuery resize() 事件在浏览器大小改变时被触发,该事件只绑定到 $(窗口)

 $(window).resize(function () {
	$('#msg').text('Browser (Width : ' + $(window).width() 
	+ ' , Height :' + $(window).height() + ' )');
}); 

要获得浏览器的宽度和高度细节,使用 \((window)。width()** 和 **\)(窗口)。身高()

你自己试试

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

<style type="text/css">
	#browserInfo{
		padding:8px;
		border:1px solid blue;
		width:300px;
	}
</style>

</head>
<body>
  <h1>jQuery resize() example</h1>

  <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script><h2>Try resize this browser</h2>

  <div id="browserInfo">
  </div>

<script type="text/javascript">

   $('#browserInfo').text('Browser (Width : '
                + $(window).width() + ' , Height :' + $(window).height() + ' )');

    $(window).resize(function () {
		$('#browserInfo').text('Browser (Width : ' + $(window).width() 
                                 + ' , Height :' + $(window).height() + ' )');
    });

</script>
</body>
</html> 

http://web.archive.org/web/20190213135544if_/http://www.mkyong.com/wp-content/uploads/jQuery/jQuery-resize-example.html

Try Demobrowser event jquery (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190213135544/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

jQuery show()和 hide()示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-show-and-hide-example/

jQuery show()和 hide()是最常用的效果。

  1. show()–显示匹配的元素。
  2. Hide()–隐藏匹配的元素。

这两种方法都支持将持续时间作为参数:慢、快或精确的毫秒。如果省略此参数,则应用默认的 400 毫秒。

你自己试试

 <html>
<head>

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

<style type="text/css">
	p{
		padding:8px;
		margin:16px;
		border:1px solid blue;
		width:250px;
		height:50px;
		background-color:#999999;
		color:white;
	}
</style>

</head>

<body>

<h1>jQuery show() and hide() example</h1>

<p>Hello, this show() and hide() example</p>

<button id=show>show()</button>
<button id=hide>hide()</button>
<button id=reset>Reset</button>

<script type="text/javascript">

$("#show").click(function () {
   $("p").show('fast');
});

$("#hide").click(function () {
   $("p").hide(1000);
});

$("#reset").click(function(){
	location.reload();
});
</script>

</body>
</html> 

http://web.archive.org/web/20190608151308if_/http://www.mkyong.com/wp-content/uploads/jQuery/jQuery-show-hide-example.html

Try Demojquery jquery effects (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190608151308/https://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

jQuery slideUp()、slideDown()和 slideToggle()示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-slideup-slidedown-and-slidetoggle-example/

jQuery 提供了三种简便的方法来轻松创建滑动效果。

  1. slide up()–隐藏具有向上滑动效果的匹配元素。
  2. slide down()–以向下滑动的效果显示匹配的元素。
  3. slide toggle()–如果匹配的元素被显示,它将以向上滑动的效果隐藏;如果隐藏,它将以向下滑动的效果显示。

以上三种方法都支持持续时间作为参数:慢速、快速或精确的毫秒。如果省略此参数,则应用默认的 400 毫秒。

你自己试试

 <html>
<head>

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

<style type="text/css">
	.slideDownbox, .slideUpbox, .slideTogglebox{
		float:left;
		padding:8px;
		margin:16px;
		border:1px solid red;
		width:200px;
		height:50px;
		background-color:#000000;
		color:white;
	}
	.clear{
		clear:both;
	}
</style>

</head>

<body>

<h1>jQuery slideUp(), slideDown() and slideToggle() example</h1>

<div class="clear">
	<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script><h2>slideDown() example</h2>

	<div class="slideDownbox">
		Click me - slideDown()
	</div>

	<div class="slideDownbox">
		Click me - slideDown()
	</div>
</div>

<div class="clear">
	<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script><h2>slideUp() example</h2>

	<div class="slideUpbox">
		Click me - slideUp()
	</div>

	<div class="slideUpbox">
		Click me - slideUp()
	</div>
</div>

<div class="clear">
	<h2>slideToggle() example</h2> <button id=slideToggle>slideToggle()</button>
	<br/>
	<div class="slideTogglebox">
	 	slideToggle()
	</div>

	<div class="slideTogglebox">
	 	slideToggle()
	</div>

</div>

<br/><br/>

<div class="clear">
	<button id=reset>Reset</button>
</div>

<script type="text/javascript">

$(".slideDownbox").click(function () {
   $(this).hide().slideDown('slow');
});

$(".slideUpbox").click(function () {
   $(this).slideUp(2000);
});

$("#slideToggle").click(function () {
   $('.slideTogglebox').slideToggle();
});

$("#reset").click(function(){
	location.reload();
});
</script>

</body>
</html> 

http://web.archive.org/web/20190304003356if_/http://www.mkyong.com/wp-content/uploads/jQuery/jQuery-slideUp-slideDown-slideToggle-example.html

Try Demojquery jquery effects (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190304003356/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

jQuery text()示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-text-example/

jQuery text() 用于获取所有匹配元素的内容;而text(‘新文本’)用于替换或设置所有匹配元素的文本内容。

举个例子,

 <div class="TClass">TEXT 1</div>
<div class="Tlass">TEXT 2</div> 

1. $(‘.TClass’).text()

这将组合所有匹配元素的内容,得到“ TEXT 1 TEXT 2 ”作为返回。与 html()不同,只获取第一个元素的内容。

2.$('.t class’)。文本('这是新文本【T1 ')

所有 html 标签 <和>将被替换为&lt;以及&gt;,将不应用 html 效果。

 <div class="AClass"><b>This is new text</b></div>
<div class="AClass"><b>This is new text</b></div> 

jQuery text()示例

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

<style type="text/css">
	.textClass{
		padding:8px;
		border:1px solid blue;
		margin-bottom:8px;
	}
</style>

</head>
<body>
  <h1>jQuery text() example</h1>

  <div class="textClass">Text ABC ....</div>

  <div class="textClass">Text ABC 2....</div>

  <p>
  <button id="getText">text()</button>
  <button id="setText">text('xxx')</button>
  <button id="reset">reset</button>
  </p>
<script type="text/javascript">

    $("#getText").click(function () {

	  alert($('.textClass').text());

    });

    $("#setText").click(function () {

	  $('.textClass').text('<b>This is a new text</b>');

    });

    $("#reset").click(function () {
	  location.reload();
    });

</script>
</body>
</html> 

http://web.archive.org/web/20220826132030if_/https://www.mkyong.com/wp-content/uploads/jQuery/jQuery-text-example.html

Try Demo

jQuery toggleClass 示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-toggleclass-example/

toggleClass() 方法意味着如果匹配的元素没有类名,那么添加它;如果匹配的元素已经有了类名,那么删除它。

让我们看一个例子,一个简单的“p”标签。

 <p>This is paragraph</p> 

调用 $('p ')。toggleClass('highlight') ,它会给' p '标签添加一个高亮类。

 <p class="highlight">This is paragraph</p> 

调用 $('p ')。toggleClass('highlight') 再次,它将从' p '标记中删除高亮显示的类。

 <p>This is paragraph</p> 

toggleClass()也等效于下面的 jQuery 代码。

 if ($('p').is('.highlight')) {
    $('p').removeClass('highlight');
}
else{
    $('p').addClass('highlight');
} 

jQuery toggleClass 示例

 <html>
<head>
<style type="text/css">
  .highlight { 
  	background:blue;
  }
 </style>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
</head>
<body>
  <h1>jQuery toggleClass example</h1>

  <p>This is paragraph1</p>
  <p id="para2">This is paragraph2 (toggleClass effect)</p>
  <p>This is paragraph3</p>
  <p id="para4">This is paragraph4 (add/remove effect)</p>

  <button id="toggleClass">toggle class</button>
  <button id="addremoveClass">Add/Remove class</button>

<script type="text/javascript">

    $("#toggleClass").click(function () {

	  $('#para2').toggleClass('highlight');

    });

    $("#addremoveClass").click(function () {

	  if ($('#para4').is('.highlight')) {

	      $('#para4').removeClass('highlight');

	  }
	  else{

	      $('#para4').addClass('highlight');

	  }

    });

</script>
</body>
</html> 

http://web.archive.org/web/20220826132031if_/https://www.mkyong.com/wp-content/uploads/jQuery/jQuery-toggleClass-example.html

Try Demo

jQuery 教程

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/tutorials/jquery-tutorials/

jQuery Tutorials

jQuery 是一个 24k 的小型 JavaScript 库,提供了一个极其简单和强大的选择器来选择 HTML 页面中你想要的任何东西。此外,它还提供了许多用于 DOM 遍历、事件处理(表单、浏览器、鼠标、键盘)、动画效果和 Ajax 的创新方法来简化 web 开发。它肯定会改变你编写 JavaScript 的方式。

快乐学习 jQuery。🙂

jQuery 快速入门

jQuery 简单用法示例。

  • 一个简单的 jQuery Hello World 示例,展示了如何下载 jQuery 库并将其包含到 HTML 页面中。
  • 在 JavaScript 和 jQuery 中调用函数
    演示了在 JavaScript 和 jQuery 中调用函数的不同方式,以创建页面加载后的动态内容。
  • 从谷歌代码
    加载 jQuery 这个例子展示了如何从谷歌加载 jQuery 库以及为什么要这样做。

jQuery 实际例子

一些 jQuery 的实际用法和例子。

jQuery 选择器

在 jQuery 中选择您想要的任何内容。

jQuery 属性选择器

jQuery 中关于属性选择器的一切。

  • 属性选择器[ ]
    8 属性选择器示例展示了属性选择器与 jQuery 的使用。

jQuery DOM 遍历

jQuery 中关于元素遍历的一切。

jQuery DOM 操作

jQuery 中关于 dom 操作的一切。

jQuery HTML 表单

jQuery 中关于 HTML 表单元素的一切。

jQuery 效果

jQuery 中关于内置效果的一切。

jQuery 事件处理

jQuery 中关于事件处理的一切。

jQuery 浏览器事件

jQuery 中关于浏览器事件的一切。

jQuery 鼠标事件

jQuery 中关于鼠标事件的一切。

jQuery 键盘事件

jQuery 中关于键盘事件的一切。

  • 键盘事件示例
    键盘事件——keyup()、keydown()和 keypress()示例。
  • 这个例子展示了如何用 jQuery 键盘事件来检查一个“回车键”是否被按下。
  • 检测复制、粘贴和剪切行为
    如何用 jQuery 检测复制、粘贴和剪切行为。

jQuery 常见问题

一些常见的 jQuery 问题及解决方案。

jQuery 引用

Tags : jquery tutorials

jQuery–通用*选择器示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-universal-selector-example/

通用* 选择器用于选择所有元素,一切。

例子

  1. $('* '):选择文档中的所有元素。
  2. $('div > *):选择作为元素的子元素的所有元素。

总的来说,单独使用通用没有意义,至少我想不出任何用例。但是,它总是被用来与其他元素组合形成一个新的自定义选择器表达式。

jQuery 示例

一个简单的例子展示了 jQuery universal *选择器的用法。

 <html>
<head>
<title>jQuery universal example</title>

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

<style type="text/css">
	div{
		padding:8px;
	}
</style>
</head>

<body>

<h1>jQuery universal example</h1>

<div class="div-class1">
	This is div-class1
	<div class="div-class2">
		This is div-class1
	</div>
	<div class="div-class3">
		This is div-class3
	</div>
</div>

<br/><br/>
<button>*</button>
<button>div > *</button>
<button id="refresh">Refresh</button>

<script type="text/javascript">
    $("button").click(function () {
       var str = $(this).text();
       $(str).css("border", "1px solid #ff0000");
    });

    $('#refresh').click(function() {
    	location.reload();
    });

</script>

</body>
</html> 

http://web.archive.org/web/20190224162548if_/http://www.mkyong.com/wp-content/uploads/jQuery/jQuery-universal-example.html

Try Demojquery jquery selector (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190224162548/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

jQuery wrap()示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jquery/jquery-wrap-example/

jQuery wrap() 用于将 HTML 元素包装在每个匹配的元素周围。

举个例子,

 <div class="innerBox">Ip man vs Iron man</div>
<div class="innerBox">Ip man 2 vs Iron man 2</div> 

用包含类名“wrapBox”的 div 标记包装它。

 $('.innerBox').wrap("<div class='wrapBox'></div>"); 

新内容将变成:

 <div class='wrapBox'>
   <div class="innerBox">Ip man vs Iron man</div>
</div>

<div class='wrapBox'>
   <div class="innerBox">Ip man 2 vs Iron man 2</div>
</div> 

警告
不要用 html 内容换行

 $('.innerBox').wrap("<div class='wrapBox'>TESTING</div>"); 

你希望有下文吗?

 <div class='wrapBox'>TESTING
   <div class="innerBox">Ip man vs Iron man</div>
</div> 

不,结果将是完全替换。wrap 只支持 html 标签,不支持内容。

 <div class='wrapBox'>TESTING</div> 

你自己试试

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

<style type="text/css">
	.innerBox{
		padding:8px;
		border:1px solid blue;
		margin:8px;
	}
	.wrapBox{
		padding:8px;
		border:1px solid red;
		margin:8px;
	}
</style>

</head>
<body>
  <h1>jQuery wrap() example</h1>

  <div class="innerBox">Ip man vs Iron man</div>

  <div class="innerBox">Ip man 2 vs Iron man 2</div>

  <p>
  <button id="wrapButton">wrap()</button>
  <button id="reset">reset</button>
  </p>

<script type="text/javascript">

    $("#wrapButton").click(function () {

	  $('.innerBox').wrap("<div class='wrapBox'></div>");

    });

	$("#reset").click(function () {
	  location.reload();
    });

</script>
</body>
</html> 

http://web.archive.org/web/20220826132031if_/https://www.mkyong.com/wp-content/uploads/jQuery/jQuery-wrap-example.html

Try Demo

JSF 2.0 + Ajax hello world 示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jsf2/jsf-2-0-ajax-hello-world-example/

在 JSF 2.0 中,编写 Ajax 就像编写普通的 HTML 标签一样,非常简单。在本教程中,您将重构最后一个 JSF 2.0 hello world 示例,这样,当按钮被点击时,它将发出一个 Ajax 请求,而不是提交整个表单。

1.JSF 2.0 页面

支持 Ajax 的 JSF 2.0 xhtml 页面。

helloAjax.xhtml

 <?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:f="http://java.sun.com/jsf/core"      
      xmlns:h="http://java.sun.com/jsf/html">

    <h:body>
    	<h2>JSF 2.0 + Ajax Hello World Example</h2>

    	<h:form>
    	   <h:inputText id="name" value="#{helloBean.name}"></h:inputText>
    	   <h:commandButton value="Welcome Me">
    		 <f:ajax execute="name" render="output" />
    	   </h:commandButton>

    	   <h2><h:outputText id="output" value="#{helloBean.sayWelcome}" /></h2>	
    	</h:form>

    </h:body>
</html> 

在这个例子中,它使按钮可 Ajax 化。当按钮被点击时,它将向服务器发出一个 Ajax 请求,而不是提交整个表单。

 <h:commandButton value="Welcome Me">
    <f:ajax execute="name" render="output" />
</h:commandButton>
<h:outputText id="output" value="#{helloBean.sayWelcome}" /> 

< f:ajax > 标签中:

  1. execute = " name "–表示 Id 为" name 的表单组件将被发送到服务器进行处理。对于多个组件,只需用空格将其分开,例如execute = " name another id another xxid "。在这种情况下,它将提交文本框值。
  2. render = " output "–Ajax 请求后,会刷新 id 为" output "的组件。在这种情况下,Ajax 请求完成后,会刷新 < h:outputText > 组件。

2.ManagedBean

参见完整的 #{helloBean} 示例。

地狱篇. java

 package com.mkyong.common;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import java.io.Serializable;

@ManagedBean
@SessionScoped
public class HelloBean implements Serializable {

	private static final long serialVersionUID = 1L;

	private String name;

	public String getName() {
	   return name;
	}
	public void setName(String name) {
	   this.name = name;
	}
	public String getSayWelcome(){
	   //check if null?
	   if("".equals(name) || name ==null){
		return "";
	   }else{
		return "Ajax message : Welcome " + name;
	   }
	}
} 

3.它是如何工作的?

访问网址:http://localhost:8080/Java server faces/hello Ajax . JSF

jsf2-ajax-hello-world-example-1

当单击按钮时,它发出一个 Ajax 请求,并将文本框值传递给服务器进行处理。之后刷新 outputText 组件,通过 getSayWelcome() 方法显示值,没有任何“翻页效果”。

jsf2-ajax-hello-world-example-2

下载源代码

Download it – JSF-2-Ajax-Hello-World-Example.zip (8KB)Tags : ajax hello world jsf2

相关文章

JSF 2.0 和资源包示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jsf2/jsf-2-0-and-resource-bundles-example/

在本教程中,我们将演示在 JSF 2.0 中使用资源包来显示消息。出于可维护性的考虑,总是建议将所有消息放在属性文件中,而不是直接在页面中硬编码消息。

1.属性文件

创建一个属性文件,包含页面的消息,并把它放到项目的资源文件夹中,见下图

消息.属性

 message = This is "message"
message.test1 = This is "message.test1"
message.test2 = This is "<h2>message.test3</h2>"
message.test3 = This is "&lt;h2&gt;message.test4&lt;/h2&gt;"
message.param1 = This is "message.param1" - {0}
message.param2 = This is "message.param2" - {0} and {1} 

项目文件夹结构。

jsf2-resource-bundles-folder

2.使用资源包

将属性文件加载到 JSF 2.0 中有两种方法。

1。全局资源包
全局加载属性文件,这样所有的 jsf 页面都可以访问消息。您可以创建一个“ faces-config.xml ”文件,并显式声明属性文件。

faces-config.xml

 <?xml version="1.0" encoding="UTF-8"?>
<faces-config

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
    version="2.0">
     <application>
	  <resource-bundle>
		<base-name>com.mkyong.messages</base-name>
		<var>msg</var>
	   </resource-bundle>
     </application>
</faces-config> 

2。本地资源包
用于本地加载属性文件,或者仅用于指定页面。在需要访问 messages.properties 中消息的页面中声明 < f:loadBundle / > 标签。

 <f:loadBundle basename="com.mkyong.messages" var="msg"/> 

3.JSF 2.0 页

在这种情况下, messages.properties 文件被命名为“ msg ,要访问该消息,只需使用“ msg.key ”。

hello.xhtml

 <?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:f="http://java.sun.com/jsf/core"      
      xmlns:h="http://java.sun.com/jsf/html">

    <h:body>
      <h2>JSF 2.0 and Resource Bundles Examples</h2>
      <ol>

   	<li><h:outputText value="#{msg.message}" /></li>

    	<li><h:outputText value="#{msg['message.test1']}" /></li>

    	<li><h:outputText value="#{msg['message.test2']}" /></li>
    	<li><h:outputText value="#{msg['message.test2']}" escape="false" /></li>

    	<li><h:outputText value="#{msg['message.test3']}" /></li>
    	<li><h:outputText value="#{msg['message.test3']}" escape="false" /></li>

    	<li>
 	     <h:outputFormat value="#{msg['message.param1']}">
		<f:param value="param0" />
	     </h:outputFormat>
	</li>
	 <li>
	     <h:outputFormat value="#{msg['message.param2']}">
	    	<f:param value="param0" />
	    	<f:param value="param1" />
	     </h:outputFormat>
	  </li>
    	</ol>
    </h:body>
</html> 

4.它是如何工作的?

例 1
访问消息的正常方式。

 <h:outputText value="#{msg.message}" />

//properties file
message = This is "message" 

例 2
对于有一个点“.”的键作为名字,你不能用正常的方式 #{msg.message.test1} ,那是不行的。而是应该用类似 #{msg['message.test1']} 这样的括号。

 <h:outputText value="#{msg['message.test1']}" />

//properties file
message.test1 = This is "message.test1" 

例 3
要在消息中显示 HTML 标签,只需添加“ escape 属性并将其设置为 false 即可。

 <h:outputText value="#{msg['message.test2']}" />
<h:outputText value="#{msg['message.test2']}" escape="false" />
<h:outputText value="#{msg['message.test3']}" />
<h:outputText value="#{msg['message.test3']}" escape="false" />

//properties file
message.test2 = This is "<h2>message.test3</h2>"
message.test3 = This is "&lt;h2&gt;message.test4&lt;/h2&gt;" 

例 4
对于一个参数消息,只需使用 < h:outputFormat / >< f:param / > 标签即可。

 <h:outputFormat value="#{msg['message.param1']}">
   <f:param value="param0" />
</h:outputFormat>
<h:outputFormat value="#{msg['message.param2']}">
   <f:param value="param0" />
   <f:param value="param1" />
</h:outputFormat>

//properties file
message.param1 = This is "message.param1" - {0}
message.param2 = This is "message.param2" - {0} and {1} 

5.演示

URL:http://localhost:8080/Java server faces/hello . JSF

jsf2-resource-bundles-example

下载源代码

Download it – JSF-2-Resource-Bundles-Example.zip (8KB)Tags : jsf2 resource bundle

JSF 2.0 : 包含一个未知的 id

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jsf2/jsf-2-0-f-ajax-contains-an-unknown-id/

问题

一个支持 Ajax 的 JSF 按钮…

 <h:outputText id="output" value="#{helloBean.sayWelcome}" />
<h:form>    	
   <h:inputText id="name" value="#{helloBean.name}"></h:inputText>
   <h:commandButton value="Welcome Me">
   	 <f:ajax execute="name" render="output" />
   </h:commandButton>
</h:form> 

当显示此页面时,它会提示以下错误消息

 javax.faces.FacesException: <f:ajax> contains an unknown id 'output'
                             - cannot locate it in the context of the component j_idt8 

显然,‘输出的 id 没有找到,但是已经在<h:output text id = " output "/>中明确声明了?

解决办法

在 JSF 2.0 中, < f:ajax > 标签要求在同一个表单级别内进行“渲染”输出。<h:output text id = " output "/>标签应该在表单内移动。

 <h:form>    	
   <h:outputText id="output" value="#{helloBean.sayWelcome}" />
   <h:inputText id="name" value="#{helloBean.name}"></h:inputText>
   <h:commandButton value="Welcome Me">
   	 <f:ajax execute="name" render="output" />
   </h:commandButton>
</h:form> 

参考

  1. JSF 2.0 + Ajax hello world 示例

ajax jsf2

JSF 2.0 hello world 示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jsf2/jsf-2-0-hello-world-example/

在本教程中,我们将向您展示如何开发一个 Java server Faces(JSF)2.0 hello world 示例,展示了 JSF 2.0 依赖项列表、基本注释和配置。

项目环境

这个 JSF 2.0 示例是使用以下工具和技术构建的

  1. JSF 2.1.7
  2. maven3
  3. Eclipse 3.6
  4. JDK 1.6
  5. Tomcat 6.0.26

首先,查看最终的项目结构,以防您对以后应该在哪里创建相应的文件或文件夹感到困惑。

jsf2-hello-world-example

1.JSF 2.0 依赖项

Maven 中央库只有 JSF 1.2 版本,要获得 JSF 2.0 ,可能需要从Java.net 库下载。
maven 中央库是 JSF 库更新到 2.1.7。不再需要以前的 Java.net 存储库。

对于大多数 Java EE 应用服务器中的 Glassfish
这样的 Java EE 应用服务器来说,它内置了对 JSF 2.0 的支持,所以你需要下载单个 JSF API 进行开发。

 ...
<dependencies>
  <dependency>
    <groupId>javax.faces</groupId>
    <artifactId>jsf-api</artifactId>
    <version>2.0</version>
    <scope>provided</scope>
  </dependency>
</dependencies>
<repositories>
  <repository>
    <id>java.net.m2</id>
    <name>java.net m2 repo</name>
    <url>http://download.java.net/maven/2</url>
  </repository>
</repositories>
... 

对于像 Tomcat
这样简单的 servlet 容器来说,这有点麻烦,你需要下载下面的依赖项。

文件:pom.xml

 <project  
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
        http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.mkyong.common</groupId>
	<artifactId>JavaServerFaces</artifactId>
	<packaging>war</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>JavaServerFaces Maven Webapp</name>
	<url>http://maven.apache.org</url>

	<dependencies>

		<dependency>
			<groupId>com.sun.faces</groupId>
			<artifactId>jsf-api</artifactId>
			<version>2.1.7</version>
		</dependency>
		<dependency>
			<groupId>com.sun.faces</groupId>
			<artifactId>jsf-impl</artifactId>
			<version>2.1.7</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
		</dependency>
                <!-- Tomcat 6 need this -->
		<dependency>
			<groupId>com.sun.el</groupId>
			<artifactId>el-ri</artifactId>
			<version>1.0</version>
		</dependency>

	</dependencies>

	<build>
		<finalName>JavaServerFaces</finalName>

		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.1</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project> 

Note
For more detail about the JSF 2.0 dependencies, please refer to this official JSF 2.0 release note.Warning
The el-ri.jar is an arguable dependency in the Tomcat servlet container, even it’s not stated in the release note, but you need this library to solve the “JSP version of the container is older than 2.1…” error message.Updated – 21-10-2010
This “el-ri.jar” is too old, it’s recommended to use the latest “el-impl-2.2.jar”, from Java.net

 <dependency>
	  <groupId>org.glassfish.web</groupId>
	  <artifactId>el-impl</artifactId>
	  <version>2.2</version>
     </dependency> 

Updated–25-07-2012Tomcat 7 中不再需要这个el-ri.jar依赖项。

2.JSF 2.0 托管 Bean

Java bean 或 JSF 管理的 bean,具有存储用户数据的名称属性。在 JSF,托管 bean 意味着可以从 JSF 页面访问这个 Java 类或 bean。

在 JSF 2.0 中,使用 @ManagedBean 注释来表示这是一个受管 Bean。HelloBean.java
T3

 package com.mkyong.common;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.io.Serializable;

@ManagedBean
@SessionScoped
public class HelloBean implements Serializable {

	private static final long serialVersionUID = 1L;

	private String name;

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

Note
In JSF 1.x, you had to declare beans in the faces-config.xml, but this is no longer required in JSF 2.0.

3.JSF 2.0 页

在 JSF 2.0 中,建议以 XHTML 文件格式创建 JSF 页面,这是一个扩展名为. XHTML 的文件。

参见下面两个 JSF 2.0 页面:

Note
To use the JSF 2.0 components or features, just declared the JSF namespace at the top of the page.

 <html 
      xmlns:f="http://java.sun.com/jsf/core"      
      xmlns:h="http://java.sun.com/jsf/html"> 

File:hello . XHTML–呈现一个 JSF 文本框,并链接到“hello Bean”(JSF 托管 bean)、“ name ”属性,以及一个单击时显示“ welcome.xhtml ”页面的按钮。

 <?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:f="http://java.sun.com/jsf/core"      
      xmlns:h="http://java.sun.com/jsf/html">

    <h:head>
        <title>JSF 2.0 Hello World</title>
    </h:head>
    <h:body>
    	<h2>JSF 2.0 Hello World Example - hello.xhtml</h2>
    	<h:form>
    	   <h:inputText value="#{helloBean.name}"></h:inputText>
    	   <h:commandButton value="Welcome Me" action="welcome"></h:commandButton>
    	</h:form>
    </h:body>
</html> 

Note
In JSF 1.x, you had to declare the “navigation rule” in “faces-config.xml“, to tell which page to display when the button is clicked. In JSF 2.0, you can put the page name directly in the button’s “action” attribute. For simple navigation, it’s more than enough, but, for complex navigation, you are still advised to use the “navigation rule” in “faces-config.xml“.

File:welcome . XHTML–显示提交的文本框值。

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

    <h:head>
    	<title>JSF 2.0 Hello World</title>
    </h:head>
    <h:body bgcolor="white">
    	<h2>JSF 2.0 Hello World Example - welcome.xhtml</h2>
    	<h2>Welcome #{helloBean.name}</h2>
    </h:body>
</html> 

#{…} 表示这是一个 JSF 表达式语言,这里是 #{helloBean.name} ,当页面提交时,JSF 会找到“ helloBean ,并通过 setName() 方法设置提交的 textbox 值。当显示 welcome.xhtml 页面时,JSF 将再次找到同一个会话“ helloBean ”,并通过 getName() 方法显示 name 属性值。

4.JSF 2.0 Serlvet 配置

就像任何其他标准的 web 框架一样,你需要在 web.xml 文件中配置 JSF 的东西。

文件:web.xml

 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

        xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">

	<display-name>JavaServerFaces</display-name>

	<!-- Change to "Production" when you are ready to deploy -->
	<context-param>
		<param-name>javax.faces.PROJECT_STAGE</param-name>
		<param-value>Development</param-value>
	</context-param>

	<!-- Welcome page -->
	<welcome-file-list>
		<welcome-file>faces/hello.xhtml</welcome-file>
	</welcome-file-list>

	<!-- JSF mapping -->
	<servlet>
		<servlet-name>Faces Servlet</servlet-name>
		<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<!-- Map these files with JSF -->
	<servlet-mapping>
		<servlet-name>Faces Servlet</servlet-name>
		<url-pattern>/faces/*</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>Faces Servlet</servlet-name>
		<url-pattern>*.jsf</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>Faces Servlet</servlet-name>
		<url-pattern>*.faces</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
		<servlet-name>Faces Servlet</servlet-name>
		<url-pattern>*.xhtml</url-pattern>
	</servlet-mapping>

</web-app> 

定义一个"javax . faces . web app . faces servlet"映射,映射到那些众所周知的 JSF 文件扩展名( /faces/* 、 *)。jsf , *。xhtml , *。面相

在这种情况下,下面 4 个 URL 指向同一个 hello.xhtml

  1. http://localhost:8080/Java server faces/hello . JSF
  2. http://localhost:8080/Java server faces/hello . faces
  3. http://localhost:8080/Java server faces/hello . XHTML
  4. http://localhost:8080/Java server faces/faces/hello . JSF

在 JSF 2.0 开发中,建议将“javax . faces . project _ STAGE”设置为“开发”,它会提供很多有用的调试信息,让你轻松跟踪 bug。对于部署,只需将其更改为“生产”,您只是不想让您的客户看到这些烦人的调试信息:)。

5.演示

一篇长文章以一个项目演示结束🙂

URL:http://localhost:8080/Java server faces/hello . JSF

jsf2-hello-world-example-1

一个简单的 JSF 页面,有一个文本框和一个按钮。

jsf2-hello-world-example-2

单击按钮时,显示提交的文本框值。

下载源代码

Download It (v2.1.7 example)- JSF2.0-hello-world-example-2.1.7.zip (8KB)Download It (old v2.1.0-b03 example)- JSF-2-Hello-World-Example-2.1.0-b03.zip (8KB)

参考

  1. JavaServer Faces 技术
  2. JSF 2.0 发行说明
  3. Wiki : JavaServer Faces
  4. Wiki : XHTML 文件解释
  5. Java . lang . illegalargumentexception:javax . faces . context . exception handler factory
  6. JSF 2.0 + Tomcat:看来这个容器的 JSP 版本比 2.1 还要老…
  7. Eclipse IDE:编辑器中不支持的内容类型
  8. Eclipse IDE:。xhtml 代码辅助对 JSF 标签不起作用

Tags : hello world jsf2

相关文章

JSF 2.0 + JDBC 集成示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jsf2/jsf-2-0-jdbc-integration-example/

这里有一个指南,向您展示如何通过 JDBC 集成 JSF 2.0 与数据库。在这个例子中,我们使用 MySQL 数据库和 Tomcat web 容器。

本例的目录结构

1.表结构

创建一个“客户”表,并插入五条虚拟记录。稍后,通过 JSF h:dataTable显示。

SQL 命令

 DROP TABLE IF EXISTS `mkyongdb`.`customer`;
CREATE TABLE  `mkyongdb`.`customer` (
  `CUSTOMER_ID` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `NAME` varchar(45) NOT NULL,
  `ADDRESS` varchar(255) NOT NULL,
  `CREATED_DATE` datetime NOT NULL,
  PRIMARY KEY (`CUSTOMER_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;

insert into mkyongdb.customer(customer_id, name, address, created_date) 
values(1, 'mkyong1', 'address1', now());
insert into mkyongdb.customer(customer_id, name, address, created_date) 
values(2, 'mkyong2', 'address2', now());
insert into mkyongdb.customer(customer_id, name, address, created_date) 
values(3, 'mkyong3', 'address3', now());
insert into mkyongdb.customer(customer_id, name, address, created_date) 
values(4, 'mkyong4', 'address4', now());
insert into mkyongdb.customer(customer_id, name, address, created_date) 
values(5, 'mkyong5', 'address5', now()); 

2.MySQL 数据源

配置一个名为"JDBC/mkyondb"的 MySQL 数据源,遵循本文-如何在 Tomcat 6 中配置 MySQL 数据源

3.模型类

创建一个“ Customer ”模型类来存储表记录。

文件:Customer.java

 package com.mkyong.customer.model;

import java.util.Date;

public class Customer{

	public long customerID;
	public String name;
	public String address;
	public Date created_date;

	//getter and setter methods 
} 

4.JDBC 的例子

一个 JSF 2.0 托管 bean,通过@Resource注入 data source "JDBC/mkyondb,使用普通的 JDBC API 从数据库中检索所有的客户记录并存储到一个列表中。

文件:CustomerBean.java

 package com.mkyong;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import com.mkyong.customer.model.Customer;

@ManagedBean(name="customer")
@SessionScoped
public class CustomerBean implements Serializable{

	//resource injection
	@Resource(name="jdbc/mkyongdb")
	private DataSource ds;

	//if resource injection is not support, you still can get it manually.
	/*public CustomerBean(){
		try {
			Context ctx = new InitialContext();
			ds = (DataSource)ctx.lookup("java:comp/env/jdbc/mkyongdb");
		} catch (NamingException e) {
			e.printStackTrace();
		}

	}*/

	//connect to DB and get customer list
	public List<Customer> getCustomerList() throws SQLException{

		if(ds==null)
			throw new SQLException("Can't get data source");

		//get database connection
		Connection con = ds.getConnection();

		if(con==null)
			throw new SQLException("Can't get database connection");

		PreparedStatement ps 
			= con.prepareStatement(
			   "select customer_id, name, address, created_date from customer"); 

		//get customer data from database
		ResultSet result =  ps.executeQuery();

		List<Customer> list = new ArrayList<Customer>();

		while(result.next()){
			Customer cust = new Customer();

			cust.setCustomerID(result.getLong("customer_id"));
			cust.setName(result.getString("name"));
			cust.setAddress(result.getString("address"));
			cust.setCreated_date(result.getDate("created_date"));

			//store all data into a List
			list.add(cust);
		}

		return list;
	}
} 

5.JSF 页面数据表

一个 JSF 2.0 xhtml 页面,使用h:dataTable以表格布局格式显示所有客户记录。

 <?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"
      >
    <h:head>
    	<h:outputStylesheet library="css" name="table-style.css"  />
    </h:head>

    <h:body>

    	<h1>JSF 2.0 + JDBC Example</h1>

 		<h:dataTable value="#{customer.getCustomerList()}" var="c"
    			styleClass="order-table"
    			headerClass="order-table-header"
    			rowClasses="order-table-odd-row,order-table-even-row"
    		>

    		<h:column>
    			<f:facet name="header">
    				Customer ID
    			</f:facet>
    				#{c.customerID}
    		</h:column>

    		<h:column>
    			<f:facet name="header">
    				Name
				</f:facet>
    				#{c.name}
    		</h:column>

 			<h:column>
    			<f:facet name="header">
    				Address
				</f:facet>
    				#{c.address}
    		</h:column>

    		<h:column>
    			<f:facet name="header">
    				Created Date
				</f:facet>
    				#{c.created_date}
    		</h:column>

    	</h:dataTable>

    </h:body>

</html> 

6.演示

运行它,查看输出

下载源代码

Download It – JSF-2-JDBC-Integration-Example.zip (12KB)

参考

  1. Java 中的 JDBC 例子
  2. Tomcat 6 中的 JNDI 数据源示例
  3. 在 Tomcat 6 中配置 MySQL 数据源
  4. JSF 2 数据表示例

integration jdbc jsf2

JSF 2.0:托管 bean x 不存在,请检查适当的 getter 和/或 setter 方法是否存在

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jsf2/jsf-2-0-managed-bean-x-does-not-exist-check-that-appropriate-getter-andor-setter-methods-exist/

问题

在 JSF 2.0 中,当使用 @ManagedProperty 注释将 bean 插入另一个 bean 的字段时,

地狱篇. java

 @ManagedBean
@SessionScoped
public class HelloBean implements Serializable {

	@ManagedProperty(value="#{message}")
	private MessageBean messageBean; 

MessageBean.java

 @ManagedBean(name="message")
@SessionScoped
public class MessageBean implements Serializable { 

它会显示以下错误消息。

出现错误:
无法创建受管 bean helloBean。发现以下问题:–受管 bean helloBean 的属性 messageBean 不存在。检查是否存在适当的 getter 和/或 setter 方法。

解决办法

要将“messageBean”注入到“helloBean”的字段中,必须提供 messageBean setter 方法

地狱篇. java

 @ManagedBean
@SessionScoped
public class HelloBean implements Serializable {

	@ManagedProperty(value="#{message}")
	private MessageBean messageBean;

	public void setMessageBean(MessageBean messageBean) {
		this.messageBean = messageBean;
	} 

完成后,错误消息应该会消失。

jsf2 managed bean (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);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/20190225125610/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

JSF 2.0 + Spring + Hibernate 集成示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jsf2/jsf-2-0-spring-hibernate-integration-example/

这里有一篇长文告诉你如何将 JSF 2.0春天冬眠整合在一起。在文章的最后,您将创建一个页面,显示数据库中现有客户的列表和一个“添加客户”功能,允许用户添加一个新客户到数据库中。

在这个例子中,我们使用 MySQL 数据库并部署到 Tomcat 6 web 容器。

1.项目结构

此示例的目录结构

jsf2-spring-hibernate-folder-1jsf2-spring-hibernate-folder-2 ## 2.表格脚本

创建一个客户表并插入 2 条虚拟记录。

 DROP TABLE IF EXISTS `mkyongdb`.`customer`;
CREATE TABLE  `mkyongdb`.`customer` (
  `CUSTOMER_ID` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `NAME` varchar(45) NOT NULL,
  `ADDRESS` varchar(255) NOT NULL,
  `CREATED_DATE` datetime NOT NULL,
  PRIMARY KEY (`CUSTOMER_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;

insert into mkyongdb.customer(customer_id, name, address, created_date)
values(1, 'mkyong1', 'address1', now());
insert into mkyongdb.customer(customer_id, name, address, created_date)
values(2, 'mkyong2', 'address2', now()); 

3.冬眠的东西

客户表的模型类和 Hibernate 映射文件。

文件:Customer.java

 package com.mkyong.customer.model;

import java.util.Date;

public class Customer{

	public long customerId;
	public String name;
	public String address;
	public Date createdDate;

	//getter and setter methods

} 

文件:Customer.hbm.xml

 <?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.mkyong.customer.model.Customer" 
        table="customer" catalog="mkyongdb">

        <id name="customerId" type="long">
            <column name="CUSTOMER_ID" />
            <generator class="identity" />
        </id>
        <property name="name" type="string">
            <column name="NAME" length="45" not-null="true" />
        </property>
        <property name="address" type="string">
            <column name="ADDRESS" not-null="true" />
        </property>
        <property name="createdDate" type="timestamp">
            <column name="CREATED_DATE" length="19" not-null="true" />
        </property>
    </class>
</hibernate-mapping> 

4.春天的东西

Spring 的 BO 和 DAO 类用于业务逻辑和数据库交互。

文件:CustomerBo.java

 package com.mkyong.customer.bo;

import java.util.List;

import com.mkyong.customer.model.Customer;

public interface CustomerBo{

	void addCustomer(Customer customer);

	List<Customer> findAllCustomer();

} 

文件:CustomerBoImpl.java

 package com.mkyong.customer.bo.impl;

import java.util.List;
import com.mkyong.customer.bo.CustomerBo;
import com.mkyong.customer.dao.CustomerDao;
import com.mkyong.customer.model.Customer;

public class CustomerBoImpl implements CustomerBo{

	CustomerDao customerDao;

	public void setCustomerDao(CustomerDao customerDao) {
		this.customerDao = customerDao;
	}

	public void addCustomer(Customer customer){

		customerDao.addCustomer(customer);

	}

	public List<Customer> findAllCustomer(){

		return customerDao.findAllCustomer();
	}
} 

文件:CustomerDao.java

 package com.mkyong.customer.dao;

import java.util.List;

import com.mkyong.customer.model.Customer;

public interface CustomerDao{

	void addCustomer(Customer customer);

	List<Customer> findAllCustomer();

} 

文件:CustomerDaoImpl.java

 package com.mkyong.customer.dao.impl;

import java.util.Date;
import java.util.List;

import com.mkyong.customer.dao.CustomerDao;
import com.mkyong.customer.model.Customer;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class CustomerDaoImpl extends 
       HibernateDaoSupport implements CustomerDao{

	public void addCustomer(Customer customer){

		customer.setCreatedDate(new Date());
		getHibernateTemplate().save(customer);

	}

	public List<Customer> findAllCustomer(){

		return getHibernateTemplate().find("from Customer");

	}
} 

文件:CustomerBean.xml

 <?xml version="1.0" encoding="UTF-8"?>
<beans 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

   	<bean id="customerBo" 
         class="com.mkyong.customer.bo.impl.CustomerBoImpl" >
   		<property name="customerDao" ref="customerDao" />
   	</bean>

   	<bean id="customerDao" 
         class="com.mkyong.customer.dao.impl.CustomerDaoImpl" >
   		<property name="sessionFactory" ref="sessionFactory" />
   	</bean>

</beans> 

5.Spring +数据库

在 Spring 中配置数据库细节。

文件:db.properties

 jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mkyongdb
jdbc.username=root
jdbc.password=password 

文件:DataSource.xml

 <beans 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

 <bean 
   class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
   <property name="location">
		<value>WEB-INF/classes/config/database/db.properties</value>
   </property>
</bean>

  <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
	<property name="driverClassName" value="${jdbc.driverClassName}" />
	<property name="url" value="${jdbc.url}" />
	<property name="username" value="${jdbc.username}" />
	<property name="password" value="${jdbc.password}" />
  </bean>

</beans> 

6.春天+冬眠

通过LocalSessionFactoryBean集成 Hibernate 和 Spring。

档案:HibernateSessionFactory.xml

 <?xml version="1.0" encoding="UTF-8"?>
<beans 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<!-- Hibernate session factory -->
<bean id="sessionFactory" 
     class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

    <property name="dataSource">
      <ref bean="dataSource"/>
    </property>

    <property name="hibernateProperties">
       <props>
         <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
         <prop key="hibernate.show_sql">true</prop>
       </props>
    </property>

    <property name="mappingResources">
	<list>
          <value>com/mkyong/customer/hibernate/Customer.hbm.xml</value>
	</list>
     </property>	

</bean>
</beans> 

7.JSF 2.0

JSF 管理 bean 调用 Spring 的 BO 来添加或获取数据库中的客户记录。

文件:CustomerBean.java

 package com.mkyong;

import java.io.Serializable;
import java.util.List;

import com.mkyong.customer.bo.CustomerBo;
import com.mkyong.customer.model.Customer;

public class CustomerBean implements Serializable{

	//DI via Spring
	CustomerBo customerBo;

	public String name;
	public String address;
	//getter and setter methods

	public void setCustomerBo(CustomerBo customerBo) {
		this.customerBo = customerBo;
	}

	//get all customer data from database
	public List<Customer> getCustomerList(){
		return customerBo.findAllCustomer();
	}

	//add a new customer data into database
	public String addCustomer(){

		Customer cust = new Customer();
		cust.setName(getName());
		cust.setAddress(getAddress());

		customerBo.addCustomer(cust);

		clearForm();

		return "";
	}

	//clear form values
	private void clearForm(){
		setName("");
		setAddress("");
	}

} 

一个通过h:dataTable显示现有客户记录的 JSF 页面和一些文本组件,允许用户向数据库中插入新的客户记录。

文件:default.xhtml

 <?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"
      >
    <h:head>
    	<h:outputStylesheet library="css" name="table-style.css"  />
    </h:head>

    <h:body>

    	<h1>JSF 2.0 + Spring + Hibernate Example</h1>

 		<h:dataTable value="#{customer.getCustomerList()}" var="c"
    			styleClass="order-table"
    			headerClass="order-table-header"
    			rowClasses="order-table-odd-row,order-table-even-row"
    		>

    		<h:column>
    			<f:facet name="header">
    				Customer ID
    			</f:facet>
    				#{c.customerId}
    		</h:column>

    		<h:column>
    			<f:facet name="header">
    				Name
				</f:facet>
    				#{c.name}
    		</h:column>

 			<h:column>
    			<f:facet name="header">
    				Address
				</f:facet>
    				#{c.address}
    		</h:column>

    		<h:column>
    			<f:facet name="header">
    				Created Date
				</f:facet>
    				#{c.createdDate}
    		</h:column>

    	</h:dataTable>

 		<h2>Add New Customer</h2>
 		<h:form>

 			<h:panelGrid columns="3">

				Name : 
				<h:inputText id="name" value="#{customer.name}" 
					size="20" required="true"
					label="Name" >
				</h:inputText>

				<h:message for="name" style="color:red" />

				Address : 
				<h:inputTextarea id="address" value="#{customer.address}" 
					cols="30" rows="10" required="true"
					label="Address" >
				</h:inputTextarea>

				<h:message for="address" style="color:red" />

			</h:panelGrid>

			<h:commandButton value="Submit" action="#{customer.addCustomer()}" />

 		</h:form>

    </h:body>

</html> 

8.JSF 2.0 +春天

将 JSF 2.0 与 Spring 集成,详细解释见此——JSF 2.0+Spring 集成示例

文件:applicationContext.xml

 <beans 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

	<!-- Database Configuration -->
	<import resource="classes/config/spring/beans/DataSource.xml"/>
	<import resource="classes/config/spring/beans/HibernateSessionFactory.xml"/>

	<!-- Beans Declaration -->
	<import resource="classes/com/mkyong/customer/spring/CustomerBean.xml"/>

</beans> 

文件:faces-config.xml

 <?xml version="1.0" encoding="UTF-8"?>
<faces-config

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
    version="2.0">

	<application>
    	<el-resolver>
    		org.springframework.web.jsf.el.SpringBeanFacesELResolver
    	</el-resolver>
  	</application>

	<managed-bean>
		<managed-bean-name>customer</managed-bean-name>
		<managed-bean-class>com.mkyong.CustomerBean</managed-bean-class>
		<managed-bean-scope>session</managed-bean-scope>
		<managed-property>
			<property-name>customerBo</property-name>
			<value>#{customerBo}</value>
		</managed-property>
	</managed-bean>

</faces-config> 

文件:web.xml

 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 

	xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
	id="WebApp_ID" version="2.5">

  <display-name>JavaServerFaces</display-name>

  <!-- Add Support for Spring -->
  <listener>
	<listener-class>
		org.springframework.web.context.ContextLoaderListener
	</listener-class>
  </listener>
  <listener>
	<listener-class>
		org.springframework.web.context.request.RequestContextListener
	</listener-class>
  </listener>

  <!-- Change to "Production" when you are ready to deploy -->
  <context-param>
    <param-name>javax.faces.PROJECT_STAGE</param-name>
    <param-value>Development</param-value>
  </context-param>

  <!-- Welcome page -->
  <welcome-file-list>
    <welcome-file>faces/default.xhtml</welcome-file>
  </welcome-file-list>

  <!-- JSF mapping -->
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <!-- Map these files with JSF -->
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.jsf</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.faces</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
  </servlet-mapping>

</web-app> 

9.演示

运行它,填写客户数据并点击“提交”按钮。

jsf2-spring-hibernate-example-1jsf2-spring-hibernate-example-2

下载源代码

Download It – JSF-2-Spring-Hibernate-Integration-Example.zip (19KB)

参考

  1. JSF 2.0 + Spring 集成示例
  2. Struts + Spring + Hibernate 集成示例

hibernate integration jsf2 spring

JSF 2 + Spring 3 集成示例

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/jsf2/jsf-2-0-spring-integration-example/

在本教程中,我们将向您展示如何使用以下工具将 JSF 2.0 与 Spring 3 集成:

  1. JSF XML faces-config.xml
  2. 弹簧注释
  3. JSR-330 标准注射液

使用的工具和技术:

  1. JSF 2.1.13
  2. 释放弹簧
  3. maven3
  4. Eclipse 4.2
  5. Tomcat 6 或 7

1.目录结构

用于演示的标准 Maven 项目。

jsf2-spring-example-folder

2.项目相关性

声明 JSF 2,春天 3,JSR 330 注入,和 Tomcat 的依赖。

pom.xml

 <project  
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
  	http://maven.apache.org/maven-v4_0_0.xsd">

	<modelVersion>4.0.0</modelVersion>
	<groupId>com.mkyong.common</groupId>
	<artifactId>JavaServerFaces</artifactId>
	<packaging>war</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>JavaServerFaces Maven Webapp</name>
	<url>http://maven.apache.org</url>

	<dependencies>

		<!-- Spring framework -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>3.1.2.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>3.1.2.RELEASE</version>
		</dependency>

		<!-- JSR-330 -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>

		<!-- JSF -->
		<dependency>
			<groupId>com.sun.faces</groupId>
			<artifactId>jsf-api</artifactId>
			<version>2.1.13</version>
		</dependency>
		<dependency>
			<groupId>com.sun.faces</groupId>
			<artifactId>jsf-impl</artifactId>
			<version>2.1.13</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
		</dependency>

		<!-- EL -->
		<dependency>
			<groupId>org.glassfish.web</groupId>
			<artifactId>el-impl</artifactId>
			<version>2.2</version>
		</dependency>

		<!-- Tomcat 6 need this -->
		<dependency>
			<groupId>com.sun.el</groupId>
			<artifactId>el-ri</artifactId>
			<version>1.0</version>
		</dependency>

	</dependencies>

	<build>
	<finalName>JavaServerFaces</finalName>

	<plugins>
	   <plugin>
		<groupId>org.apache.maven.plugins</groupId>
		<artifactId>maven-compiler-plugin</artifactId>
		<version>2.3.1</version>
		<configuration>
			<source>1.6</source>
			<target>1.6</target>
		</configuration>
	   </plugin>
	</plugins>
	</build>
</project> 

3.JSF 2 + Spring 集成

Spring Ioc 环境下的 Spring bean 和 JSF Ioc 环境下的 JSF 托管 bean,如何让两者协同工作?解决方法是在faces-config.xml中定义弹簧的SpringBeanFacesELResolver。检查这个官方弹簧指南

faces-config.xml

 <?xml version="1.0" encoding="UTF-8"?>
<faces-config 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-facesconfig_2_1.xsd"
	version="2.1">

	<application>
		<el-resolver>
    		    org.springframework.web.jsf.el.SpringBeanFacesELResolver
		</el-resolver>
  	</application>

</faces-config> 

参见下面 3 个例子在 JSF 管理的 bean 中注入 Spring 的 bean。

3.1.XML 模式示例

许多开发人员仍然喜欢使用 XML 来管理 beans。使用SpringBeanFacesELResolver,只是使用 EL ${userBo}将 Spring 的 bean 注入到 JSF 的托管 bean 中。

UserBo.java

 package com.mkyong.user.bo;

public interface UserBo{

	public String getMessage();

} 

UserBoImpl.java

 package com.mkyong.user.bo.impl;

import com.mkyong.user.bo.UserBo;

public class UserBoImpl implements UserBo{

	public String getMessage() {

		return "JSF 2 + Spring Integration";

	}

} 

UserBean.java – JSF backing bean

 package com.mkyong;

import java.io.Serializable;
import com.mkyong.user.bo.UserBo;

public class UserBean{

        //later inject in faces-config.xml
	UserBo userBo;

	public void setUserBo(UserBo userBo) {
		this.userBo = userBo;
	}

	public String printMsgFromSpring() {

		return userBo.getMessage();

	}

} 

applicationContext.xml – Declares userBo bean

 <beans 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

	<bean id="userBo" class="com.mkyong.user.bo.impl.UserBoImpl"></bean>

</beans> 

faces-config.xml – Declares managed bean and inject userBo

 <?xml version="1.0" encoding="UTF-8"?>
<faces-config

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
    version="2.0">

	<managed-bean>
		<managed-bean-name>user</managed-bean-name>
		<managed-bean-class>com.mkyong.UserBean</managed-bean-class>
		<managed-bean-scope>session</managed-bean-scope>
		<managed-property>
			<property-name>userBo</property-name>
			<value>#{userBo}</value>
		</managed-property>
	</managed-bean>

</faces-config> 

3.2.弹簧注释–自动扫描

这个例子使用了 Spring 注释。像普通的 bean 一样注入@ManagedBean@Autowired@Component,它就像预期的那样工作。

UserBoImpl.java

 package com.mkyong.user.bo.impl;

import org.springframework.stereotype.Service;
import com.mkyong.user.bo.UserBo;

@Service
public class UserBoImpl implements UserBo{

	public String getMessage() {

		return "JSF 2 + Spring Integration";

	}

} 

UserBean.java

 package com.mkyong;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.mkyong.user.bo.UserBo;

@Component
@ManagedBean
@SessionScoped
public class UserBean{

	@Autowired
	UserBo userBo;

	public void setUserBo(UserBo userBo) {
		this.userBo = userBo;
	}

	public String printMsgFromSpring() {
		return userBo.getMessage();
	}

} 

applicationContext.xml – Enable the component auto scan

 <beans 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-3.1.xsd">

	<context:component-scan base-package="com.mkyong" />

</beans> 

混合使用 JSF 和春天注释工作正常,但是看起来很奇怪而且重复——@Component@ManagedBean在一起。实际上,你可以只用一个@Component,看下面的新版本,它是纯弹簧的,而且很有效!

UserBean.java

 package com.mkyong;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.mkyong.user.bo.UserBo;

@Component
@Scope("session")
public class UserBean{

	@Autowired
	UserBo userBo;

	public void setUserBo(UserBo userBo) {
		this.userBo = userBo;
	}

	public String printMsgFromSpring() {
		return userBo.getMessage();
	}

} 

3.3.JSR-330 注解

从 Spring 3.0 开始, Spring 为 JSR-330 注入标准提供支持。现在,你可以用@Inject代替@Autowired,用@Named代替@Component。这是推荐的解决方案,遵循 JSR-330 标准使应用程序更容易移植到其他环境,它在 Spring 框架中工作良好。

UserBoImpl.java

 package com.mkyong.user.bo.impl;

import javax.inject.Named;
import com.mkyong.user.bo.UserBo;

@Named
public class UserBoImpl implements UserBo{

	public String getMessage() {

		return "JSF 2 + Spring Integration";

	}

} 

UserBean.java

 package com.mkyong;

import javax.inject.Inject;
import javax.inject.Named;
import org.springframework.context.annotation.Scope;
import com.mkyong.user.bo.UserBo;

@Named
@Scope("session") //need this, JSR-330 in Spring context is singleton by default
public class UserBean {

	@Inject
	UserBo userBo;

	public void setUserBo(UserBo userBo) {
		this.userBo = userBo;
	}

	public String printMsgFromSpring() {
		return userBo.getMessage();
	}

} 

applicationContext.xml – Need component auto scan also

 <beans 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-3.1.xsd">

	<context:component-scan base-package="com.mkyong" />

</beans> 

4.演示

3.13.23.3 中的例子都在做同样的事情——将userBo注入 JSF 豆,只是实现方式不同。现在,创建一个简单的 JSF 页面来显示结果。

default.xhtml

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

    <h:body>

    	<h1>JSF 2.0 + Spring Example</h1>

 	#{userBean.printMsgFromSpring()}

    </h:body>

</html> 

web.xml

 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 

	xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
	id="WebApp_ID" version="2.5">

  <display-name>JavaServerFaces</display-name>

  <!-- Add Support for Spring -->
  <listener>
	<listener-class>
		org.springframework.web.context.ContextLoaderListener
	</listener-class>
  </listener>
  <listener>
	<listener-class>
		org.springframework.web.context.request.RequestContextListener
	</listener-class>
  </listener>

  <!-- Change to "Production" when you are ready to deploy -->
  <context-param>
    <param-name>javax.faces.PROJECT_STAGE</param-name>
    <param-value>Development</param-value>
  </context-param>

  <!-- Welcome page -->
  <welcome-file-list>
    <welcome-file>default.jsf</welcome-file>
  </welcome-file-list>

  <!-- JSF Mapping -->
  <servlet>
    <servlet-name>facesServlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>facesServlet</servlet-name>
    <url-pattern>*.jsf</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>facesServlet</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
  </servlet-mapping>

</web-app> 

完成,查看输出:http://localhost:8080/Java server faces/default . JSF

jsf2 and spring integration

下载源代码

Download It – JSF2-Spring-Example.zip (31KB)

参考

  1. 弹簧参考–弹簧面选择分解器
  2. Spring 如何在会话监听器中进行依赖注入
  3. 弹簧 3 和 JSR-330 @注入和@命名示例

Tags : integration jsf2 spring spring3

相关文章

JSF 2.0 + Tomcat:看来容器的 JSP 版本比 2.1 还要旧…

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jsf2/jsf-2-0-tomcat-it-appears-the-jsp-version-of-the-container-is-older-than-2-1/

问题

将 JSF 2.0 web 应用程序部署到 Tomcat 6.0.26 时,遇到“ JSP 版本的容器比 2.1 旧”异常,无法启动 Tomcat 服务器。但是 JSP api v2.1 包含在项目类路径中,为什么 Tomcat 还在说 JSP 版本比 2.1 老?

 <dependency>
	 <groupId>javax.servlet.jsp</groupId>
	 <artifactId>jsp-api</artifactId>
	 <version>2.1</version>
    </dependency> 

这是错误堆栈…

 SEVERE: Critical error during deployment: 
   ...
Caused by: com.sun.faces.config.ConfigurationException: 
It appears the JSP version of the container is older than 2.1 and unable to 
locate the EL RI expression factory, com.sun.el.ExpressionFactoryImpl. 

If not using JSP or the EL RI, make sure the context initialization parameter, 
com.sun.faces.expressionFactory, is properly set. 

解决办法

不太确定它的根本原因,但解决方案是包含 el-ri.jar

 <dependency>
     <groupId>com.sun.el</groupId>
     <artifactId>el-ri</artifactId>
     <version>1.0</version>
  </dependency> 

这个 el-ri.jar 在默认的 Maven 中央存储库中可用。

Note
The JSF 2.0 released note didn’t mention about this el-ri.jar dependency library, that’s weird. ## 更新日期:2010 年 10 月 21 日

这个“el-ri.jar”太旧了,建议使用最新的“el-impl-2.2.jar”,来自Java.net

 <dependency>
	  <groupId>org.glassfish.web</groupId>
	  <artifactId>el-impl</artifactId>
	  <version>2.2</version>
     </dependency> 

jsf2 jsp tomcat

JSF 2.0 教程

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/tutorials/jsf-2-0-tutorials/

jsf2-tutorials

JavaServer Faces (JSF) 2.0 ,是一个 MVC web 框架,致力于简化 Java web 应用程序用户界面的构建(附带 100 多个现成的 UI 标签),并使可重用的 UI 组件易于实现。与 JSF 1.x 不同,几乎所有的东西都在faces-config.xml中声明,在 JSF 2.0 中,你可以使用注释来声明导航、托管 bean 或 CDI bean,这使得你的开发更加容易和快速。

在本教程中,它提供了许多关于使用 JavaServer Faces (JSF) 2.0 框架的分步示例和解释。

快乐学习 JSF 2.0🙂

快速启动

JSF 2.0 的一些快速入门示例

  • JSF 2.0 hello world 示例
    一个 Java server Faces(JSF)2.0 hello world 示例,展示了 JSF 2.0 的依赖项、基本注释和配置。让您快速了解 JSF 2.0 的样子,以及它与 JSF 1.x 的不同之处
  • JSF 2.0 + Ajax hello world 示例
    在 JSF 2.0 中,编写 Ajax 就像编写一个普通的 HTML 标签一样,非常容易。在本教程中,您将重新构建最后一个 JSF 2.0 hello world 示例,这样,当单击按钮时,它将发出一个 Ajax 请求,而不是提交整个表单。
  • 如何让 Eclipse IDE 支持 JSF 2.0
    这里有一个快速指南,展示如何在 Eclipse 项目中启用 JSF 2.0 的特性。
  • JSF 2.0 中的资源(库)
    在 JSF 2.0 中,你所有的资源文件,比如 css、图片或者 JavaScript,都应该放到你的 web 应用程序根目录下的“Resources”文件夹中。在 JSF 2.0 术语中,“资源”文件夹的所有子文件夹名称都被认为是 JSF 2.0 web 应用程序中的“库”。稍后,您可以使用 JSF 标签的库属性来引用这个“库”。

受管 Bean

关于 JSF 2.0 中的受管 bean 配置和注入

  • 在 JSF 2.0 中配置受管 bean
    在 JSF 2.0 中,可以从 JSF 页面访问的 Java bean 称为受管 Bean。受管 bean 可以是一个普通的 Java bean,它包含 getter 和 setter 方法、业务逻辑,甚至是一个后备 bean(一个 bean 包含所有的 HTML 表单值)。
  • 在 JSF 2.0 中注入受管 bean
    在 JSF 2.0 中,一个新的@ManagedProperty 注释用于将一个受管 bean 依赖注入(DI)到另一个受管 bean 的属性中。

航行

JSF 2.0 中导航的工作原理

  • JSF 2.0
    中的隐式导航现在,JSF 2 出来了一个新的“自动查看页面解析器”机制,命名为“隐式导航”,在这里你不需要声明上面的导航规则,取而代之的是,只要把“视图名称”放在 action 属性中,JSF 就会自动找到正确的“查看页面”。
  • JSF 2.0 中的条件导航规则
    JSF 2 自带非常灵活的条件导航规则,解决复杂的页面导航流程。
  • JSF“表单-动作”导航规则示例
    在 JSF 导航规则中,你可能会遇到两个单独的动作在一个页面中返回同一个“结果的情况。在这种情况下,您可以使用“ form-action 元素来区分这两种导航情况。
  • JSF:页面前进 vs 页面重定向
    默认情况下,JSF 在导航到另一个页面时执行服务器页面前进。请参见下面的示例来区分页面转发和页面重定向。

资源包

JSF 的信息操纵和国际化。

  • JSF 2.0 和资源包示例
    在本教程中,我们将向您展示如何使用资源包来显示 JSF 2.0 中的消息。出于可维护性的考虑,建议将所有消息放在属性文件中,而不是直接在页面中硬编码消息。
  • JSF 2 国际化范例
    JSF 2.0 国际化或多语言范例。

JSF 标签库

标准 JSF 2 表单的标签组件。

表格操作

通过 JSF 的数据表添加、更新、删除和排序数据。

Facelets 标签

用 JSF 2.0 facelets 标签做布局模板。

转换器和验证

jsf 2.0 中的标准 cconverter 和 validator 标记

复合组件

JSF 2.0 中的可重用组件

  • JSF 2.0 中的复合组件在本教程中,我们将向您展示如何在 JSF 2.0 中创建一个可重用的组件(复合组件)

事件处理程序

JSF 2 附带了许多事件处理程序来劫持 JSF 的生命周期。

与其他框架集成

如何整合 JSF 与外部服务?

常见问题解答

JSF 2.0 中的一些常见问题

常见错误

JSF 2.0 中的一些常见错误消息

参考

进一步研究 JSF 2.0 的一些有用的参考网站

  1. JSF 官网
  2. JSF 应用生命周期
  3. 转换器和验证
  4. JSF 的通信

JSF 2 actionListener 示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jsf2/jsf-2-actionlistener-example/

在 JSF,动作事件是通过点击按钮或链接组件来触发的,例如 h:commandButtonh:commandLink

actions vs action listeners
Do not confuse these two tags, actions is used to perform business logic and navigation task; While action listeners are used to perform UI interface logic or action invoke observation.

这个动作监听器的常见用例是用来取回附加到组件的属性值,参见这个 JSF 2 f:属性示例

这里有两种方法来实现它:

1.方法绑定

在按钮或链接组件中,可以直接在“ actionListener ”属性中指定 bean 的方法。

JSF 页……

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

    <h:body>

    <h1>JSF 2 actionListener example</h1>

	<h:form id="form">

	  <h:commandButton id="submitButton" 
		value="Submit" action="#{normal.outcome}" 
		actionListener="#{normal.printIt}" />

	</h:form>

    </h:body>
</html> 

托管 Bean…
与动作事件交互的方法应该接受一个动作事件参数。

 package com.mkyong;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ActionEvent;

@ManagedBean(name="normal")
@SessionScoped
public class NormalBean{

	public String buttonId; 

	public void printIt(ActionEvent event){

		//Get submit button id
		buttonId = event.getComponent().getClientId();

	}

	public String outcome(){
		return "result";
	}
} 

2.动作监听器

在按钮或链接组件中,内部添加一个“ f:actionListener 标签,并指定一个 ActionListener 接口的实现类,并覆盖其 processAction()

JSF 页……

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

    <h:body>

    <h1>JSF 2 actionListener example</h1>

	<h:form id="form">

	  <h:commandButton id="submitButton" 
		value="Submit" action="#{normal.outcome}" >
		<f:actionListener type="com.mkyong.NormalActionListener" />
	  </h:commandButton>

	</h:form>

    </h:body>
</html> 

action listener 接口的实现

 package com.mkyong;

import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;

public class NormalActionListener implements ActionListener{

	@Override
	public void processAction(ActionEvent event)
		throws AbortProcessingException {

		System.out.println("Any use case here?");

	}

} 

下载源代码

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

参考

  1. stack overflow–action 和 actionlistener
  2. 动作事件 JavaDoc

JSF 2 属性示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jsf2/jsf-2-attribute-example/

在 JSF 中,“ f:attribute ”标签允许您将属性值传递给组件,或者通过动作监听器将参数传递给组件。举个例子,

1.为组件分配属性值。

 <h:commandButton">
    <f:attribute name="value" value="Click Me" />				
</h:commandButton>

//is equal to 

<h:commandButton value="Click Me" /> 

2.将参数分配给一个组件,并通过动作监听器获取它。

 <h:commandButton actionListener="#{user.attrListener}" >
    <f:attribute name="username" value="mkyong" />
</h:commandButton> 
 @ManagedBean(name="user")
@SessionScoped
public class UserBean{

  //action listener event
  public void attrListener(ActionEvent event){

	nickname = (String)event.getComponent().getAttributes().get("username");

  } 

JSF f:属性示例

好了,让我们来看一个 JSF 2.0 的完整例子。

1.受管 Bean

一个名为“user”的受管 bean,带有一个操作监听器方法。

 package com.mkyong;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ActionEvent;

@ManagedBean(name="user")
@SessionScoped
public class UserBean{

	public String nickname;

	//action listener event
	public void attrListener(ActionEvent event){

		nickname = (String)event.getComponent().getAttributes().get("username");

	}

	public String outcome(){
		return "result";
	}

	public String getNickname() {
		return nickname;
	}

	public void setNickname(String nickname) {
		this.nickname = nickname;
	}
} 

2.JSF·佩奇

JSF 页面展示了如何使用" f:attribute "标签将一个属性值传递给一个" h:commandButton "组件。

default.xhtml

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

    <h:body>

    	<h1>JSF 2 attribute example</h1>

	<h:form id="form">

	  <h:commandButton action="#{user.outcome}"
			actionListener="#{user.attrListener}" >

		<f:attribute name="username" value="mkyong" />
		<f:attribute name="value" value="Click Me" />

	  </h:commandButton>

	</h:form>

    </h:body>
</html> 

result.xhtml

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

    <h:body>

    	<h1>JSF 2 attribute example</h1>

		#{user.nickname}

    </h:body>

</html> 

3.演示

这是结果。

jsf2-attribute-example-1jsf2-attribute-example-2

下载源代码

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

参考

  1. JSF 2 属性 JavaDoc
  2. JSF 2 行动监听器示例

jsf2

JSF 2 按钮和命令按钮示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jsf2/jsf-2-button-and-commandbutton-example/

在 JSF 2.0 中, < h:button / >< h:commandButton / > 标签都是用来渲染按钮类型的 HTML 输入元素,用不同的机制来处理导航。

1.JSF h:命令按钮示例

h:commandButton 标签是 JSF 1.x 以后发布的,可以声明 bean,它在“ action 属性中返回导航结果。如果浏览器禁用了 JavaScript,导航仍然可以工作,因为导航是通过表单 post 处理的。

1.提交按钮

 //JSF
<h:commandButton value="submit" type="submit" action="#{user.goLoginPage}" />

//HTML output
<input type="submit" name="xxx" value="submit" /> 

2.复原按钮

 //JSF
<h:commandButton value="reset" type="reset" />

//HTML output
<input type="reset" name="xxx" value="reset" /> 

3.正常按钮

 //JSF
<h:commandButton value="button" type="button" />

//HTML output
<input type="button" name="xxx" value="button" /> 

4.带有 onclick 事件的普通按钮

 //JSF
<h:commandButton value="Click Me" type="button" onclick="alert('h:commandButton');" />	

//HTML output
<input type="button" name="xxx" value="Click Me" onclick="alert('h:commandButton');" /> 

2.JSF h:按钮示例

h:button 是 JSF 2.0 中新增的标签,可以直接在“ outcome 属性中声明导航结果,不需要像上面的“h:commandButton”那样调用 bean 返回结果。但是,如果浏览器禁用了 JavaScript,导航就会失败,因为“ h:button ”标签会生成一个“onclick”事件来通过“window.location.href”处理导航。参见示例:

1.没有结果的正常按钮

 //JSF
<h:button value="buton" />			

//HTML output
<input type="button" 
   onclick="window.location.href='/JavaServerFaces/faces/currentpage.xhtml; return false;" 
   value="buton" /> 

如果省略了 outcome 属性,当前页面 URL 将被视为结果。

2.有结果的正常按钮

 //JSF
<h:button value="buton" outcome="login" />			

//HTML output
<input type="button" 
   onclick="window.location.href='/JavaServerFaces/faces/login.xhtml; return false;" 
   value="buton" /> 

3.带有 JavaScript 的普通按钮。

 //JSF
<h:button value="Click Me" onclick="alert('h:button');" />

//HTML output
<input type="button" 
   onclick="alert('h:button');window.location.href='/JavaServerFaces/faces/page.xhtml;return false;" 
   value="Click Me" /> 

My thought…
No really sure why JSF 2.0 released this “h:button” tag, the JavaScript redirection is not practical, especially in JavaScript disabled browser. The best is integrate the “outcome” attribute into the “h:commandButton” tag, hope it can be done in future release.

下载源代码

Download It – JSF-2-Button-CommandButton-Example.zip (10KB)

参考

  1. JSF<h:button/>JavaDoc
  2. JSF < h:命令按钮/ > JavaDoc

标签:按钮JSF 2

相关文章

JSF 2 复选框示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jsf2/jsf-2-checkboxes-example/

在 JSF,<h:selectBooleanCheckbox/>标签用于呈现“ checkbox 类型的单个 HTML 输入元素。

 //JSF...
<h:selectBooleanCheckbox value="#{user.rememberMe}" /> Remember Me

//HTML output...
<input type="checkbox" name="j_idt6:j_idt8" /> Remember Me 

<h:selectmany Checkbox/>标签用于渲染一组“checkbox”类型的 HTML 输入元素,并用 HTML 表格和标签标签对其进行格式化。

 //JSF...
<h:selectManyCheckbox value="#{user.favNumber1}">
   	<f:selectItem itemValue="1" itemLabel="Number1 - 1" />
   	<f:selectItem itemValue="2" itemLabel="Number1 - 2" />
   	<f:selectItem itemValue="3" itemLabel="Number1 - 3" />
</h:selectManyCheckbox>

//HTML output...
<table>
<tr>
  <td>
	<input name="j_idt6:j_idt10" id="j_idt6:j_idt10:0" value="1" type="checkbox" />
	<label for="j_idt6:j_idt10:0" class=""> Number1 - 1</label></td>
  <td>
	<input name="j_idt6:j_idt10" id="j_idt6:j_idt10:1" value="2" type="checkbox" />
	<label for="j_idt6:j_idt10:1" class=""> Number1 - 2</label></td>
  <td>
	<input name="j_idt6:j_idt10" id="j_idt6:j_idt10:2" value="3" type="checkbox" />
	<label for="j_idt6:j_idt10:2" class=""> Number1 - 3</label></td>
  <td>
</tr>
</table> 

JSF 2.0 示例

这里有一个 JSF 2.0 的例子来展示“ h:selectBooleanCheckbox ”和“ h:selectManyCheckbox ”标签的使用。

h:selectBooleanCheckbox
渲染单个复选框,用布尔属性绑定。

h:selectManyCheckbox
呈现一组复选框,以不同的方式填充数据:

  1. f:selecti item标签中的硬核值。
  2. 用数组生成值,放入“f:selecti items标签。
  3. 用 Map 生成值,并将其放入“f:selecti items标签中。
  4. 用一个对象数组生成值,放入“ f:selectItems ”标签,然后用“ var 属性表示值。

1.支撑豆

用于保存提交的复选框值的后备 bean。

 package com.mkyong;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean(name="user")
@SessionScoped
public class UserBean{

	public boolean rememberMe;
	public String[] favNumber1;
	public String[] favNumber2;
	public String[] favNumber3;
	public String[] favNumber4;

	//getter and setter methods...

	public String getFavNumber1InString() {
		return Arrays.toString(favNumber1);
	}

	//Generated by Array
	public String[] getFavNumber2Value() {

		favNumber2 = new String[5];
		favNumber2[0] = "Number2 - 1";
		favNumber2[1] = "Number2 - 2";
		favNumber2[2] = "Number2 - 3";
		favNumber2[3] = "Number2 - 4";
		favNumber2[4] = "Number2 - 5";

		return favNumber2;
	}

	public String getFavNumber2InString() {
		return Arrays.toString(favNumber2);
	}

	//Generated by Map
	private static Map<String,Object> number3Value;
	static{
		number3Value = new LinkedHashMap<String,Object>();
		number3Value.put("Number3 - 1", "1"); //label, value
		number3Value.put("Number3 - 2", "2");
		number3Value.put("Number3 - 3", "3");
		number3Value.put("Number3 - 4", "4");
		number3Value.put("Number3 - 5", "5");
	}

	public Map<String,Object> getFavNumber3Value() {
		return number3Value;
	}

	public String getFavNumber3InString() {
		return Arrays.toString(favNumber3);
	}

	//Generated by Object array
	public static class Number{
		public String numberLabel;
		public String numberValue;

		public Number(String numberLabel, String numberValue){
			this.numberLabel = numberLabel;
			this.numberValue = numberValue;
		}

		public String getNumberLabel(){
			return numberLabel;
		}

		public String getNumberValue(){
			return numberValue;
		}

	}

	public Number[] number4List;

	public Number[] getFavNumber4Value() {

		number4List = new Number[5];
		number4List[0] = new Number("Number4 - 1", "1");
		number4List[1] = new Number("Number4 - 2", "2");
		number4List[2] = new Number("Number4 - 3", "3");
		number4List[3] = new Number("Number4 - 4", "4");
		number4List[4] = new Number("Number4 - 5", "5");

		return number4List;
	}

	public String getFavNumber4InString() {
		return Arrays.toString(favNumber4);
	}

} 

2.JSF·佩奇

一个 JSF 页面,演示了“ h:selectBooleanCheckbox ”和“ h:selectManyCheckbox ”标签的使用。

 <?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"
      >
    <h:body>

    	<h1>JSF 2 checkboxes example</h1>
    	<h:form>

    	    <h2>1\. Single checkbox</h2>
	    <h:selectBooleanCheckbox value="#{user.rememberMe}" /> Remember Me

	    <h2>2\. Mutiple checkboxes</h2>

	    1\. Hard-coded with "f:selectItem" : 
   		<h:selectManyCheckbox value="#{user.favNumber1}">
   			<f:selectItem itemValue="1" itemLabel="Number1 - 1" />
   			<f:selectItem itemValue="2" itemLabel="Number1 - 2" />
   			<f:selectItem itemValue="3" itemLabel="Number1 - 3" />
   			<f:selectItem itemValue="4" itemLabel="Number1 - 4" />
   			<f:selectItem itemValue="5" itemLabel="Number1 - 5" />
   		</h:selectManyCheckbox>

	    <br />

	    2\. Generated by Array :
   		<h:selectManyCheckbox value="#{user.favNumber2}">
   			<f:selectItems value="#{user.favNumber2Value}" />
   		</h:selectManyCheckbox>

   		<br />

	    3\. Generated by Map :
   		<h:selectManyCheckbox value="#{user.favNumber3}">
   			<f:selectItems value="#{user.favNumber3Value}" />
   		</h:selectManyCheckbox>

	    <br />

	    4\. Generated by Object with var :
   		<h:selectManyCheckbox value="#{user.favNumber4}">
   			<f:selectItems value="#{user.favNumber4Value}" var="n"
   			itemLabel="#{n.numberLabel}" itemValue="#{n.numberValue}" />
   		</h:selectManyCheckbox>

	    <br />

    	    <h:commandButton value="Submit" action="result" />
	    <h:commandButton value="Reset" type="reset" />

    	</h:form>

    </h:body>
</html> 

result.xhtml…

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

    <h:body>

    	<h1>JSF 2 checkboxes example</h1>

    	<h2>result.xhtml</h2>

    	<ol>
    		<li>user.rememberMe : #{user.rememberMe}</li>
    		<li>user.favNumber1 : #{user.favNumber1InString}</li>
    		<li>user.favNumber2 : #{user.favNumber2InString}</li>
    		<li>user.favNumber3 : #{user.favNumber3InString}</li>
    		<li>user.favNumber4 : #{user.favNumber4InString}</li>
    	</ol>
    </h:body>

</html> 

3.演示

jsf2-checkboxes-example-1

单击“提交”按钮时,链接到“result.xhtml”页面并显示提交的 checkboxe 值。

jsf2-checkboxes-example-2

如何默认检查复选框的值?

h:selectBooleanCheckbox
如果布尔值设置为 true,则检查“f:selectItem”标签的值。在上面的示例中,如果您将布尔属性“rememberMe”设置为 true:

 @ManagedBean(name="user")
@SessionScoped
public class UserBean{

	public boolean rememberMe = true;

	//... 

默认情况下,“记住我”复选框值处于选中状态。

h:selectManyCheckbox
检查“f:selectItems”标签的值是否与“h:selectManyCheckbox”标签的“value”匹配。在上面的示例中,如果您将收藏编号 3 设置为{ " 1 "," 3 " }:

 @ManagedBean(name="user")
@SessionScoped
public class UserBean{

	public String[] favNumber3 = {"1","3"};

	//... 

默认情况下,“收藏数字 3”复选框、“数字 1”和“数字 3”值处于选中状态。

下载源代码

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

参考

  1. JSF<h:select boolean checkbox/>JavaDoc
  2. JSF < h:选择多个复选框。html/ > JavaDoc

复选框JSF 2

JSF 新协议转换日期示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jsf2/jsf-2-convertdatetime-example/

f:convertDateTime "是一个标准的 JSF 转换器标签,它将字符串转换成指定的“日期”格式。此外,它还用于实现日期验证。

下面的 JSF 2.0 示例向您展示了如何使用这个" f:convertDateTime "标记。

1.受管 Bean

一个简单的托管 bean,具有“日期”属性。

 package com.mkyong;

import java.io.Serializable;
import java.util.Date;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean(name="receipt")
@SessionScoped
public class ReceiptBean implements Serializable{

	Date date;

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

} 

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

2.f:convertDateTime 示例

用“ f:convertDateTime 标签实现日期验证。接受的日期格式在“模式属性中定义。

Note
The date format in “pattern” attribute is defined in the java.text.SimpleDateFormat.

default.xhtml

 <?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:c="http://java.sun.com/jsp/jstl/core"
      >
    <h:body>

    	<h1>JSF 2 convertDate example</h1>

	<h:form>

		<h:panelGrid columns="3">

		  Receipt Date : 
		 <h:inputText id="date" value="#{receipt.date}" 
			size="20" required="true"
			label="Receipt Date" >

			<f:convertDateTime pattern="d-M-yyyy" />
		  </h:inputText>

		  <h:message for="date" style="color:red" />

		</h:panelGrid>

		<h:commandButton value="Submit" action="receipt" />

	   </h:form>

    </h:body>
</html> 

receipt.xhtml

 <?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:c="http://java.sun.com/jsp/jstl/core"
      >
    <h:body>

    	<h1>JSF 2 convertDate example</h1>

		Receipt Date :  
		<h:outputText value="#{receipt.date}" >
			<f:convertDateTime pattern="d-M-yyyy" />
		</h:outputText>

    </h:body>
</html> 

3.演示

如果提供的日期无效,则显示错误消息。

jsf2-ConvertDateTime-Example

下载源代码

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

参考

  1. JSF 2 号 convertDateTime JavaDoc
  2. 简单日期格式 JavaDoc

Tags : date jsf2freestar.config.enabled_slots.push({ placementName: "mkyong_leaderboard_btf", slotId: "mkyong_leaderboard_btf" });

JSF 新协议转换编号示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/jsf2/jsf-2-convertnumber-example/

在 JSF,“ f:convertNumber ”是一个标准的转换器,将字符串转换成指定的“数字”格式。此外,它还用作验证器来确保输入值是有效的数字。请参见以下常用示例:

:假设#{receipt.amount}包含一个“ 0.1 值。

1。minFractionDigits 属性

 <h:outputText value="#{receipt.amount}" >
	<f:convertNumber minFractionDigits="2" />
</h:outputText> 

将值显示为“0.10”。

2。图案属性

 <h:outputText value="#{receipt.amount}" >
	<f:convertNumber pattern="#0.000" />
</h:outputText> 

将值显示为“0.100”。

Note
The pattern format is defined in java.text.DecimalFormat.

3。货币代码属性

 <h:outputText value="#{receipt.amount}" >
	<f:convertNumber currencyCode="GBP" type="currency" />
</h:outputText> 

将值显示为“GBP0.10”。

Note
The currencyCode is defined in ISO 4217. To use currencyCode attribute, the type attribute have to change to “currency“.

4。type="percent "属性

 <h:outputText value="#{receipt.amount}" >
	<f:convertNumber type="percent" />
</h:outputText> 

将该值显示为“10%”。

P.S 其他“f:convertNumber”属性,可以访问这个JSF“f:convert number”JavaDoc

JSF f:convertNumber 示例

下面的 JSF 2.0 完整示例向您展示了如何使用" f:convertNumber "标签。

1.受管 Bean

一个简单的托管 bean,具有“amount”属性。

 package com.mkyong;

import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean(name="receipt")
@SessionScoped
public class ReceiptBean implements Serializable{

	double amount;

	public double getAmount() {
		return amount;
	}

	public void setAmount(double amount) {
		this.amount = amount;
	}

} 

2.f:convertNumber 示例

JSF XHTML 页面使用“ f:convertNumber ”标签进行验证,也是字符串格式化程序。

default.xhtml

 <?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:c="http://java.sun.com/jsp/jstl/core"
      >
    <h:body>

    	<h1>JSF 2 convertNumber example</h1>

	   <h:form>

		<h:panelGrid columns="3">

			Amount : 
			<h:inputText id="amount" value="#{receipt.amount}" 
				size="20" required="true"
				label="Amount" >
				<!-- display in at least 2 decimal points -->
				<f:convertNumber minFractionDigits="2" />
			</h:inputText>

			<h:message for="amount" style="color:red" />

		</h:panelGrid>

		<h:commandButton value="Submit" action="receipt" />

	   </h:form>

    </h:body>
</html> 

receipt.xhtml

 <?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:c="http://java.sun.com/jsp/jstl/core"
      >
    <h:body>

    	<h1>JSF 2 convertNumber example</h1>

	  <ol>
		<li>
			Amount [minFractionDigits="2"] : 
			<h:outputText value="#{receipt.amount}" >
				<f:convertNumber minFractionDigits="2" />
			</h:outputText>
		</li>
		<li>
			Amount [pattern="#0.000"] : 
			<h:outputText value="#{receipt.amount}" >
				<f:convertNumber pattern="#0.000" />
			</h:outputText>
		</li>
		<li>
			Amount [currencySymbol="$"] : 
			<h:outputText value="#{receipt.amount}">
				<f:convertNumber currencySymbol="$" type="currency" />
			</h:outputText>
		</li>
		<li>
			Amount [currencyCode="GBP"] : 
			<h:outputText value="#{receipt.amount}" >
				<f:convertNumber currencyCode="GBP" type="currency" />
			</h:outputText>
		</li>
		<li>
			Amount [type="percent"] : 
			<h:outputText value="#{receipt.amount}" >
				<f:convertNumber type="percent" />
			</h:outputText>
		</li>
	   </ol>

    </h:body>
</html> 

3.演示

如果用户填写了无效的数字格式,则显示错误消息。

jsf2-ConvertNumber-Example-1

用户键入一个" 0.01 值并点击"提交"按钮。

jsf2-ConvertNumber-Example-2

将提交的值显示为不同的显示格式。

jsf2-ConvertNumber-Example-3

下载源代码

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

参考

  1. JSF 2 号转换器 JavaDoc
  2. 维基 ISO 4217 当前代码
  3. DecimalFormat JavaDoc

jsf2

posted @ 2024-11-01 16:32  绝不原创的飞龙  阅读(15)  评论(0编辑  收藏  举报