2017年2月15日 星期三

ng-hide、ng-show、ng-disabled、ng-readonly、ng-selected、ng-checked (angularJS 六)

※ng-hide、ng-show、ng-disabled、ng-readonly 

※寫死的值

<html>
    <script type="text/javascript" src="angular.js"></script>
    
    <body ng-app>
        <p ng-hide="true">看不見</p>
        <p ng-hide="false">看見</p>
    
        <p ng-show="true">看見</p>
        <p ng-show="false">看不見</p>
    
        <p>
            <button ng-disabled="true">按不下去</button>
            <button ng-disabled="false">按的下去</button>
        </p>
    
        <p>
            <input ng-readonly="true" value="不可改" />
            <input ng-readonly="false" value="可改" />
        </p>
    </body>
</html>v

※注意 readonly 屬性在HTML裡有三種方式:readonly="true"、readonly、readonly="readonly"
但用ng-readonly就只有true|false;disabled也是一樣

※初始值

<html>
    <script type="text/javascript" src="angular.js"></script>
    
    <body ng-app ng-init="xxx=true; ooo=10">
        <p ng-hide="xxx">看不見</p>
    
        <p ng-show="xxx">看見</p>
    
        <p>
            <button ng-disabled="xxx">按不下去</button>
        </p>
    
        <p>
            <input ng-readonly="ooo > 1" value="不可改" />
        </p>
    </body>
</html>

※變數也可以取名為readonly,但並不表示 ng-readonly="readonly" 成立,只是剛好 readonly 是個true|false

※動態給值

<html>
    <script type="text/javascript" src="angular.js"></script>
    
    <body ng-app ng-init="xxx=true">
        <p ng-hide="xxx">看不見</p>
        <p ng-show="xxx">看見</p>
    
        <input type="checkbox" ng-model="xxx">按我
        <p>{{ xxx }}</p>
    </body>
</html>

※



※ng-selected、ng-checked

<html>
    <script type="text/javascript" src="angular.js"></script>
    
    <body ng-app>
        <select>
            <option value="a">A</option>
            <option value="b" ng-selected="true">B</option>
            <option value="c">C</option>
        </select>
        <br />
        <select multiple>
            <option value="a">A</option>
            <option value="b" ng-selected="true">B</option>
            <option value="c" ng-selected="true">C</option>
        </select>
        <br />
        <input type="checkbox" name="xxx" />c1
        <input type="checkbox" name="xxx" ng-checked="true" />c2
        <input type="checkbox" name="xxx" ng-checked="true" />c3
        <br />
        <input type="radio" name="ooo" />r1
        <input type="radio" name="ooo" ng-checked="true" />r2
        <input type="radio" name="ooo" />r3
    </body>
</html>

※觀念和上面一模一樣

2017年2月14日 星期二

ng-options、$even、$odd、$index (angularJS 五)

※ng-options 和 ng-repeat 不同

<html>
    <script type="text/javascript" src="angular.min.js"></script>
    
    <body ng-app='xxx' ng-controller='ccc'>
        <select ng-model="sel">
            <option ng-repeat="l in lists" value="{{l.x}}">{{l.o}}</option>
        </select>
        <p>選到的value是{{sel}}</p>
        
        <select ng-model="sel2" ng-options="l.o for l in lists"></select>
        <p>選了{{sel2.o}},value是{{sel2.x}}</p>
    </body>
</html>
    
<script>
    var app = angular.module('xxx', []);
    app.controller('ccc', ($scope) => {
        $scope.lists = [
            {
                o: 'a', x: 1
            }, {
                o: 'b', x: 2
            }, {
                o: 'c', x: 3
            }
        ];
    });
</script>

※ng-repeat by 字串;ng-options by 物件



※ng-options 可設多個物件

<html>
    <script type="text/javascript" src="angular.min.js"></script>
    
    <body ng-app='xxx' ng-controller='ccc'>
        <select ng-model="sel" ng-options=" p2.name for (p1, p2) in lists "></select>
        <p>選了{{sel.name}},價錢是{{sel.price}},製造年是{{sel.date}}年</p>
    </body>
</html>
    
