首页 文章 精选 留言 我的

精选列表

搜索[webpack入门],共10000篇文章
优秀的个人博客,低调大师

Golang 入门系列(四)如何理解interface接口

前面讲了很多Go 语言的基础知识,包括go环境的安装,go语言的语法等,感兴趣的朋友,可以先看看之前的文章。https://www.cnblogs.com/zhangweizhong/category/1275863.html 今天就正式开始写Go 的代码,讲讲如何理解interface接口。 1. 什么是interface接口 interface 是GO语言的基础特性之一。可以理解为一种类型的规范或者约定。它跟java,C# 不太一样,不需要显示说明实现了某个接口,它没有继承或子类或“implements”关键字,只是通过约定的形式,隐式的实现interface 中的方法即可。因此,Golang 中的 interface 让编码更灵活、易扩展。 如何理解go 语言中的interface ? 只需记住以下三点即可: 1.interface 是方法声明的集合 2. 任何类型的对象实现了在interface 接口中声明的全部方法,则表明该类型实现了该接口。 3. interface 可以作为一种数据类型,实现了该接口的任何对象都可以给对应的接口类型变量赋值。 注意: a. interface 可以被任意对象实现,一个类型/对象也可以实现多个 interface b. 方法不能重载,如 eat() eat(s string) 不能同时存在 2. 接口实现 package main import "fmt" type Phone interface { call() } type NokiaPhone struct { } func (nokiaPhone NokiaPhone) call() { fmt.Println("I am Nokia, I can call you!") } type ApplePhone struct { } func (iPhone ApplePhone) call() { fmt.Println("I am Apple Phone, I can call you!") } func main() { var phone Phone phone = new(NokiaPhone) phone.call() phone = new(ApplePhone) phone.call() } 3. interface 查询 如果接口A实现了接口B中所有方法,那么A可以转化为B接口。 if varName2, ok := varName1.(interface2|typeName); ok { //此时 varName2 的类型由 interface1 转为 interface2,或者 varName1 不是 typeName 类型的变量 } else { //不能转换 interface,或者 varName1 不是 typeName 类型的变量 4. interface{} 类型 interface{} 类型没有声明任何一个方法,俗称空接口。interface{} 在我们需要存储任意类型的数值的时候相当有用,有点类似于C语言的void*类型。 package main import ( "fmt" ) func PrintAll(vals []interface{}) { for _, val := range vals { fmt.Println(val) } } func main() { names := []string{"stanley", "david", "oscar"} vals := make([]interface{}, len(names)) for i, v := range names { vals[i] = v } PrintAll(vals) } 然而,需要注意的是,[]T不能直接赋值给[]interface{} t := []int{1, 2, 3, 4} var s []interface{} = t 编译时会输出下面的错误: cannot use t (type []int) as type []interface {} in assignment 最后 以上,对Go 语言中的接口特性做了一个简单的介绍。我觉得对于go语言来说,设计最精妙的应该是interface了,感兴趣的,可以好好研究研究。 作者:章为忠 出处:http://www.fpeach.com/ 本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。如有问题,可以微信:18618243664联系我,非常感谢。扫下面的二维码关注我的微信公众号。

优秀的个人博客,低调大师

Java_脚本引擎_01_用法入门