<script>
    var app = angular.module('xxx', []);
    app.controller('ccc', ($scope) => {
        $scope.lists = {
            chessProduct1: {name:'象棋', price: 30, date: '1999'},
            chessProduct2: {name:'五子棋', price: 25, date: '2000'},
            chessProduct3: {name:'圍棋', price: 40, date: '2010'}
        };
    });
</script>

※注意chessProduct1~3,這三個變數如果一樣會覆蓋,使畫面上只剩最後一個



※$even、$odd、$index

<html>
    <script type="text/javascript" src="angular.min.js"></script>
    
    <body ng-app='xxx' ng-controller='ccc'>
        <table>
            <tr ng-repeat="l in lists |orderBy:'name'">
                <td ng-if="$odd" style="background-color:lightgreen">{{ $index + 1 }}</td>
                <td ng-if="$even">{{ l.name }}</td>
                <td>{{ l.price }}</td>
            </tr>
        </table>
    </body>
</html>
    
<script>
    var app = angular.module('xxx', []);
    app.controller('ccc', ($scope) => {
        $scope.lists = [
            {name: 'papaya', price: 30}, 
            {name: 'apple', price: 25}, 
            {name: 'guava', price: 80},
            {name: 'durian', price: 60},
            {name: 'banana', price: 40}
        ];
    });
</script>

※這三個都是從0開始的
$index:從0開始的數字
$odd:奇數時會顯示
$even:偶數時會顯示

2017年2月13日 星期一

Service (angularJS 四)

官網API連結

※$location、$http、$timeout、$interval

<html>
    <script type="text/javascript" src="angular.js"></script>
    
    <body ng-app='xxx'>
        <div ng-controller='ooo'>
            <p>{{myUrl}}</p>
            <p>{{myHttp}}</p>
            <p>{{myURL}}</p>
            <p>{{myTimeout}}</p>
            <p>{{myInterval}}</p>
        </div>
    </body>
</html>
    
<script>
    var app = angular.module('xxx', []);
    app.controller('ooo', function($scope, $location, $http, $timeout, $interval) {
        $scope.myUrl = $location.absUrl();
    
        $http.get("http://localhost:8080/TestServletXXX/xxx.jsp").then(function (response) {
            $scope.myHttp = response.data;
            $scope.myURL = response.config.url;
        });
    
        $timeout(function () {
            $scope.myTimeout = "我佇這,你看啥貨?";
        }, 2000);
    
        $interval(function () {
            $scope.myInterval = new Date().toLocaleTimeString();
        }, 1000);
    });
</script>

※$location:類似window.location

※$http:連到已啟動的伺服器,但Chrome會有同源策略的問題,可參考這篇

※$timeout:js的window.timeout,過幾毫秒做什麼事

※$interval:js的window.interval,每過幾毫秒做什麼事

※以上可以加debugger看還有什麼可以「.」的


※service

<html>
    <script type="text/javascript" src="angular.js"></script>
    
    <body ng-app='xxx'>
        <div ng-controller='ooo'>
            <p>{{self}}</p>
        </div>
    </body>
</html>
    
<script>
    var app = angular.module('xxx', []);
    app.controller('ooo', function($scope, zzz) {
        $scope.self = zzz.yyyFun(100);
    });
    
    app.service('zzz', function() {
        this.yyyFun = function (x) {
            return x + x;
        }
    });
</script>

※自定 service 的功能,也就是定義controller裡可以放的service,此例是zzz



※filter 抓 service 的方法

<html>
    <script type="text/javascript" src="angular.js"></script>
    
    <body ng-app='xxx'>
        <ul ng-controller='ooo'>
            <li ng-repeat="a in intArr">{{a | myFilter}}</li>
        </ul>
    </body>
</html>
    
<script>
    var app = angular.module('xxx', []);
    app.controller('ooo', ($scope) => {
        $scope.intArr = [73, 108, 49];
    });
    
    app.filter('myFilter',['zzz', (f) => { // 這裡的zzz對應到service,使用裡面的方法
        return (x) => {
            return f.yyy(x);
        };
    }]);
    
    app.service('zzz', function() {
        this.yyy = (x) => {
            return String.fromCharCode(x);
        }
    });
</script>

※zzz 對應好即可



※Servlet 回傳 JSON

@WebServlet(urlPatterns = { "/xxx" })
public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String json = "{\"A\":\"1\",\"B\":2,\"C\":3.3}";
        System.out.println("json=" + json);
    
    //    JSONObject json = new JSONObject();
    //    json.put("A", "1");
    //    json.put("B", 2);
    //    json.put("C", 3.3);
    //    System.out.println("json=" + json.toString());
    
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
    
        PrintWriter out = resp.getWriter();
        out.write(json);
        out.flush();
        out.close();
    }
}

※一定要用「"」,單引號我試的結果,前端會跑到fail,所以最好是用註解這一類的工具,才不會看到目睭拖窗

※JSON回傳「"xxx":["A":1,"B":2,"C":3]」,試的結果也是會跑到fail,很奇怪

※不使用setContentType也是可以的


※前端

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" isELIgnored="false"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
        <script type="text/javascript" src="angular.min.js"></script>
        <script>
            var app = angular.module('xxx', []);
            app.controller('ooo', function($scope, $http) {
                $http({
                    method : 'GET',
                    url : 'xxx'
                }).then(function successCallback(resp) {
                    $scope.a = resp.data.A;
                    $scope.b = resp.data.B;
                    $scope.c = resp.data.C;
                }, function errorCallback(resp) {
                    alert('fail');
                });
            });
        </script>
    </head>
    
    <body ng-app='xxx'>
        <div ng-controller='ooo'>
            <p>{{a}}</p>
            <p>{{b}}</p>
            <p>{{c}}</p>
        </div>
    </body>
</html>

※一載入頁面就呼叫了

※resp.data 是固定的,而後面如果是JSON還可以繼續「.」

2017年2月12日 星期日

單例模式

一個class只有一個實體


※餓漢式單例

public class Singleton {
    private static final Singleton SINGLETON = new Singleton();
    
    private Singleton() {}
    
    public static Singleton getInstance() {
        return SINGLETON;
    }
}

※類別載入就創建物件,執行效率高,但浪費記憶體



※懶漢式單例

public class Singleton {
    private static Singleton singleton = null;
    
    private Singleton() {}
    
    public static synchronized Singleton getInstance() {
        if (singleton == null) {
            singleton = new Singleton();
        }
        return singleton;
    }
}

※第一次請求實體才會創建物件,但必須要用synchronized

※如果不用 synchronized 有可能會有多個實體,因為Parallel程序可能會進入,如下:
public class Singleton {
    private static Singleton singleton = null;
    
    private Singleton() {}
    
    public static Singleton getInstance() {
        if (singleton == null) {
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            singleton = new Singleton();
        }
        return singleton;
    }
}
    
    
    
public class MyThread implements Runnable {
    @Override
    public void run() {
        System.out.println(Singleton.getInstance());
    }
    
    public static void main(String... ss) {
        /*Runnable my = () -> {
            System.out.println(Singleton.getInstance());
        };*/
    
        MyThread my = new MyThread();
        for(int i=1; i<=5; i++){
            new Thread(my).start();
        }
    }
}

※停一秒鐘,然後 Parallel,就有可能會有2個實體

※註解是 Java8 的 lambda 寫法,此時可以不用 implements Runnable 和實作

※1.設定 msconfig
2.設定 taskmgr,針對java、javaw、Eclipse 使用一顆 CPU,還是一樣的結果,不知道為什麼
理論上單核是不會有併行的


※登記式單例

public class Singleton {
    private Singleton() {}
    
    public static Singleton getInstance() {
        return InnerSingleton.SINGLETON;
    }
    
    private static class InnerSingleton {
        private static final Singleton SINGLETON = new Singleton();
    }
}

※綜合餓漢和懶漢的最佳單例

2017年2月11日 星期六

DOM4j

※xml.xml

<?xml version="1.0" encoding="UTF-8"?>
<root>top1
    top2
    <first fa="f1" fb="1f">
        first-1
        <second1 sa="s1">aaa</second1>
        <second2>bbb</second2>
        <second3>ccc</second3>
    </first>
    top3
    <first fa="f2" fb="2f">
        first-2
        <second1 sa="s2">ddd</second1>
        <second2>eee</second2>
        <second3>fff</second3>
    </first>
    top4
    <first fa="f3" fb="3f">
        first-3
        <second1 sa="s3">ggg</second1>
        <second2>hhh</second2>
        <second3>iii</second3>
    </first>