一、前言 最近有个需求,需要在js中调用java,这样能避免更新java,从而实现代码的热更新。 于是想到用NashornJavaScript 引擎。 二、概述 通过 JDK 8 的 NashornJavaScript 引擎 ,可以很方便的实现在java中调用js,以及在js中调用java。 三、简单示例 1.java中调用js @Test public void testDemo1() throws ScriptException { //1.创建引擎 ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); //2.要执行的脚本 String script = "var sum = n1 + n2;print(msg + ' n1= '+ n1 + '; n2 ='+ n2 + '; sum=' + sum);"; manager.put("n1", 1); //3.执行脚本 //3.1 直接传参,并执行脚本 engine.put("n2", 2); //使用put(key,value)直接传参到到脚本中,在脚本中通过key来取值 engine.put("msg", "a string"); engine.eval(script); //3.2 通过绑定传参,并执行脚本 Bindings bindings = engine.createBindings(); bindings.put("n2", 3); // AbstractScriptEngine.put(key,value)的内部实现就是使用的Bindings.put(key,value) bindings.put("msg", "another string"); engine.eval(script, bindings); //3.3 通过上下文来传参,并执行脚本 ScriptContext ctx = new SimpleScriptContext(); Bindings ctxGlobalBindings = engine.createBindings(); ctx.setBindings(ctxGlobalBindings, GLOBAL_SCOPE); ctx.setAttribute("n1", 4, GLOBAL_SCOPE); ctx.setAttribute("n2", 5, ENGINE_SCOPE); ctx.setAttribute("msg", "ScriptContext:", ENGINE_SCOPE); engine.eval(script, ctx); //使用指定上下文来执行脚本 engine.eval(script); //使用默认上下文执行脚本 } View Code 2.js中调用java HelloWorld.java public class HelloWorld { public void sayHello(){ System.out.println("hello"); } } View Code 测试用例: @Test public void test2() throws ScriptException { //1.创建引擎 ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); //2.设置要执行的脚本 String script="$hello.sayHello();"; //3.传参,并执行脚本 engine.put("$hello", new HelloWorld()); engine.eval(script); //使用指定上下文来执行脚本 } View Code 3.通过js实现java接口 参见:Java脚本教程 - Java脚本实现接口 四、脚本引擎类结构图 脚本引擎相关源码的类和接口如下: 先关注这几个基本实现类 1. ScriptEngineManager 源码如下: /* * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package javax.script; import java.util.*; import java.security.*; import java.util.ServiceLoader; import java.util.ServiceConfigurationError; /** * The <code>ScriptEngineManager</code> implements a discovery and instantiation * mechanism for <code>ScriptEngine</code> classes and also maintains a * collection of key/value pairs storing state shared by all engines created * by the Manager. This class uses the <a href="../../../technotes/guides/jar/jar.html#Service%20Provider">service provider</a> mechanism to enumerate all the * implementations of <code>ScriptEngineFactory</code>. <br><br> * The <code>ScriptEngineManager</code> provides a method to return a list of all these factories * as well as utility methods which look up factories on the basis of language name, file extension * and mime type. * <p> * The <code>Bindings</code> of key/value pairs, referred to as the "Global Scope" maintained * by the manager is available to all instances of <code>ScriptEngine</code> created * by the <code>ScriptEngineManager</code>. The values in the <code>Bindings</code> are * generally exposed in all scripts. * * @author Mike Grogan * @author A. Sundararajan * @since 1.6 */ public class ScriptEngineManager { private static final boolean DEBUG = false; /** * The effect of calling this constructor is the same as calling * <code>ScriptEngineManager(Thread.currentThread().getContextClassLoader())</code>. * * @see java.lang.Thread#getContextClassLoader */ public ScriptEngineManager() { ClassLoader ctxtLoader = Thread.currentThread().getContextClassLoader(); init(ctxtLoader); } /** * This constructor loads the implementations of * <code>ScriptEngineFactory</code> visible to the given * <code>ClassLoader</code> using the <a href="../../../technotes/guides/jar/jar.html#Service%20Provider">service provider</a> mechanism.<br><br> * If loader is <code>null</code>, the script engine factories that are * bundled with the platform and that are in the usual extension * directories (installed extensions) are loaded. <br><br> * * @param loader ClassLoader used to discover script engine factories. */ public ScriptEngineManager(ClassLoader loader) { init(loader); } private void init(final ClassLoader loader) { globalScope = new SimpleBindings(); engineSpis = new HashSet<ScriptEngineFactory>(); nameAssociations = new HashMap<String, ScriptEngineFactory>(); extensionAssociations = new HashMap<String, ScriptEngineFactory>(); mimeTypeAssociations = new HashMap<String, ScriptEngineFactory>(); initEngines(loader); } private ServiceLoader<ScriptEngineFactory> getServiceLoader(final ClassLoader loader) { if (loader != null) { return ServiceLoader.load(ScriptEngineFactory.class, loader); } else { return ServiceLoader.loadInstalled(ScriptEngineFactory.class); } } private void initEngines(final ClassLoader loader) { Iterator<ScriptEngineFactory> itr = null; try { ServiceLoader<ScriptEngineFactory> sl = AccessController.doPrivileged( new PrivilegedAction<ServiceLoader<ScriptEngineFactory>>() { @Override public ServiceLoader<ScriptEngineFactory> run() { return getServiceLoader(loader); } }); itr = sl.iterator(); } catch (ServiceConfigurationError err) { System.err.println("Can't find ScriptEngineFactory providers: " + err.getMessage()); if (DEBUG) { err.printStackTrace(); } // do not throw any exception here. user may want to // manage his/her own factories using this manager // by explicit registratation (by registerXXX) methods. return; } try { while (itr.hasNext()) { try { ScriptEngineFactory fact = itr.next(); engineSpis.add(fact); } catch (ServiceConfigurationError err) { System.err.println("ScriptEngineManager providers.next(): " + err.getMessage()); if (DEBUG) { err.printStackTrace(); } // one factory failed, but check other factories... continue; } } } catch (ServiceConfigurationError err) { System.err.println("ScriptEngineManager providers.hasNext(): " + err.getMessage()); if (DEBUG) { err.printStackTrace(); } // do not throw any exception here. user may want to // manage his/her own factories using this manager // by explicit registratation (by registerXXX) methods. return; } } /** * <code>setBindings</code> stores the specified <code>Bindings</code> * in the <code>globalScope</code> field. ScriptEngineManager sets this * <code>Bindings</code> as global bindings for <code>ScriptEngine</code> * objects created by it. * * @param bindings The specified <code>Bindings</code> * @throws IllegalArgumentException if bindings is null. */ public void setBindings(Bindings bindings) { if (bindings == null) { throw new IllegalArgumentException("Global scope cannot be null."); } globalScope = bindings; } /** * <code>getBindings</code> returns the value of the <code>globalScope</code> field. * ScriptEngineManager sets this <code>Bindings</code> as global bindings for * <code>ScriptEngine</code> objects created by it. * * @return The globalScope field. */ public Bindings getBindings() { return globalScope; } /** * Sets the specified key/value pair in the Global Scope. * @param key Key to set * @param value Value to set. * @throws NullPointerException if key is null. * @throws IllegalArgumentException if key is empty string. */ public void put(String key, Object value) { globalScope.put(key, value); } /** * Gets the value for the specified key in the Global Scope * @param key The key whose value is to be returned. * @return The value for the specified key. */ public Object get(String key) { return globalScope.get(key); } /** * Looks up and creates a <code>ScriptEngine</code> for a given name. * The algorithm first searches for a <code>ScriptEngineFactory</code> that has been * registered as a handler for the specified name using the <code>registerEngineName</code> * method. * <br><br> If one is not found, it searches the set of <code>ScriptEngineFactory</code> instances * stored by the constructor for one with the specified name. If a <code>ScriptEngineFactory</code> * is found by either method, it is used to create instance of <code>ScriptEngine</code>. * @param shortName The short name of the <code>ScriptEngine</code> implementation. * returned by the <code>getNames</code> method of its <code>ScriptEngineFactory</code>. * @return A <code>ScriptEngine</code> created by the factory located in the search. Returns null * if no such factory was found. The <code>ScriptEngineManager</code> sets its own <code>globalScope</code> * <code>Bindings</code> as the <code>GLOBAL_SCOPE</code> <code>Bindings</code> of the newly * created <code>ScriptEngine</code>. * @throws NullPointerException if shortName is null. */ public ScriptEngine getEngineByName(String shortName) { if (shortName == null) throw new NullPointerException(); //look for registered name first Object obj; if (null != (obj = nameAssociations.get(shortName))) { ScriptEngineFactory spi = (ScriptEngineFactory)obj; try { ScriptEngine engine = spi.getScriptEngine(); engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE); return engine; } catch (Exception exp) { if (DEBUG) exp.printStackTrace(); } } for (ScriptEngineFactory spi : engineSpis) { List<String> names = null; try { names = spi.getNames(); } catch (Exception exp) { if (DEBUG) exp.printStackTrace(); } if (names != null) { for (String name : names) { if (shortName.equals(name)) { try { ScriptEngine engine = spi.getScriptEngine(); engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE); return engine; } catch (Exception exp) { if (DEBUG) exp.printStackTrace(); } } } } } return null; } /** * Look up and create a <code>ScriptEngine</code> for a given extension. The algorithm * used by <code>getEngineByName</code> is used except that the search starts * by looking for a <code>ScriptEngineFactory</code> registered to handle the * given extension using <code>registerEngineExtension</code>. * @param extension The given extension * @return The engine to handle scripts with this extension. Returns <code>null</code> * if not found. * @throws NullPointerException if extension is null. */ public ScriptEngine getEngineByExtension(String extension) { if (extension == null) throw new NullPointerException(); //look for registered extension first Object obj; if (null != (obj = extensionAssociations.get(extension))) { ScriptEngineFactory spi = (ScriptEngineFactory)obj; try { ScriptEngine engine = spi.getScriptEngine(); engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE); return engine; } catch (Exception exp) { if (DEBUG) exp.printStackTrace(); } } for (ScriptEngineFactory spi : engineSpis) { List<String> exts = null; try { exts = spi.getExtensions(); } catch (Exception exp) { if (DEBUG) exp.printStackTrace(); } if (exts == null) continue; for (String ext : exts) { if (extension.equals(ext)) { try { ScriptEngine engine = spi.getScriptEngine(); engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE); return engine; } catch (Exception exp) { if (DEBUG) exp.printStackTrace(); } } } } return null; } /** * Look up and create a <code>ScriptEngine</code> for a given mime type. The algorithm * used by <code>getEngineByName</code> is used except that the search starts * by looking for a <code>ScriptEngineFactory</code> registered to handle the * given mime type using <code>registerEngineMimeType</code>. * @param mimeType The given mime type * @return The engine to handle scripts with this mime type. Returns <code>null</code> * if not found. * @throws NullPointerException if mimeType is null. */ public ScriptEngine getEngineByMimeType(String mimeType) { if (mimeType == null) throw new NullPointerException(); //look for registered types first Object obj; if (null != (obj = mimeTypeAssociations.get(mimeType))) { ScriptEngineFactory spi = (ScriptEngineFactory)obj; try { ScriptEngine engine = spi.getScriptEngine(); engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE); return engine; } catch (Exception exp) { if (DEBUG) exp.printStackTrace(); } } for (ScriptEngineFactory spi : engineSpis) { List<String> types = null; try { types = spi.getMimeTypes(); } catch (Exception exp) { if (DEBUG) exp.printStackTrace(); } if (types == null) continue; for (String type : types) { if (mimeType.equals(type)) { try { ScriptEngine engine = spi.getScriptEngine(); engine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE); return engine; } catch (Exception exp) { if (DEBUG) exp.printStackTrace(); } } } } return null; } /** * Returns a list whose elements are instances of all the <code>ScriptEngineFactory</code> classes * found by the discovery mechanism. * @return List of all discovered <code>ScriptEngineFactory</code>s. */ public List<ScriptEngineFactory> getEngineFactories() { List<ScriptEngineFactory> res = new ArrayList<ScriptEngineFactory>(engineSpis.size()); for (ScriptEngineFactory spi : engineSpis) { res.add(spi); } return Collections.unmodifiableList(res); } /** * Registers a <code>ScriptEngineFactory</code> to handle a language * name. Overrides any such association found using the Discovery mechanism. * @param name The name to be associated with the <code>ScriptEngineFactory</code>. * @param factory The class to associate with the given name. * @throws NullPointerException if any of the parameters is null. */ public void registerEngineName(String name, ScriptEngineFactory factory) { if (name == null || factory == null) throw new NullPointerException(); nameAssociations.put(name, factory); } /** * Registers a <code>ScriptEngineFactory</code> to handle a mime type. * Overrides any such association found using the Discovery mechanism. * * @param type The mime type to be associated with the * <code>ScriptEngineFactory</code>. * * @param factory The class to associate with the given mime type. * @throws NullPointerException if any of the parameters is null. */ public void registerEngineMimeType(String type, ScriptEngineFactory factory) { if (type == null || factory == null) throw new NullPointerException(); mimeTypeAssociations.put(type, factory); } /** * Registers a <code>ScriptEngineFactory</code> to handle an extension. * Overrides any such association found using the Discovery mechanism. * * @param extension The extension type to be associated with the * <code>ScriptEngineFactory</code>. * @param factory The class to associate with the given extension. * @throws NullPointerException if any of the parameters is null. */ public void registerEngineExtension(String extension, ScriptEngineFactory factory) { if (extension == null || factory == null) throw new NullPointerException(); extensionAssociations.put(extension, factory); } /** Set of script engine factories discovered. */ private HashSet<ScriptEngineFactory> engineSpis; /** Map of engine name to script engine factory. */ private HashMap<String, ScriptEngineFactory> nameAssociations; /** Map of script file extension to script engine factory. */ private HashMap<String, ScriptEngineFactory> extensionAssociations; /** Map of script script MIME type to script engine factory. */ private HashMap<String, ScriptEngineFactory> mimeTypeAssociations; /** Global bindings associated with script engines created by this manager. */ private Bindings globalScope; } View Code 此类主要有三个作用: (1)设置全局变量 (2)获取脚本引擎 (3)注册脚本引擎工厂 (1)设置全局变量 /** Global bindings associated with script engines created by this manager. */ private Bindings globalScope; public void put(String key, Object value) { globalScope.put(key, value); } public Object get(String key) { return globalScope.get(key); } 可以看到,通过ScriptEngineManager 设置的变量都绑定到了 globalScope 这个绑定中。 这里并不能说明这个一个全局绑定。 再往下看: 此处设置了绑定的作用域为全局。因此可通过 ScriptEngineManager 设置全局变量 (2)获取脚本引擎 可通过以下方法获取脚本引擎 2.SimpleBindings 绑定是用来存放变量的。 simpleBingdings是 绑定的基本实现类,源码如下 /* * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package javax.script; import java.util.Map; import java.util.HashMap; import java.util.Collection; import java.util.Set; /** * A simple implementation of Bindings backed by * a <code>HashMap</code> or some other specified <code>Map</code>. * * @author Mike Grogan * @since 1.6 */ public class SimpleBindings implements Bindings { /** * The <code>Map</code> field stores the attributes. */ private Map<String,Object> map; /** * Constructor uses an existing <code>Map</code> to store the values. * @param m The <code>Map</code> backing this <code>SimpleBindings</code>. * @throws NullPointerException if m is null */ public SimpleBindings(Map<String,Object> m) { if (m == null) { throw new NullPointerException(); } this.map = m; } /** * Default constructor uses a <code>HashMap</code>. */ public SimpleBindings() { this(new HashMap<String,Object>()); } /** * Sets the specified key/value in the underlying <code>map</code> field. * * @param name Name of value * @param value Value to set. * * @return Previous value for the specified key. Returns null if key was previously * unset. * * @throws NullPointerException if the name is null. * @throws IllegalArgumentException if the name is empty. */ public Object put(String name, Object value) { checkKey(name); return map.put(name,value); } /** * <code>putAll</code> is implemented using <code>Map.putAll</code>. * * @param toMerge The <code>Map</code> of values to add. * * @throws NullPointerException * if toMerge map is null or if some key in the map is null. * @throws IllegalArgumentException * if some key in the map is an empty String. */ public void putAll(Map<? extends String, ? extends Object> toMerge) { if (toMerge == null) { throw new NullPointerException("toMerge map is null"); } for (Map.Entry<? extends String, ? extends Object> entry : toMerge.entrySet()) { String key = entry.getKey(); checkKey(key); put(key, entry.getValue()); } } /** {@inheritDoc} */ public void clear() { map.clear(); } /** * Returns <tt>true</tt> if this map contains a mapping for the specified * key. More formally, returns <tt>true</tt> if and only if * this map contains a mapping for a key <tt>k</tt> such that * <tt>(key==null ? k==null : key.equals(k))</tt>. (There can be * at most one such mapping.) * * @param key key whose presence in this map is to be tested. * @return <tt>true</tt> if this map contains a mapping for the specified * key. * * @throws NullPointerException if key is null * @throws ClassCastException if key is not String * @throws IllegalArgumentException if key is empty String */ public boolean containsKey(Object key) { checkKey(key); return map.containsKey(key); } /** {@inheritDoc} */ public boolean containsValue(Object value) { return map.containsValue(value); } /** {@inheritDoc} */ public Set<Map.Entry<String, Object>> entrySet() { return map.entrySet(); } /** * Returns the value to which this map maps the specified key. Returns * <tt>null</tt> if the map contains no mapping for this key. A return * value of <tt>null</tt> does not <i>necessarily</i> indicate that the * map contains no mapping for the key; it's also possible that the map * explicitly maps the key to <tt>null</tt>. The <tt>containsKey</tt> * operation may be used to distinguish these two cases. * * <p>More formally, if this map contains a mapping from a key * <tt>k</tt> to a value <tt>v</tt> such that <tt>(key==null ? k==null : * key.equals(k))</tt>, then this method returns <tt>v</tt>; otherwise * it returns <tt>null</tt>. (There can be at most one such mapping.) * * @param key key whose associated value is to be returned. * @return the value to which this map maps the specified key, or * <tt>null</tt> if the map contains no mapping for this key. * * @throws NullPointerException if key is null * @throws ClassCastException if key is not String * @throws IllegalArgumentException if key is empty String */ public Object get(Object key) { checkKey(key); return map.get(key); } /** {@inheritDoc} */ public boolean isEmpty() { return map.isEmpty(); } /** {@inheritDoc} */ public Set<String> keySet() { return map.keySet(); } /** * Removes the mapping for this key from this map if it is present * (optional operation). More formally, if this map contains a mapping * from key <tt>k</tt> to value <tt>v</tt> such that * <code>(key==null ? k==null : key.equals(k))</code>, that mapping * is removed. (The map can contain at most one such mapping.) * * <p>Returns the value to which the map previously associated the key, or * <tt>null</tt> if the map contained no mapping for this key. (A * <tt>null</tt> return can also indicate that the map previously * associated <tt>null</tt> with the specified key if the implementation * supports <tt>null</tt> values.) The map will not contain a mapping for * the specified key once the call returns. * * @param key key whose mapping is to be removed from the map. * @return previous value associated with specified key, or <tt>null</tt> * if there was no mapping for key. * * @throws NullPointerException if key is null * @throws ClassCastException if key is not String * @throws IllegalArgumentException if key is empty String */ public Object remove(Object key) { checkKey(key); return map.remove(key); } /** {@inheritDoc} */ public int size() { return map.size(); } /** {@inheritDoc} */ public Collection<Object> values() { return map.values(); } private void checkKey(Object key) { if (key == null) { throw new NullPointerException("key can not be null"); } if (!(key instanceof String)) { throw new ClassCastException("key should be a String"); } if (key.equals("")) { throw new IllegalArgumentException("key can not be empty"); } } } View Code 可以发现绑定的内部实现时通过HashMap来实现的。 Bingding通过HashMap来存放变量。 3.SimpleScriptContext 脚本引擎是在脚本上下文中执行的。 脚本上下文由四个组件组成: 与不同范围相关联的绑定。上下文中的绑定将参数传递给脚本。 读取器读取输入 写入输出 写入错误输出的错误写入器 绑定是是有作用域的,有两个作用域: ScriptContext.ENGINE_SCOPE (引擎范围,值为100) ScriptContext.GLOBAL_SCOPE (全局范围,值为200) (1) 设置变量: public void setAttribute(String var1, Object var2, int var3) { this.checkName(var1); switch(var3) { case 100: this.engineScope.put(var1, var2); return; case 200: if (this.globalScope != null) { this.globalScope.put(var1, var2); } return; default: throw new IllegalArgumentException("Illegal scope value."); } } protected Bindings engineScope = new SimpleBindings(); protected Bindings globalScope = null; View Code 可以看到全局绑定默认为空。回到 三、简单示例 中,如下: //3.3 通过上下文来传参,并执行脚本 ScriptContext ctx = new SimpleScriptContext(); Bindings ctxGlobalBindings = engine.createBindings(); ctx.setBindings(ctxGlobalBindings, GLOBAL_SCOPE); ctx.setAttribute("n1", 4, GLOBAL_SCOPE); ctx.setAttribute("n2", 5, ENGINE_SCOPE); ctx.setAttribute("msg", "ScriptContext:", ENGINE_SCOPE); engine.eval(script, ctx); //使用指定上下文来执行脚本 设置全局变量的步骤:我们先设置了一个全局绑定,这样全局绑定就不为空,然后再设置全局变量。 4.ScriptEngine ScriptEngine提供了如下接口, 抽象类AbstractScriptEngine实现了ScriptEngine的部分基本方法。 脚本引擎实际的执行者 NashornScriptEngine 继承自AbstractScriptEngine 实现了ScriptEngine的全部方法,功能强大。 五、参考资料 1.Java 脚本引擎—w3cschool 我的博客即将搬运同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=8rf7kovqfyoo

优秀的个人博客,低调大师

Java入门之初识设计模式---单列模式

设计模式 是软件开发人员在软件开发过程中面临的一般问题的解决方案 单例模式 目的:使得类的一个对象成为该类系统中的唯一实例 定义:一个类有且仅有一个实例,并且自行实例化向整个系统提供 因此,设计要点是: 某个类只能有一个实例 必须自行创建实例 必须自行向整个系统提供这个实例 实现: 只提供私有的构造方法 含有一个该类的静态私有对象 提供一个静态的公有方法用于创建、获取静态私有对象 代码实现方案: 饿汉式 懒汉式 饿汉式 类加载时,静态实例对象完成了实例化操作;空间换时间。(对象创建过程中实例化) 饿汉式线程安全 新建文件SingletonOne.java /** * 饿汉式 */ public class SingletonOne { //1.创建类中的私有构造函数 private SingletonOne(){ } //2.创建该类型的私有静态实例 private static SingletonOne instance = new SingletonOne(); //3.创建公有静态方法返回静态实例对象 public static SingletonOne getInstance(){ return instance; } } 新建文件Test.java public class Test { public static void main(String[] args) { SingletonOne one = SingletonOne.getInstance(); SingletonOne two = SingletonOne.getInstance(); System.out.println(one); System.out.println(two); } } 输出结果可以看到是同一个类的地址。 懒汉式 类加载时并未实例化,第一次使用时才进行实例化;时间换空间。(静态公有方法中实例化) 懒汉式存在线程风险 懒汉式线程安全的解决方案:(此处大致介绍下,后边在线程篇会详细介绍) 同步锁 双重校验锁 静态内部类 枚举 新建文件:SingletonOne.java public class SingletonTwo { //1.创建私有构造方法 private SingletonTwo(){ } //2.创建静态的该类实例对象 private static SingletonTwo instance = null; //3.创建开放的静态方法提供实例对象 public static SingletonTwo getInstance(){ if(instance == null) instance = new SingletonTwo(); return instance; } } 新建文件Test.java public class Test { public static void main(String[] args) { SingletonTwo one = SingletonTwo.getInstance(); SingletonTwo two = SingletonTwo.getInstance(); System.out.println(one); System.out.println(two); } } 输出结果同上饿汉式代码 单列模式的特点以及应用场景 优点: 在内存中只有一个对象,节省内存 避免频繁的创建和销毁对象,提高性能 避免对共享资源的多重占用 缺点: 扩展比较困难 如果实例化后的对象长期不利用,系统将默认认为垃圾,进行回收,造成对象状态丢失 使用场景: 创建对象时占用资源过多,但同时又需要用到该类对象 对系统内资源要求统一读写,如读写配置信息 当多个实例存在可能引起程序逻辑错误,如号码生成器

优秀的个人博客,低调大师

Java入门之面向对象使用接口编程

假设: 三位互联网风云人物除了本身的职位外,给他们增加医生、警察、司机三个职务。现在他们要去学习一项Java开发的技术,对于老师来讲,三位都是学生,老师只关注学生这一个身份,其他的身份与老师无关。 image.png 使用接口的好处 通用性 隔离性 通用性:无论是医生、警察、司机,通通全部当做学生对待。 隔离性:无论是医生、警察、司机,特有的功能与我无关,我只关心学生相关的功能。 接口的格式与组成部分 接口基本定义格式: public interface 要定义的接口名称 { //...... } 接口当中可以包含的组成部分有: 1.抽象方法 2.常量 3.默认方法(Java8) 4.静态方法(Java8) 5.私有方法(Java9) 接口的抽象方法定义 抽象方法定义:public abstract 返回值类型 方法名称 (参数类型 参数名称); 注意: 1.接口中的抽象方法,修饰符如果要写,必须是:public abstract; 2.接口中的抽象方法,修饰符可以省略不写,默认就是 :public abstract; 3.抽象方法只有方法头,不能有方法体大括号; public interface Animal { //定义一个抽象方法 :吃东西 public abstract void eat(); //写了修饰符; //定义一个抽象方法 :睡觉; void sleep(); //不写修饰符; } image.png 使用接口 如果要想使用定义好的接口,必须有一个接口的"实现类", 定义实现类格式为: public class 实现的类名称 implements 接口名称 { 一定要覆盖重写所有抽象方法 } 什么是覆盖重写(Override)抽象方法? 1.将接口当中的抽象方法抄过来; 2.去掉abstract关键字; 3.写上大括号方法体; Cat就是Animal接口的实现类;Cat类实现了Animal接口。如下图: public class Cat implements Animal { public void eat(){ } public void sleep() { } } 接口与实现类的基本使用 如何使用接口与实现类? 创建: 接口名 引用名 = new 实现类名(); 调用: 引用名.抽象方法名(参数); public class Demo01 { public static void maim(String[] args){ //创建 Animal cat = new Cat(); //调用接口当中定义好的抽象方法; cat.eat(); cat.sleep(); } } 上图代码注意: 1.左边是接口类型,那么只能调用接口当中定义好的内容,不能调用右侧实现类当中特有的内容。(接口隔离)。 2.当调用接口当中的抽象方法时,真正进行运行的是右侧new的时候类的具体方法的内容。 3.调用的时候看左边,运行的时候看右边。 面向接口编程 准备三个.java文件,分别是Animal.java 、 Cat.java 、 Dog.java 我这里把三个文件写在一起 大家测试的时候还是常规分开三个文件。 Animal.java public interface Animal { public abstract void eat(); void sleep(); } Cat.java public class Cat implements Animal { public void eat(){ } public void sleep(){ } //这是一个Cat特有方法,接口中没有定义 public void catchMouse(){ } } Dog.java public class Dog implements Animal { public void eat(){ } public void sleep(){ } //这是一个Dog特有方法,接口中没有定义 public void watchHouse(){ } } 上边Cat和Dog各有一个自己独有的方法,Cat(catchMouse) Dog(watchHouse) 接口中只定义了两个方法 eat sleep. 如果不使用面向接口编程要这样写: public class Demo1 { public static void main(String[] args){ Cat cat = new Cat(); method(cat); Dog dog = new Dog(); method(dog); } public static void method(Cat cat){ cat.eat(); cat.sleep(); } public static void method(Dog dog){ dog.eat(); dog.sleep(); } } 如果使用面向接口编程: public class Demo2 { public static void main(String[] args){ Cat cat = new Cat(); method(cat); Dog dog = new Dog(); method(dog); } //使用接口作为参数类型 这样就不区分到底是猫还是狗 只能访问接口中定义的方法 隔离开了猫和狗特有的方法 public static void method(Animal animal){ animal.eat(); animal.sleep(); } } 很显然,后者使用接口作为参数类型 ,这样就不区分到底是猫还是狗 ,只能访问接口中定义的方法, 隔离开了猫和狗特有的方法。 使用接口作为左侧类型的好处,屏蔽掉了右侧的特性内容(catchMouse、watchHouse),达到隔离同一的目的。 面向接口编程: 如果使用的功能,接口已经可以满足,那么就不在乎具体的类是谁,只在乎接口即可。

优秀的个人博客,低调大师

Netty 源码阅读入门实战(一)-介绍

1 简介 以 Netty 为底层的框架 Netty 是什么 Netty 技术和方法的特点 设计 针对多种传输类型的统一接口 - 阻塞和非阻塞 简单但更强大的线程模型 真正的无连接的数据报套接字支持 链接逻辑支持复用 易用性 大量的 Javadoc 和 代码实例 除了在 JDK 1.6 + 额外的限制。(一些特征是只支持在Java 1.7 +。可选的功能可能有额外的限制。) 性能 比核心 Java API 更好的吞吐量,较低的延时 资源消耗更少,这个得益于共享池和重用 减少内存拷贝 健壮性 消除由于慢,快,或重载连接产生的 OutOfMemoryError 消除经常发现在 NIO 在高速网络中的应用中的不公平的读/写比 安全 完整的 SSL / TLS 和 StartTLS 的支持 运行在受限的环境例如 Applet 或 OSGI 社区 发布的更早和更频繁 社区驱动

优秀的个人博客,低调大师

【从入门到放弃-Hadoop】Hadoop基础学习

前言 目前人工智能和大数据火热,使用的场景也越来越广,日常开发中前端同学也逐渐接触了更多与大数据相关的开发需求。因此对大数据知识也有必要进行一些学习理解 基础概念 大数据的本质 一、数据的存储:分布式文件系统(分布式存储)二、数据的计算:分部署计算 基础知识 学习大数据需要具备Java知识基础及Linux知识基础 学习路线 (1)Java基础和Linux基础(2)Hadoop的学习:体系结构、原理、编程第一阶段:HDFS、MapReduce、HBase(NoSQL数据库)第二阶段:数据分析引擎 -> Hive、Pig 数据采集引擎 -> Sqoop、Flume 第三阶段:HUE:Web管理工具 ZooKeeper:实现Hadoop的HA

优秀的个人博客,低调大师

Spring Boot入门(13)自制音乐平台

经过笔者这几天的辛勤劳作(其实就是苦逼地码代码),一个新的网站已经上线啦!该网站是用Spring Boot工具写的,主要实现的功能如下: 根据歌曲名称和音乐平台搜索歌曲,并实现歌曲的在线播放; 歌曲的下载功能; 网页统计量功能; 开发历史介绍。 该网站的首页网址为: http://musicdownload.cfapps.io/index ,页面如下: 在输入框中输入“2002 Anne Marie”,音乐平台(platform)选择QQ,稍等片刻,就会跳转到歌曲播放页面,如下: 点击该页面中的“Download”按钮即可下载该歌曲,点击“RETURN”按钮即可返回到歌曲搜索页面。下载歌曲的页面如下: 点击搜索页面中的红色文字“Music Player”,即可查看该网站的开发历史,页面如下: 欢迎大家访问这个网站,也希望大家能够提出有用的建议(注:网站的功能还在不断完善中,具体的开发过程可参考: http://musicdownload.cfapps.io/dev)~~ 希望您能肯定我的工作,更重要的是,享受音乐带来的快乐哦~ 注意:本人现已开通两个微信公众号: 因为Python(微信号为:python_math)以及轻松学会Python爬虫(微信号为:easy_web_scrape), 欢迎大家关注哦~~

优秀的个人博客,低调大师

Spring Boot入门(11)实现文件下载功能

在这篇博客中,我们将展示如何在Spring Boot中实现文件的下载功能。 还是遵循笔者写博客的一贯风格,简单又不失详细,实用又能让你学会。 本次建立的Spring Boot项目的主要功能为文件下载,而且这也是唯一功能,当然,作为例子,要尽可能简单,所以,功能简化为只下载E盘music_eg目录下的某一个文件。 该Spring Boot项目的名称为file_download,其具体结构如下: build.gradle文件的代码如下: buildscript { ext { springBootVersion = '2.0.3.RELEASE' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'org.springframework.boot' apply plugin: 'io.spring.dependency-management' group = 'com.example' version = '0.0.1-SNAPSHOT' sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile('org.springframework.boot:spring-boot-starter-web') testCompile('org.springframework.boot:spring-boot-starter-test') } 我们只需要创建一个控制器(Controler)文件,即Controller目录下的File_Download.java,其完整目录如下: package com.example.file_download.Controller; import java.io.*; import java.net.URLEncoder; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class File_Download { //实现Spring Boot 的文件下载功能,映射网址为/download @RequestMapping("/download") public String downloadFile(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException { // 获取指定目录下的第一个文件 File scFileDir = new File("E://music_eg"); File TrxFiles[] = scFileDir.listFiles(); System.out.println(TrxFiles[0]); String fileName = TrxFiles[0].getName(); //下载的文件名 // 如果文件名不为空,则进行下载 if (fileName != null) { //设置文件路径 String realPath = "E://music_eg/"; File file = new File(realPath, fileName); // 如果文件名存在,则进行下载 if (file.exists()) { // 配置文件下载 response.setHeader("content-type", "application/octet-stream"); response.setContentType("application/octet-stream"); // 下载文件能正常显示中文 response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); // 实现文件下载 byte[] buffer = new byte[1024]; FileInputStream fis = null; BufferedInputStream bis = null; try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); OutputStream os = response.getOutputStream(); int i = bis.read(buffer); while (i != -1) { os.write(buffer, 0, i); i = bis.read(buffer); } System.out.println("Download the song successfully!"); } catch (Exception e) { System.out.println("Download the song failed!"); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } } return null; } } 这样我们就完成了Spring Boot的文件下载功能。什么?这样就搞定了?是的,就是这么简单,因为只实现了文件下载功能。具体的代码留给读者好好分析哦~~ 写完代码并不是我们的最终目的,我们还差最后一步,那就是测试!测试,真的相当重要啊~ 运行Spring Boot项目后,在浏览器中输入:http://localhost:8080/download , 你会发现什么?那就是你的浏览器已经开始下载E盘music_eg目录下的某一个文件啦(前提是E盘中存在music_eg目录,当然里面还得有文件,本例仅作为测试),如下图所示: 我们再去查看E盘music_eg目录,如下: So, 用Spring Boot实现文件下载功能搞定!欢迎大家交流哦~ 注意:本人现已开通两个微信公众号: 因为Python(微信号为:python_math)以及轻松学会Python爬虫(微信号为:easy_web_scrape), 欢迎大家关注哦~~

优秀的个人博客,低调大师

Java多线程 -- wait() 和 notify() 使用入门

在前面讲解synchronize的文章中,有提到wait和notify,大概描述了它的使用,这里我将根据官方api详细的教你如何使用。 所属对象 wait,notify,notifyAll 是定义在Object类的实例方法,用于控制线程状态。 文档分析 我们找到Object类,下载它的文档,翻译每个方法的注释。 总结如下: wait() 和 notify() 必须由对象持有者去调用,有三种方式: 1️⃣执行该对象的synchronized实例方法 2️⃣执行synchronized代码块 3️⃣执行该类的synchronized静态方法 当想要调用wait( )进行线程等待时,必须要取得这个锁对象的控制权(对象监视器),一般是放到synchronized(obj)代码中。 在while循环里用wait操作性能更好(比if判断) 调用obj.wait( )释放了obj的锁,否则其他线程也无法获得obj的锁,也就无法在synchronized(obj){ obj.notify() } 代码段内唤醒A。 notify( )方法只会通知等待队列中的第一个相关线程(不会通知优先级比较高的线程) notifyAll( )通知所有等待该竞争资源的线程(也不会按照线程的优先级来执行) 如果是synchronized声明的方法,wait()操作后会施放synchronized锁,相反notify()触发后会重拿起synchronized锁。 如果当前线程不是当前对象所持有,则会报异常IllegalMonitorStateException 实例 1. 通过调用对象的wait和notify实现 /** 调用对象的 wait 和 notify 实例 * Created by Fant.J. */ public class Demo { private boolean flag = false; public boolean isFlag() { return flag; } public void setFlag(boolean flag) { this.flag = flag; } public static void main(String[] args) { Demo demo = new Demo(); new Thread(new Runnable() { @Override public void run() { System.out.println("修改flag线程执行"); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } demo.setFlag(true); notify(); System.out.println("修改flag并释放锁成功"); } }).start(); new Thread(new Runnable() { @Override public void run() { while (demo.isFlag() != true){ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("flag为true时线程执行"); } }).start(); } } 修改flag线程执行 Exception in thread "Thread-1" java.lang.IllegalMonitorStateException at java.lang.Object.wait(Native Method) at java.lang.Object.wait(Object.java:502) at com.thread.waitNotify.Demo$2.run(Demo.java:41) at java.lang.Thread.run(Thread.java:748) Exception in thread "Thread-0" java.lang.IllegalMonitorStateException at java.lang.Object.notify(Native Method) at com.thread.waitNotify.Demo$1.run(Demo.java:31) at java.lang.Thread.run(Thread.java:748) 从运行结果可以看出,它报错IllegalMonitorStateException,我们上面有给出报该异常的原因,是因为没有没有获取到对象的监视器控制权,我们new了两个线程,一个调用了wait 一个调用了notify,jvm认为wait是一个线程下的wait,notify是另一个线程下的notify,事实上,我们想实现的是针对Demo对象的锁的wait和notify,所以,我们需要调用Demo对象的wait和notify方法。 修改后的代码: /** 调用对象的 wait 和 notify 实例 * Created by Fant.J. */ public class Demo { private boolean flag = false; public boolean isFlag() { return flag; } public void setFlag(boolean flag) { this.flag = flag; } public static void main(String[] args) { Demo demo = new Demo(); new Thread(new Runnable() { @Override public void run() { synchronized (demo) { System.out.println("修改flag线程执行"); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } demo.setFlag(true); demo.notify(); System.out.println("修改flag并释放锁成功"); } } }).start(); new Thread(new Runnable() { @Override public void run() { synchronized (demo) { while (demo.isFlag() != true) { try { demo.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("flag为true时线程执行"); } } }).start(); } } 修改flag线程执行 修改flag并释放锁成功 flag为true时线程执行 修改了两处,一处是加了synchronized代码块,一处是添加了wait和notify的调用对象。 2. 通过synchronized修饰方法来实现 package com.thread.waitNotify_1; /** 通过synchronized方法实现 wait notify * Created by Fant.J. */ public class Demo2 { private volatile boolean flag = false; public synchronized boolean getFlag() { System.out.println(Thread.currentThread().getName()+"开始执行..."); if (this.flag != true){ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName()+"执行结束..."); return flag; } public synchronized void setFlag(boolean flag) { this.flag = flag; notify(); } public static void main(String[] args) { Demo2 demo2 = new Demo2(); Runnable target1 = new Runnable() { @Override public void run() { demo2.getFlag(); } }; Runnable target2 = new Runnable() { @Override public void run() { demo2.setFlag(true); } }; new Thread(target1).start(); new Thread(target1).start(); new Thread(target1).start(); new Thread(target1).start(); } } Thread-0开始执行... Thread-1开始执行... Thread-2开始执行... Thread-3开始执行... 为什么四个线程都执行了呢?synchronized不是锁定线程了吗?我在上面8点中也有说明,wait()操作后,会暂时释放synchronized的同步锁,等notify()触发后,又会重拾起该锁,保证线程同步。 然后我们条用target2来释放一个线程: new Thread(target1).start(); new Thread(target1).start(); new Thread(target1).start(); new Thread(target1).start(); new Thread(target2).start(); Thread-0开始执行... Thread-1开始执行... Thread-2开始执行... Thread-3开始执行... Thread-0执行结束... 可以看到只释放了一个线程,并且是第一个线程,如果有优先级,他也是释放第一个线程。 如果把notify改成notifyAll。 Thread-0开始执行... Thread-2开始执行... Thread-1开始执行... Thread-3开始执行... Thread-3执行结束... Thread-1执行结束... Thread-2执行结束... Thread-0执行结束... 如何证明,每次notify后会拿到synchronized锁呢,我在执行notify后添加一些时间戳捕获帮助我们查看 public synchronized void setFlag(boolean flag) { this.flag = flag; // notify(); notifyAll(); System.out.println("测试notify触发后会不会等2s"+System.currentTimeMillis()); try { Thread.sleep(2000); System.out.println("测试notify触发后会不会等2s"+System.currentTimeMillis()); } catch (InterruptedException e) { e.printStackTrace(); } } Thread-0开始执行... Thread-1开始执行... Thread-2开始执行... Thread-3开始执行... 测试notify触发后会不会等2s1529817196847 测试notify触发后会不会等2s1529817198847 Thread-3执行结束... Thread-2执行结束... Thread-1执行结束... Thread-0执行结束... 可以看到的确是notify重拾了synchronized的同步锁,执行完该方法后才会释放锁。

优秀的个人博客,低调大师

React 入门实例 参考阮一峰博客

React 可以在浏览器运行,也可以在服务器运行。服务器的用法与浏览器差别不大。 1 hello world程序 **开发环境**visual studio code和谷歌浏览器(谷歌浏览器翻墙安装React Developer Tools)。 1.1 使用 React 开发新项目 前提安装npm工具,Node版本 >= 6。 在工作空间,执行以下命令: 1. npm install -g create-react-app 2. create-react-app my-app 3. cd my-app 4. npm start 1 2 3 4 然后打开http:// localhost:3000 /查看您的应用程序。 创建React App不处理后端逻辑或数据库; 它只是创建一个前端构建管道,所以你可以将它用于任何你想要的后端。 当您准备部署到生产环境时,运行 npm run build 1 将在build文件夹中创建应用程序的优化版本。将 src 子目录的 js 文件进行语法转换,转码后的文件全部放在 build 子目录。 结果 在当前文件夹内创建一个目录。my-app 在该目录内,它将生成初始项目结构并安装依赖项: my-app ├── README.md ├── node_modules ├── package.json ├── .gitignore ├── public │ └── favicon.ico │ └── index.html │ └── manifest.json └── src └── App.css └── App.js └── App.test.js └── index.css └── index.js └── logo.svg └── registerServiceWorker.js 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 没有配置或复杂的文件夹结构,只有构建应用程序所需的文件。 安装完成后,您可以打开项目文件夹,编辑目录、文件开发自己的项目(如下面: 修改APP.js)。 如果您更改了代码,该页面将自动重新加载。您将在控制台中看到构建错误和lint警告。 1) APP.js文件中编写Hello world程序 APP.js源码: import React, { Component } from 'react'; class App extends Component { render() { return ( <div className="App"> <h1 className="App-title">Hello World</h1> </div> ); } } export default App; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 注意:组件类只能包含一个顶层标签,否则也会报错 1.2 运行现有React项目/框架 一般readme文件中有说明,仔细阅读。运行现有源码包的基本步骤 1) 在项目的目录安装依赖 $ npm install 1 2) 将src子目录中的所有jsx文件转换为js文件。 $ npm run build 1 2 3) 启动http server $ node server.js 1 2 render() render()是 React 的最基本方法,用于将模板转为 HTML 语言,并插入指定的 DOM 节点。 例如:index.js中将App标签,插入 root节点 ReactDOM.render( <App />, document.getElementById('root') ); 1 2 3 4 3 JSX 语法 HTML 语言直接写在 JavaScript 语言之中,不加任何引号,这就是 JSX 的语法,它允许 HTML 与 JavaScript 的混写。demo2(项目index.js中修改import App from ‘./demo1’即可运行对应示例) import React, { Component } from 'react'; var names = ['Alice', 'Emily', 'Kate']; class App extends Component{ render(){ return( <div> { names.map(function (name, index) { return <div key={index}>Hello, {name}!</div> }) } </div> ) }; } export default App; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 JSX 的基本语法规则:遇到 HTML 标签(以 < 开头),就用 HTML 规则解析;遇到代码块(以 { 开头),就用 JavaScript 规则解析。 JSX 允许直接在模板插入 JavaScript 变量。如果这个变量是一个数组,则会展开这个数组的所有成员。JSX 会把它的所有成员,添加到模板。demo03 import React, { Component } from 'react'; var arr = [ <h1>Hello world!</h1>, <h2>React is awesome</h2>, ]; class App extends Component{ render(){ return( <div> <div>{arr}</div> </div> ) }; } export default App; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 4 组件 React 允许将代码封装成组件(component),然后像插入普通 HTML 标签一样,在网页中插入这个组件。class关键字用于生成一个组件类。demo04 import React, { Component } from 'react'; class App extends Component{ render(){ return( <div> <HelloMessage name="pengwei" />, </div> ) }; } class HelloMessage extends Component{ render() { return <h1>Hello {this.props.name}</h1>; } } export default App; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 上面代码中,变量 HelloMessage 就是一个组件类。模板插入 时,会自动生成 HelloMessage 的一个实例(下文的”组件”都指组件类的实例)。所有组件类都必须有自己的 render 方法,用于输出组件。 注意,组件类的第一个字母必须大写,否则会报错,比如HelloMessage不能写成helloMessage。另外,组件类只能包含一个顶层标签,否则也会报错。 组件的用法与原生的 HTML 标签完全一致,可以任意加入属性,比如 ,就是 HelloMessage 组件加入一个 name 属性,值为 John。组件的属性可以在组件类的 this.props 对象上获取,比如 name 属性就可以通过 this.props.name 读取。 注意,添加组件属性, class 属性需要写成 className ,for 属性需要写成 htmlFor ,这是因为 class 和 for 是 JavaScript 的保留字。 5 this.props.children this.props 对象的属性与组件的属性一一对应,但是有一个例外,就是 this.props.children 属性,它表示组件的所有子节点。demo05 import React, { Component } from 'react'; class App extends Component{ render(){ return( <div> <Parent> <span>hello</span> <span>world</span> </Parent> </div> ) }; } class Parent extends Component{ render(){ return( <ol> {React.Children.map(this.props.children,function(child) {return <li>{child}</li>;})} </ol> ) }; } export default App; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 注意, this.props.children 的值有三种可能:如果当前组件没有子节点,它就是 undefined ;如果有一个子节点,数据类型是 object ;如果有多个子节点,数据类型就是 array 。所以,处理 this.props.children 的时候要小心。 React 提供一个工具方法 React.Children 来处理 this.props.children 。我们可以用 React.Children.map 来遍历子节点,而不用担心 this.props.children 的数据类型 6 PropTypes和DefaultProps 组件的属性可以接受任意值,字符串、对象、函数等等都可以。有时,我们需要一种机制,验证别人使用组件时,提供的参数是否符合要求。 - PropTypes属性,就是用来验证组件实例的属性是否符合要求。 - DefaultProps 方法可以用来设置组件属性的默认值。demo06 import React, { Component } from 'react'; import PropTypes from 'prop-types'; class App extends Component{ render(){ return( <div> <DefaultMessage /> </div> ); }; } class DefaultMessage extends Component{ render() { return (<h1>Hello {this.props.name}</h1>); } } DefaultMessage.propTypes = { name: PropTypes.string }; DefaultMessage.defaultProps ={ name : 'World' } export default App; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 7 获取真实的DOM节点 组件并不是真实的 DOM 节点,而是存在于内存之中的一种数据结构,叫做虚拟 DOM (virtual DOM)。只有当它插入文档以后,才会变成真实的 DOM 。根据 React 的设计,所有的 DOM 变动,都先在虚拟 DOM 上发生,然后再将实际发生变动的部分,反映在真实 DOM上,这种算法叫做 DOM diff ,它可以极大提高网页的性能表现。 但是,有时需要从组件获取真实 DOM 的节点,这时就要用到 ref 属性demo07 import React, { Component } from 'react'; class App extends Component{ render(){ return( <div> <TrueDom /> </div> ); }; } class TrueDom extends Component{ constructor(props) { super(props); // This binding is necessary to make `this` work in the callback this.handleClick = this.handleClick.bind(this); } handleClick() { this.refs.myTextInput.focus(); }; render() { return( <div> <input type="text" ref="myTextInput" /> <input type="button" value="Focus the text input" onClick={this.handleClick} /> </div> ); }; } export default App; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 需要注意的是,由于 this.refs.[refName] 属性获取的是真实 DOM ,所以必须等到虚拟 DOM 插入文档以后,才能使用这个属性,否则会报错。上面代码中,通过为组件指定 Click 事件的回调函数,确保了只有等到真实 DOM 发生 Click 事件之后,才会读取 this.refs.[refName] 属性。 8 this.state react将组件看成是一个状态机,一开始有一个初始状态,然后用户互动,导致状态变化,从而触发重新渲染 UI。 由于 this.props 和 this.state 都用于描述组件的特性,可能会产生混淆。一个简单的区分方法是,this.props 表示那些一旦定义,就不再改变的特性,而 this.state 是会随着用户互动而产生变化的特性demo08 import React, { Component } from 'react'; class App extends Component{ render(){ return( <div> <LikeButton/> </div> ) }; } class LikeButton extends Component{ constructor(props) { super(props); this.state = {liked: false}; // This binding is necessary to make `this` work in the callback this.handleClick = this.handleClick.bind(this); } handleClick(event) { this.setState({liked: !this.state.liked}); }; render() { var text = this.state.liked ? 'like' : 'don\'t liked'; return ( <p onClick={this.handleClick}> You {text} this. Click to toggle. </p> ); }; } export default App; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 9 表单 用户在表单填入的内容,属于用户跟组件的互动,所以不能用 this.props 读取demo9 import React, { Component } from 'react'; class App extends Component{ render(){ return( <div> <Input/> </div> ) }; } class Input extends Component{ constructor(props) { super(props); this.state = {value: 'Hello!'}; // This binding is necessary to make `this` work in the callback this.handleChange = this.handleChange.bind(this); }; handleChange(event) { this.setState({value: event.target.value}); }; render() { var value = this.state.value; return ( <div> <input type="text" value={value} onChange={this.handleChange} /> <p>{value}</p> </div> ); }; } export default App; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 上面代码中,文本输入框的值,不能用 this.props.value 读取,而要定义一个 onChange 事件的回调函数,通过 event.target.value 读取用户输入的值。 10 组件的生命周期 组件的生命周期分成三个状态: -Mounting:已插入真实 DOM -Updating:正在被重新渲染 -Unmounting:已移出真实 DOM React 为每个状态都提供了两种处理函数,will 函数在进入状态之前调用,did 函数在进入状态之后调用,三种状态共计五种处理函数: -componentWillMount() -componentDidMount() -componentWillUpdate(object nextProps, object nextState) -componentDidUpdate(object prevProps, object prevState) -componentWillUnmount() 此外,React 还提供两种特殊状态的处理函数: -componentWillReceiveProps(object nextProps):已加载组件收到新的参数时调用 -shouldComponentUpdate(object nextProps, object nextState):组件判断是否重新渲染时调用demo10 import React, { Component } from 'react'; class App extends Component{ render(){ return( <div> <ComponentLifestyle name = "pengwei"/> </div> ) }; } class ComponentLifestyle extends Component{ constructor(props) { super(props); this.state = {opacity: 1.0}; }; componentWillMount() { this.timer = setInterval(function () { var opacity = this.state.opacity; var flag = this.state.flag; if(opacity >= 1||opacity<=0) {flag = !flag;} if (flag){ opacity -= 0.02; } else{ opacity += 0.02; } this.setState({ opacity: opacity, flag: flag }); }.bind(this), 100); }; render() { return ( <div style={{opacity: this.state.opacity}} flag = {true}> Hello {this.props.name} </div> ); }; } export default App; 原文发布时间:2018年03月25日 本文来源CSDN博客如需转载请紧急联系作者

优秀的个人博客,低调大师

python web开发之——Flask入门教程

一、安装python2.7(略) 1、Mac下使用python2.7 2、Windows下安装python2.7 从官网下载 双击python2.7,然后选择安装路径,一顿下一步就可以了。 设置环境变量,把python的安装路径添加到PATH变量中。 还需设置一个环境变量,将python的Script目录也添加到PATH中,一定要设置,不然后面就不能正常安装flask了。想学习可以加Python学习(q-u-n )-227-435-450 即可获取,内附:开发工具和安装包,以及视频资料系统学习路线图 二、安装python虚拟环境 1、为什么要安装虚拟环境,举个栗子: 假设你现在要开发一个项目A,使用的Flask的版本是0.12.2,过几年你又要开发一个项目B,但是这时候Flask的版本已经升级到1.0了,但其实Flask0.12.2版本和Flask1.0版本是不兼容的,怎么办呢?你不可能把Flask0.12.2版本卸掉重新安装吧,这样的项目A不是都不能用了? 我们安装python虚拟环境就是为了解决兼容性问题。虚拟环境会把项目A的0.12.2版本当做一个盒子,把项目Bde 1.0版本当做另一个盒子,每个盒子里安装包都不会有任何影响,这样两个版本就可以共存。 所以我们这里解释一下: 因为python的框架跟新迭代的太快,有时需要在电脑上存在一个框架多个版本,这时候虚拟环境可以解决这个问题。 2、安装虚拟环境 通过以下命令安装虚拟环境:pip install virtualenv 开辟新的虚拟环境:virtualenv [virtualenv-name] 激活虚拟环境: 【类linux】:source [虚拟环境的目录]/bin/activate 【windows】:直接进入到虚拟环境的目录,然后执行activate 退出虚拟环境:deactivate 详细步骤(已经会的可以略过): 1、打开cmd,输入 pipinstallvirtualenv 1 2、创建一个目录,将你的虚拟环境安装在这个目录,你可以任意选择。 比如我选择我电脑的F盘,目录名为Virtualenv 3、进入到我们刚创建的Virtualenv目录 4、然后我们用命令创建一个盒子(虚拟环境的名字假设叫FlaskHello) 安装好以后,进入FlaskHello的Script目录,激活虚拟环境 activate 1 看到途中箭头所指的Flask-env,说明虚拟环境就激活了。 退出虚拟环境使用命令 deactivate 1 三、安装Flask 1、进入到我们安装的虚拟环境中,执行 pipinstallflask 1 2、安装完以后,我们进入python,到入flask,然后查看flask的版本 注意:version左右是两个下划线。 四、第一个Flask程序 使用pycharm来创建一个工程。(项目名最好不要用中文) 这里Interpreter要注意,如果你的环境是在windows下,需要选虚拟环境下的python,这里选择Add local 比如我的 如果你是linux环境,那就在虚拟环境的bin下寻找。 2、创建完成后,会看到已经有模板了,我们设置编码方式为utf8 我们来执行一下这个模板,可以看到结果给我们一个地址,我们将其复制到浏览器访问,可以看到页面上输出了“Hello World” 程序解释:

优秀的个人博客,低调大师

.NET轻量级ORM框架Dapper入门精通

一、课程介绍 本次分享课程包含两个部分《.NET轻量级ORM框架Dapper修炼手册》和《.NET轻量级ORM框架Dapper葵花宝典》,阿笨将带领大家一起领略轻量级ORM框架Dapper的魅力。 本次分享课程适合人群范围: 一、《.NET轻量级ORM框架Dapper修炼手册》适合人群如下: 1、我是一个新手,主要工作面向的是MS SQL Server数据库,那么选择修炼手册一定没错。 2、对Dapper从没有过了解或者了解不全面的同学,想通过学习进一步提升对Dapper的认识。 3、迫切想提高下ADO.NET实战技术以及Transact-SQL的编写能力。 二、《.NET轻量级ORM框架Dapper葵花宝典》适合人群如下: 1、我是一个新手,主要工作面向的是MySQL数据库,那么选择葵花宝典一定没错。 2、在Dapper修炼手册的基础上新增一个Dapper扩展库Dapper.SimpleCRUD。 3、如何运用Dapper操作Mysql数据库以及Dapper如何支持多数据库。 4、学习Dapper在实际项目常用的几种开发架构模式。(简单三层架构模式、工厂模式、Repository架构模式) 5、本次新增Dapper如何以优雅的方式使用事务。(强烈推荐) 二、课程知识点 2.1、《.NET轻量级ORM框架Dapper修炼手册》覆盖知识点 1、C# Linq To Xml技术。 2、Transact-SQL修炼手册。比如如何使用临时表、创建用户自定义表(TABLE)、XML数据字段、ROW_NUMBER分页函数、存储过程修炼手册(动态执行SQL、异常处理机制、事务处理机制)、C#如何获取存储过程的OUTPUT、RETURN参数值。 3、SQL Sever FOR XML技术(XML PATH、XML RAW、XML AUTO简单用法介绍)。 4、Transact-SQL关键字OPENXML操作内存中的 XML 文档。 5、Faker.Net仿照测试数据框架运用。 6、VS单元测试NuitTest运用。 7、Dapper在异步编程(Asyn Task)中的运用。 8、原生Dapper简单的CRUD(增删改查) 修炼手册。(强烈推荐) 9、Dapper如何通过DynamicParameters动态拼接查询SQL修炼手册。(强烈推荐) 10、Dapper扩展库Dapper.SqlBuilder、UniqueNamespace.SqlBuilder修炼手册。(强烈推荐) 11、原生Dapper高级技巧修炼手册。(强烈推荐) 12、Dapper扩展库Dapper-Extensions修炼手册。(强烈推荐) 2.2、《.NET轻量级ORM框架Dapper葵花宝典》覆盖知识点 1、.NET程序员对MySQL数据库的基本认识和理解以及使用。 2、如何通过使用.NET轻量级ORM框架Dapper操作MySQL数据库。 3、Faker.Net仿照测试数据框架运用。 4、VS单元测试NuitTest运用。 5、Dapper在异步编程(Asyn Task)中的运用。 6、原生Dapper简单的CRUD(增删改查) 葵花宝典。(强烈推荐) 7、Dapper扩展库Dapper.SimpleCRUD的基本使用。(强烈推荐) 8、Dapper如何通过DynamicParameters动态拼接查询SQL葵花宝典。(强烈推荐) 9、Dapper扩展库Dapper.SqlBuilder、UniqueNamespace.SqlBuilder葵花宝典。(强烈推荐) 10、原生Dapper高级技巧葵花宝典。(强烈推荐) 11、Dapper扩展库Dapper-Extensions葵花宝典。(强烈推荐) 三、在线源码观看地址 作者:阿笨 官方QQ一群(已满):422315558 官方QQ二群(加入):574187616 个人讲师课堂主页:http://study.163.com/instructor/2544628.htm?share=2&shareId=2544628 个人微信公众号课程主页:http://dwz.cn/ABenNET

优秀的个人博客,低调大师

Spring Boot入门(7)使用MyBatis操作MySQL

介绍 MyBatis 是一款优秀的、开源的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。 这就表明,MyBatis是SQL映射框架(SQL mapping framework),和Hibernate工作原理并不相同,因为Hibernate是ORM 框架。 MyBatis社区已经为Spring Boot提供了starter依赖,因为我们可以在Spring Boot中愉快地使用MyBatis. 本次介绍将不使用MyBatis XML来执行数据库查询,而是使用基于注释的mappers(annotation-based mappers). 准备工作 因为本次演示的是如何在Spring Boot中使用MyBatis操作MySQL,进行数据库的增删改查。所以,我们需要对MySQL数据库做一些准备工作。具体说来,就说在MySQL的test数据库下新建表格person,其中的字段为id,name,age,city,id为自增长的主键。 use test create table person( id int primary key auto_increment, name varchar(20), age int, city varchar(20) ); 接着在 http://start.spring.io/ 中创建Spring Boot项目,加入Web, MyBatis, MySQL起始依赖,如下图: 项目结构 整个项目的结构如下图: 画红线的框内的文件是我们需要新增或修改的文件。 先是实体类Person.java,其代码如下: package com.hello.MyBatisDemo.domain; public class Person{ private Integer id; private String name; private Integer age; private String city; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } } 接着是基于注释的mappers文件PersonMapper.java,其代码如下: package com.hello.MyBatisDemo.DAO; import com.hello.MyBatisDemo.domain.Person; import org.apache.ibatis.annotations.*; import java.util.List; @Mapper public interface PersonMapper { /** * 添加操作,返回新增元素的 ID * @param person */ @Insert("insert into person(id,name,age,city) values(#{id},#{name},#{age},#{city})") @Options(useGeneratedKeys = true, keyColumn = "id", keyProperty = "id") void insert(Person person); /** * 更新操作 * @param person * @return 受影响的行数 */ @Update("update person set name=#{name},age=#{age},city=#{city} where id=#{id}") Integer update(Person person); /** * 删除操作 * @param id * @return 受影响的行数 */ @Delete("delete from person where id=#{id}") Integer delete(@Param("id") Integer id); /** * 查询所有 * @return */ @Select("select id,name,age,city from person") List<Person> selectAll(); /** * 根据主键查询单个 * @param id * @return */ @Select("select id,name,age,city from person where id=#{id}") Person selectById(@Param("id") Integer id); } 下一步是控制文件PersonController.java,其代码如下: package com.hello.MyBatisDemo.Controller; import com.hello.MyBatisDemo.DAO.PersonMapper; import com.hello.MyBatisDemo.domain.Person; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController public class PersonController { @Autowired private PersonMapper personMapper; @RequestMapping("/insert") public String insert(@RequestParam String name, @RequestParam String city, @RequestParam Integer age) { Person person = new Person(); person.setName(name); person.setAge(age); person.setCity(city); personMapper.insert(person); return "第"+person.getId()+"条记录插入成功!"; } @RequestMapping("/update") public String update(@RequestParam Integer id, @RequestParam String name, @RequestParam String city, @RequestParam Integer age) { Person person = new Person(); person.setId(id); person.setName(name); person.setAge(age); person.setCity(city); return personMapper.update(person)+"条记录更新成功!"; } @RequestMapping("/delete") public String delete(@RequestParam Integer id) { return personMapper.delete(id)+"条记录删除成功!"; } @RequestMapping("/selectById") public Person selectById(@RequestParam Integer id) { return personMapper.selectById(id); } @RequestMapping("/selectAll") public List<Person> selectAll() { return personMapper.selectAll(); } } 最后一步是整个项目的配置文件application.properies,主要是MySQL数据库的连接设置,其代码如下: spring.datasource.url=jdbc:mysql://localhost:33061/test?useUnicode=true&characterEncoding=UTF-8 spring.datasource.username=root spring.datasource.password=147369 spring.datasource.driver-class-name=com.mysql.jdbc.Driver server.port=8100 整个项目的结构及代码介绍完毕。 运行及测试 启动Spring Boot项目,在浏览器中输入: http://localhost:8100/insert?name=bob&age=14&city=shanghai 即可插入一条新的记录。如此类似地插入以下三条记录: 在浏览器中输入: http://localhost:8100/update?id=2&name=tian&age=27&city=shanghai 即可更新id=2的记录 在浏览器中输入: http://localhost:8100/delete?id=3 即可删除id=3的记录。 在浏览器中输入: http://localhost:8100/selectById?id=2 即可查询id=2的记录。 在浏览器中输入: http://localhost:8100/selectAll 即可查询所有的记录。 本次分享到此结束,接下来还会继续分享更多的关于Spring Boot的内容,欢迎大家交流~~

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

用户登录
用户注册
修改密码
忘记密码