</root>

※



※maven

<dependency>
    <groupId>dom4j</groupId>
    <artifactId>dom4j</artifactId>
    <version>1.6.1</version>
</dependency>


※讀檔

import java.util.Iterator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
    
public class DOM4jTest {
    public static void main(String[] args) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document doc = reader.read("src/main/java/xml.xml");
        Element root = doc.getRootElement();
    
        System.out.println("方法一");
        List<Element> first = root.elements();
        for (Element e : first) {
            System.out.println(e.getText().trim());
            for (Object o : e.attributes()) {
                System.out.println(((Attribute) o).getValue());
            }
    
            System.out.println("子元素");
            List<Element> second = e.elements();
            for (Element s : second) {
                System.out.println(s.getText().trim());
            }
            System.out.println(System.getProperty("line.separator"));
        }
    
        System.out.println("方法二");
        Iterator<Element> it2 = root.elementIterator();
        while (it2.hasNext()) {
            Element firstTwo = (Element) it2.next();
            // ...
        }
    
        System.out.println("方法三");
        for (Iterator<Element> it3 = root.elementIterator(); it3.hasNext();) {
            Element firstThree = it3.next();
            // ...
        }
    }
}

※方法二和三,迴圈裡的內容和方法一一樣



※使用XPath


※要使用 XPath 必需要有 jaxen 的 jar,否則執行selectSingleNode方法時會報錯
<dependency>
    <groupId>jaxen</groupId>
    <artifactId>jaxen</artifactId>
    <version>1.1.6</version>
</dependency>



※
import java.io.IOException;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.dom4j.tree.DefaultAttribute;
    
public class DOM4jTest {
    public static void main(String[] args) throws IOException, DocumentException {
        SAXReader reader = new SAXReader();
        Document doc = reader.read("src/main/java/xml.xml");
        Node root = doc.selectSingleNode("/root");
        List<Element> second1 = root.selectNodes("first/second1");
    
        for (Element e : second1) {
            System.out.println(e.getName());
            System.out.println(e.getText());
            System.out.println(e.attributeValue("sa"));
            System.out.println("---------------");
        }
    
        System.out.println("===============");
        List<Element> first = root.selectNodes("first");
        for (Element e : first) {
            System.out.println(e.getName());
            System.out.println(e.getText().trim());
    
            for (Object o : e.attributes()) {
                DefaultAttribute ele = (DefaultAttribute) o;
                System.out.println(ele.getStringValue());
            }
            System.out.println("===============");
        }
    }
}

※selectSingleNode 和 selectNodes 可以寫XPath



※寫檔

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
    
public class DOM4jTest {
    public static void main(String[] args) throws IOException {
        Document doc = DocumentHelper.createDocument();
        Element root = doc.addElement("root");
        Element first = root.addElement("first");
        Element second1 = first.addElement("second1");
        Element second2 = first.addElement("second2");
        Element second3 = first.addElement("second3");
    
        root.setText("top1" + System.getProperty("line.separator") + "\ttop2");
        first.setText("first-1");
        second1.setText("aaa");
        second2.setText("bbb");
        second3.setText("ccc");
    
        first.addAttribute("fa", "f1");
        first.addAttribute("fb", "1f");
        second1.addAttribute("sa", "s1");
    
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
    
        File file = new File("D:/" + File.separator + "xml.xml");
        OutputStream fout = new FileOutputStream(file, true);
        XMLWriter out = new XMLWriter(fout, format);
        out.write(doc);
        out.close();
        System.out.println("XML已生成");
    }
}

※此例只是寫其中一個first而已

※變數format是讓產生出的XML有排版


JDOM

※xml.xml

<?xml version="1.0" encoding="UTF-8"?>
<root>top1
    top2
    <first fa="f1" fb="1f">
        first-1
        <second1 sa="s1">aaa</second1>
        <second2>bbb</second2>
        <second3>ccc</second3>
    </first>
    top3
    <first fa="f2" fb="2f">
        first-2
        <second1 sa="s2">ddd</second1>
        <second2>eee</second2>
        <second3>fff</second3>
    </first>
    top4
    <first fa="f3" fb="3f">
        first-3
        <second1 sa="s3">ggg</second1>
        <second2>hhh</second2>
        <second3>iii</second3>
    </first>
</root>

※


※maven

<dependency>
    <groupId>jdom</groupId>
    <artifactId>jdom</artifactId>
    <version>1.1</version>
</dependency>

※


※讀寫

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
    
public class JDOMTest {
    public static void main(String[] args) throws JDOMException, IOException {
        write();
        read();
    }
    
    private static void read() throws IOException, JDOMException {
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build("src/main/java/xml.xml");
    
        Element root = doc.getRootElement();
        List<Element> list = root.getChildren();
        System.out.println(list.size());
        for (Element e : list) {
            System.out.println("===== 取元素和屬性 =====");
            System.out.println(e.getText().trim());
            List<Attribute> attrs = e.getAttributes();
            for (Attribute a : attrs) {
                System.out.println(a.getValue());
            }
            System.out.println("===== 取子元素和屬性 =====");
            System.out.println(e.getChildText("second1"));
            System.out.println(e.getChild("second1").getAttribute("sa").getValue());
            System.out.println(System.getProperty("line.separator"));
        }
    }
    
    private static void write() throws IOException {
        Element root = new Element("root");
        Element first = new Element("first");
        Element second1 = new Element("second1");
        Element second2 = new Element("second2");
        Element second3 = new Element("second3");
    
        root.setText("top1" + System.getProperty("line.separator") + "top2");
        first.setText("first-1");
        second1.setText("aaa");
        second2.setText("bbb");
        second3.setText("ccc");
    
        first.setAttribute("fa", "f1");
        first.setAttribute("fb", "1f");
        second1.setAttribute(new Attribute("sa", "s1"));
    
        root.addContent(first);
        first.addContent(second1);
        first.addContent(second2);
        first.addContent(second3);
    
        Document doc = new Document(root);
    
        File file = new File("D:/" + File.separator + "xml.xml");
        OutputStream fout = new FileOutputStream(file, true);
    
        XMLOutputter out = new XMLOutputter();
        out.setFormat(out.getFormat().setEncoding("UTF-8"));
        out.output(doc, fout);
        System.out.println("XML已生成");
    }
}

※


SAXParserFactory

※xml.xml

<?xml version="1.0" encoding="UTF-8"?>
<root>top1
    top2
    <first fa="f1" fb="1f">
        first-1
        <second1 sa="s1">aaa</second1>
        <second2>bbb</second2>
        <second3>ccc</second3>
    </first>
    top3
    <first fa="f2" fb="2f">
        first-2
        <second1 sa="s2">ddd</second1>
        <second2>eee</second2>
        <second3>fff</second3>
    </first>
    top4
    <first fa="f3" fb="3f">
        first-3
        <second1 sa="s3">ggg</second1>
        <second2>hhh</second2>
        <second3>iii</second3>
    </first>
</root>

※




SAXParserFactory只能讀取XML,不能修改、新增

※SAXHandler.java

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
    
public class SAXHandler extends DefaultHandler {
    @Override
    public void startDocument() throws SAXException {
        System.out.println("<?xml version='1.0' encoding='UTF-8'?>");
    }
    
    @Override
    public void endDocument() throws SAXException {
        System.out.println("讀取結束");
    }
    
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        System.out.print("<");
        System.out.print(qName);
        if (attributes != null) {
            for (int i = 0; i < attributes.getLength(); i++) {
                System.out.print(" " + attributes.getQName(i) + "='" + attributes.getValue(i) + "'");
            }
        }
        System.out.print(">");
    }
    
    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        System.out.print("</");
        System.out.print(qName);
        System.out.print(">");
    }
    
    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        System.out.println(new String(ch, start, length));
    }
}

※startDocument方法只是為了方便閱讀,有可能「'」會被認為不是XML,應該改成「"」



※SAXTest.java 

import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
    
public class SAXTest {
    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        parser.parse("src/main/java/xml.xml", new SAXHandler());
    }
}

※