JQuery Ajax Maven [A]

JQuery Ajax Maven [A]

  • JQuery + JQuery Ajax
    • JQuery + JQueryAjax 1: JQuery
    • JQuery + Ajax 2: JQuery Ajax
  • Maven


JQuery + JQuery Ajax

JQuery Ajax Maven [A]_第1张图片

JQuery + JQueryAjax 1: JQuery

  • jQuery is using jQuery($()) wrap DOM into dynamic (factory) nodes
  • jQuery cannot user DOM object methods, DOM methods cannot use jQuery
    JQuery
  • jQuery var is an array
//conventional JS
$(document).ready(function(){//jquery code})
window.onload=function(){//js code} //appear once
//jquery
$(function(){//jQuery code}); //appear multiple time
  • difference between jQ: $(document).ready(function(){}); and js: window.οnlοad=function(){}: js only load once, jQ can appear multiple times
  • use dom var to display jQuery objects
  • method1: var dom1=jQueryObject[ index]
  • method2: var dom2=jQueryObject.get();
    JQuery Ajax Maven [A]_第2张图片
DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <script  src="../js/jquery-1.12.4.min.js">script>
    <script>
        $(document).ready(function(){
            alert('not jquery');
        });
        //jquery
        $(function(){
            alert('jquery...');
            var $btn=$('button');
            alert($btn.length);
            //use dom var to display jQuery objects
            //method1
            var b2= $btn[0];
            alert(b2.firstChild.nodeValue);
            //method2
            var b3=$btn.get(1);
            alert(b3.firstChild.nodeValue)
        })
    script>
head>
<body>
<button>push1button>
<button>push2button>
<button>push3button>
<button>push4button>
<button>push5button>
<button>push6button>
body>
html>
  • Selector:
    1. Basic: Attribute Selector: Element selector: select array
DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <script  src="../js/jquery-1.12.4.min.js">script>
    <script>
         $(function(){
//             //attribute selector
//             $('p').css('background-color','red');
//             $('p').css('border','2px solid blue');             $('p').css('background-color','red');
             $('p').css('background-color','red').css('border','2px solid blue');
         });
    script>
    <style>
        h1{
            background-color: #0008ff;
        }
    style>
head>
<body>
<p>Paragraph1p>
<p>Paragraph2p>
<p>Paragraph3p>
<p>Paragraph4p>
<h1>H1h1>
body>
html>
    1. Basic Selector: Class Selector : (“.class”) one selector refer to one class, one selector can refer to multiple elements
DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <script src="../js/jquery-1.12.4.min.js">script>
    <script>
        $(function(){
            $('.odd1').css('border','1px green dotted');
        });
    script>
    <style>
        .odd2{
            border: 2px blue dotted;
        }
    style>
head>
<body>
<div class="odd1">DIV1div>
<div class="odd2">DIV2div>
<div class="odd1">DIV3div>
<div class="odd2">DIV4div>
<div class="odd1">DIV5div>
<div class="odd2">DIV6div>
<div class="odd7">DIV7div>
body>
html>
  • (“*”) select all
    1. Basic Selector: id Selector (“#id”)
DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title> Titletitle>
    <script  src="../js/jquery-1.12.4.min.js">script>
    <script>
        $(function(){
            var str=$('#id2')[0];
            alert(str.innerHTML);
            $('*').css('border','2px dashed blue');
            alert($('span,p').text());
        });
    script>
head>
<body>
<span>span1span>
<span id="id2">span2span>
<span>span3span>
<span>span4span>
<span>span5span>
<p>paragraphp>
<div>div...div>
body>
html>
    1. Hierarchy Selector: (parent child) all child affected
DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <script src="../js/jquery-1.12.4.min.js">script>
    <script>
        $(function () {
            $('form p').css('border','1px red  dotted');
            $('form').css('border','2px blue  dotted');
        })
    script>
head>
<body>
    <form>
        <p>Paragraph1p>
        <input type="text" value="BOB">
        <p>Paragraph2p>
        <div>
            <p>paragraph3p>
            <input type="text" value="SAM">
            <p>paragraph4p>
        div>
    form>
    <p>paragraph5p>

body>
html>
    1. Hierarchy Selector: (parent > child) one tier below parent affected
DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <script src="../js/jquery-1.12.4.min.js">script>
    <script>
        $(function () {
            $('form>p').css('border','1px red  dotted');
            $('form').css('border','2px blue  dotted');
        })
    script>
head>
<body>
    <form>
        <p>Paragraph1p>
        <input type="text" value="BOB">
        <p>Paragraph2p>
        <div>
            <p>paragraph3p>
            <input type="text" value="SAM">
            <p>paragraph4p>
        div>
    form>
    <p>paragraph5p>
body>
html>
    1. Hierarchy Selector: (prev + next) prev item and next one item affected, has to match type
DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <script src="../js/jquery-1.12.4.min.js">script>
    <script>
        $(function () {
            $('form>p').css('border','1px red  dotted');
            $('form').css('border','2px blue  dotted');
            $('.input+p').css('border','1px green dotted')
        })
    script>
head>
<body>
    <form>
        <p>Paragraph1p>
        <input class="input" type="text" value="BOB">
        <p>Paragraph2p>
        <p>Paragraph3p>
        <div>
            <p>paragraph4p>
            <input class="input" type="text" value="SAM">
            <span>span1span>
            <p>paragraph5p>
            <p>paragraph6p>
        div>
    form>
    <p>paragraph7p>
body>
html>
    1. Hierarchy Selector: (prev ~ next) prev item and next all items affected, has to match hierarchy
DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <script src="../js/jquery-1.12.4.min.js">script>
    <script>
        $(function () {
            $('form>p').css('border','1px red  dotted');
            $('form').css('border','2px blue  dotted');
            $('.input ~ p').css('border','1px green dotted')
        })
    script>
head>
<body>
    <form>
        <p>Paragraph1p>
        <input class="input" type="text" value="BOB">
        <p>Paragraph2p>
        <p>Paragraph3p>
        <div>
            <p>paragraph4p>
            <input class="input" type="text" value="SAM">
            <span>span1span>
            <p>paragraph5p>
            <p>paragraph6p>
        div>
    form>
    <p>paragraph7p>
body>
html>
    1. Hierarchy Selector: $(‘type’).siblings(‘type’).script(‘content’) …affect all siblings
DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <script src="../js/jquery-1.12.4.min.js">script>
    <script>
        $(function () {
            $('form>p').css('border','1px red  dotted');
            $('form').css('border','2px blue  dotted');
            $('.input').siblings('p').css('border','2px green  dotted');
        })
    script>
head>
<body>
    <form>
        <p>Paragraph1p>
        <input class="input" type="text" value="BOB">
        <p>Paragraph2p>
        <p>Paragraph3p>
        <div>
            <p>paragraph4p>
            <input class="input2" type="text" value="SAM">
            <span>span1span>
            <p>paragraph5p>
            <p>paragraph6p>
        div>
    form>
    <p>paragraph7p>
body>
html>
    1. Hierarchy Selector: ( ′ t y p e ′ ) . n e x t A l l ( ′ t y p e ′ ) . s c r i p t ( ′ c o n t e n t ′ ) , ('type').nextAll('type').script('content') , (type).nextAll(type).script(content),(‘type’).prevAll(‘type’).script(‘content’) …affect all of same hierarchy
DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <script src="../js/jquery-1.12.4.min.js">script>
    <script>
        $(function () {
            $('#input').nextAll('p').css('backgroundColor','#e3e3e3');
            $('#input').prevAll('p').css('backgroundColor','#ffda00');
        })
    script>
head>
<body>
    <form>
        <p>Paragraph1p>
        <input class="input" type="text" value="BOB">
        <p>Paragraph2p>
        <p>Paragraph3p>
        <div>
            <p>paragraph4p>
            <span>span0span>
            <p>paragraph4p>
            <input id="input" type="text" value="SAM">
            <span>span1span>
            <p>paragraph5p>
            <span>span2span>
            <p>paragraph6p>
        div>
    form>
    <p>paragraph7p>
body>
html>
    1. Filter Selelctor:
DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <script src="../js/jquery-1.12.4.min.js">script>
    <script>
    $(function(){
        $('li:first').css('border','1px dotted blue');
        $('li:even').css('border','1px dotted red');
        $('li:last').css('border','1px dotted green');
        $('li:eq(3)').css('border','1px dotted blue');
        $('li:not(.c1)').css('border','1px dotted yellow');
        $("li:contains('2')").css('background-color','blue');
        $('.b1').click(function(){
            alert($('input:hidden').val());
        })
        $('.b2').click(function(){
            alert($('form input:visible').val());
            $('input:visible:eq(0)').css('border','2px dotted red');
            $('form input:visible:eq(0)').css('border','2px dotted blue');
            $('input:visible').each(function(){
               alert($(this).val());
            });
        });
//        for(var i=0; i<3;i++){
//            alert($('input:visible:eq(i)').val());
//        }
    });
    script>
head>
<body>
<button class="b1">PUSH1button>
<button class="b2">PUSH2button>
<input  type="text" value="visible0">
<form action="#">
    <input type="hidden" value="hidden!!!!">
    <input  type="text" value="visible1">
    <input  type="text" value="visible2">
form>
<input  type="text" value="visible3">
<ul>
    <li class="c1">li1li>
    <li class="c1">li2li>
    <li class="c1">li3li>
    <li class="c1">li4li>
    <li class="c1">li5li>
    <li >li6li>
    <li class="c1">li7li>
    <li class="c1">li8li>
ul>
<p>p1p>
body>
html>
    1. Filter Selelctor: nth-child(even/odd/2/3n/3n+1)
DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <script src="../js/jquery-1.12.4.min.js">script>
    <script>
    $(function(){
        $('button').click(function(){
            $('ul :first-child').css('border','1px red dotted');
            $('ul :last-child').css('border','1px blue dotted');
            $('ul :nth-child(3n)').css('border','1px green dotted');
        });
    });
    script>
head>
<body>
<p style="...">p1p>
<button >PUSH1button>
<button >PUSH2button>
<button >PUSH3button>
<ul>
    <li>Johnli>
    <li>Karlli>
    <li>Brandonli>
    <li>Bradli>
    <li>Joli>
ul>
<ul>
    <li>Glenli>
    <li>Taneli>
    <li>Ralphli>
    <li>Ronli>
    <li>Tomli>
ul>
body>
html>
    1. Filter Selelctor: nth-child(even/odd/2/3n/3n+1)
DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <script src="../js/jquery-1.12.4.min.js">script>
    <script>
        $(function () {
            $('button').click(function () {
                $('tr:not(:first-child) td:nth-child(4n)').css('background-color','#c1c1c1')
            });
        });
    script>
head>
<body>
<p style="...">p1p>
<button>PUSH1button>
<button>PUSH2button>
<button>PUSH3button>
<table border="1" cellpadding="5">
    <tr>
        <td>idtd>
        <td>usernametd>
        <td>salarytd>
        <td>deletetd>
    tr>
    <tr>
        <td>idtd>
        <td>username1td>
        <td>salarytd>
        <td><a href="#">deletea>td>
    tr>
    <tr>
        <td>idtd>
        <td>username2td>
        <td>salarytd>
        <td><a href="#">deletea>td>
    tr>
table>
body>
html>
    1. Filter Selector: form(input, text, password, radio, checkbox, submit, image, reset, button, file, hidden)
DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <script src="../js/jquery-1.12.4.min.js">script>
    <script>
        $(function () {
            $('button').click(function () {
                $('form input').each(function(){
                    alert($(this).val());
                });
                $('form :text').each(function(){
                    alert($(this).val());
                });
                $('form :text:disabled').each(function(){
                    alert($(this).val());
                });
                alert($(' select :selected').html());
                $('tr:odd').css('background-color', '#c1c1c1');
            });
        });
    script>
head>
<body>
<p style="...">p1p>
<button>PUSH1button>
<button>PUSH2button>
<button>PUSH3button>
<form action="#">
    <input type="text" disabled="disabled" value="111">
    <input type="text" value="222">
    <input type="text" value="333">
    <select>
        <option>1option>
        <option selected="selected">2option>
        <option>3option>
    select>
form>
<input type="text" value="444">

<table border="1" cellpadding="5">
    <tr>
        <td>idtd>
        <td>usernametd>
        <td>salarytd>
        <td>deletetd>
    tr>
    <tr>
        <td>idtd>
        <td>username1td>
        <td>salarytd>
        <td><a href="#">deletea>td>
    tr>
    <tr>
        <td>idtd>
        <td>username2td>
        <td>salarytd>
        <td><a href="#">deletea>td>
    tr>
table>
body>
html>
  • jQuery DOM : 1. $().val() :value
  • $().attr(‘attributeName’) : attribute
  • change attribute: $(‘name’).attr(‘value’,‘name’);
DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <script src="../js/jquery-1.12.4.min.js">script>
    <script>
        $(function(){
        $('button').click(function(){
            alert($(':text').attr('name'));
            $(':text').attr('value','Jerry');
        });
        });
    script>
head>
<body>
    <input type="text" value="Tom" name="username">
<br>
<button>pushbutton>
body>
html>
  • jQuery DOM :append: $ ( ‘ul’).append($content);, appendTo: $content.appendTo(‘ul’);
  • jQuery DOM :prepend: $ ( ‘ul’).prepend($content);, appendTo: $content.prependTo(‘ul’);
DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <script src="../js/jquery-1.12.4.min.js">script>
    <script>
        $(function () {
            $('button').click(function () {
                var $content = $('
  • new
  • '
    ); $('ul').append($content); $content.appendTo('ul'); $('ul').prepend($content); $content.prependTo('ul'); // $('ul li:last-child').text('13'); }); });
    script> head> <body> <button>push to appendbutton> <ul> <li>l1li> <li>l2li> <li>l3li> ul> <ul> <li>l1li> <li>l2li> <li>l3li> ul> body> html>
    • jQuery DOM : after, before, insertAfter: $content.insertAfter(‘ul’);insertBefore: $content.insertAfter(‘ul’);;
    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Titletitle>
        <script src="../js/jquery-1.12.4.min.js">script>
        <script>
            $(function(){
                $('button').click(function(){
                    var $str=$('name1age1sex1');
                    $str.insertAfter('#flag');
                });
            });
        script>
    head>
    <body>
    <table border="1" cellpadding="10">
        <tr>
            <td>usernametd>
            <td>agetd>
            <td>sextd>
        tr>
        <tr id="flag">
            <td>usernametd>
            <td>agetd>
            <td>sextd>
        tr>
    table>
    <form action="#">
        username: <input type="text" name="username"><br>
        age: <input type="text" name="age"><br>
        sex: <input type="text" name="gender"><br>
    form>
    <button>add attributebutton>
    body>
    html>
    
    • jQuery DOM: remove, empty
    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Titletitle>
        <script src="../js/jquery-1.12.4.min.js">script>
        <script>
            $(function(){
                $('button').click(function(){
                    $(":text").remove();
                    $("p").empty();
                });
            });
        script>
        <style>
            p{background-color: #ffda00;
            width: 100px;
            height: 20px;}
        style>
    head>
    <body>
     <input type="text" value="Tom" name="username">
    <p >p1p>
    <br>
    <button>pushbutton>
    body>
    html>
    
    • jQuery Dom: width(), height();
    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Titletitle>
        <script src="../js/jquery-1.12.4.min.js">script>
        <script>
            $(function () {
                $('div').click(function () {
                    alert($(this).css('background-color', '#c1c1c1').height('30px').height());
                    alert($(this).width());
                    alert($(this).text());
                    alert($(this).html());
                    alert($(this).html('changed!'));
                });
            });
        script>
    head>
    <body>
    <button>buttonbutton>
    <div>
        <span>span1span>
        <span>span2span>
    div>
    <div>div2div>
    <div>div3div>
    <div>div4div>
    <div>div5div>
    <div>div6div>
    body>
    html>
    
    • jQuery Dom: add/remove class, toggle
    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Titletitle>
        <script src="../js/jquery-1.12.4.min.js">script>
        <script>
            $(function () {
                $('button:eq(0)').click(function () {
                    $('p:eq(1)').addClass('p1');
                });
                $('button:eq(1)').click(function () {
                    $('p:eq(1)').removeClass('p1');
                });
                $('button:eq(2)').click(function(){
                   $('p:eq(1)').toggleClass('p1');
                });
            });
        script>
        <style>
            .p1{background-color: #c1c1c1;}
        style>
    head>
    <body>
    <button>push add classbutton>
    <button>push remove classbutton>
    <button>push toggle classbutton>
    <p class="p1"> p1p>
    <p> p2p>
    <p class="p1"> p3p>
    <p> p4p>
    body>
    html>
    
    • DOM: bind / unbind
    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Titletitle>
        <script src="../js/jquery-1.12.4.min.js">script>
        <script>
            $(function(){
                $('button:eq(0)').click(function(){
                    var flag=$('p').is(':hidden');
                    if(flag){
                        $('p').show();
                    }else{
                        $('p').hide();
                    }
                });
                $('button:eq(1)').bind('click',function(){
                    var flag=$('p').is(':hidden');
                    if(flag){
                        $('p').show();
                    }else{
                        $('p').hide();
                    }
                });
            });
        script>
    head>
    <body>
    <button>hide/showbutton>
    <button>bind hide/showbutton>
    <p>p1 testp>
    body>
    html>
    
    • DOM: hover
    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Titletitle>
        <script src="../js/jquery-1.12.4.min.js">script>
        <script>
            $(function () {
                $('div').hover(
                    function () {
                        $('p').addClass('p1');
                    },
                    function () {
                        $('p').removeClass('p1');
                    });
                $('td').hover(
                    function () {
                        $(this).addClass('p1');
                    },
                    function () {
                        $(this).removeClass('p1');
                    });
            });
        script>
    
        <style>
            .p1 {
                background-color: #c1c1c1
            }
        style>
    head>
    <body>
    <div>hoverdiv>
    <hr>
    <p>p1...p>
    <table border="1">
        <tr>
            <td>td1td>
            <td>td2td>
        tr>
        <tr>
            <td>td1td>
            <td>td2td>
        tr>
    table>
    body>
    html>
    
    • dom: bubble
    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Titletitle>
        <script src="../js/jquery-1.12.4.min.js">script>
        <script>
            $(function(){
                $('body').click(function(){
                    alert($(this).html());
                    return false;
                });
                $('div').click(function(){
                    alert($(this).html());
                });
                $('span').click(function(){
                    alert($(this).html());
                });
            });
        script>
    head>
    <body>
    <div><span>SPAN1span>div>
    <hr>
    <div><span>SPAN2span>div>
    body>
    html>
    
    • Dom: event
    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Titletitle>
        <script src="../js/jquery-1.12.4.min.js">script>
    <script>
        $(function(){
            $('body').height('300px').mousemove(
                function(event){
                   $('div').text("x:"+event.pageX+ "y:"+event.pageY);
                });
        });
    script>
    head>
    <body>
    <div>div>
    body>
    html>
    

    JQuery + Ajax 2: JQuery Ajax

    • Ajax: Asynchronous JavaScript & XML

    • When a page loads again, only new information is added , does not have to renew all: save time

    • get post review
      JQuery Ajax Maven [A]_第3张图片

    • JQuery encapsulation of Ajax ($.ajax()) (load(), $.get(), $.post(), $.getScript(), $.getJSON()

    • 3 ways to send info: XML, HTML, JSON

    • domObject.load( url, data)

    • url: String: server location; data: Object sent key/value to server; callback: function sent msg after request done, successful or not

    • $.get(url, args, function(result){},“JSON”);

    • $.post(url, args, function(result){},“JSON”);

    • $.getJSON(url, args, function(result){});
      在这里插入图片描述

    • html.txt

    <a href="http://www.bing.com">binga>
    <a href="http://www.baidu.com">baidua>
    
    • jquery_ajax.html
    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Titletitle>
        <script src="../js/jquery-1.12.4.min.js">script>
        <script>
    $(function(){
        $('button').click(function(){
            var url="txt/html.txt";
            var data={"time":new Date()};
            $('div').load(url,data);
        });
    });
        script>
    head>
    <body>
    <button>get HTMLbutton>
    <div>div1div>
    body>
    html>
    
    • $.get(url, args,function(result){ //return}, “JSON”)
    • $.getJSON(url, args,function(result){ //return})
    • $.post(url, args,function(result){ //return}, “JSON”)
    • url: server address
    • args: key/value sent to server
    • function: other attributes
    • result: server returned result
    • “JSON”: if selected, returned object encapsulated as JSON objects
    • ajax.json
    {
      "address":{
        "province":"AAA",
        "city": "BBB",
        "area": "CCC"
      },
      "name":"BOB",
      "age":"34"
    }
    
    • jquery_ajax2.html
    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Titletitle>
        <script src="../js/jquery-1.12.4.min.js">script>
        <script>
            $(function () {
                $('button').click(function () {
                    var url = "txt/ajax.json";
                    var data = {"time": new Date()};
    //                $('div').load(url,data);
                    $.get(url, data, function(result) {
                        $('#div1').text(result.name);
                        $('#div2').text(result.age);
                       $('#div3').text(result.address.city);
                    },"JSON");
                });
            })
        script>
    head>
    <body>
    <button>get JSON databutton>
    <div id="div1">div1div>
    <div id="div2">div1div>
    <div id="div3">div1div>
    body>
    html>
    
    • use .txt
    • ajax.txt
    {
      "address":{
        "province":"AAA",
        "city": "BBB",
        "area": "CCC"
      },
      "name":"BOB",
      "age":"34"
    }
    
    • option 1
    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Titletitle>
        <script src="../js/jquery-1.12.4.min.js">script>
        <script>
            $(function () {
                $('button').click(function () {
                    var url = "txt/ajax.txt";
                    var data = {"time": new Date()};
    //                $('div').load(url,data);
                    $.get(url, data, function(data) {
                        var result = eval("("+data+")");
                        $('#div1').text(result.name);
                        $('#div2').text(result.age);
                       $('#div3').text(result.address.city);
                    });
                });
            })
        script>
    head>
    <body>
    <button>get JSON databutton>
    <div id="div1">div1div>
    <div id="div2">div1div>
    <div id="div3">div1div>
    body>
    html>
    
    • option2
    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Titletitle>
        <script src="../js/jquery-1.12.4.min.js">script>
        <script>
            $(function () {
                $('button').click(function () {
                    var url = "txt/ajax.txt";
                    var data = {"time": new Date()};
    //                $('div').load(url,data);
                    $.getJSON(url, data, function(result) {
                        $('#div1').text(result.name);
                        $('#div2').text(result.age);
                       $('#div3').text(result.address.city);
                    });
                });
            })
        script>
    head>
    <body>
    <button>get JSON databutton>
    <div id="div1">div1div>
    <div id="div2">div1div>
    <div id="div3">div1div>
    body>
    html>
    
    • XMLHttpRequest methods: abort(); getAllResponseHeaders(); getResponseHeader(“header”); setRequestHeader(“header”, “value”)
    • XMLHttpRequest methods: open(“method”, “url”);
    • XMLHttpRequest methods: send(content);
    • XMLHttpRequest attributes: onreadystatechange; readyState; responseText; responseXML; status(404); statusText
    • Parse TEXT
    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Titletitle>
        <script src="../js/jquery-1.12.4.min.js">script>
        <script>
            $(function () {
                //parse
                $('button').click(function () {
                    //1. create XMLHTTPRequest obj
                    var xmlHttp = new XMLHttpRequest();
                    //2. use open to get connection to server
                    var method = 'get';
                    var url = 'txt/ajax.txt';
                    xmlHttp.open(method, url);
                    //3. use send method to send request to server
                    xmlHttp.send();
                    //4. use onreadystatechange to get state
                    xmlHttp.onreadystatechange = function () {
                        //when readystate=4 status=200
                        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                                var str = xmlHttp.responseText;
                                $('div').text(str);
    //                        document.getElementsByTagName('p')[0].innerHTML =
    //                            xmlHttp.responseText;
                        }
                    }
                });
            })
        script>
    head>
    <body>
    <button>clickbutton>
    <p>p>
    <div>div>
    body>
    html>
    
    • parse XML eval()
    • Ajax.xml
    
    <student>
        <name id="xName">BOBname>
        <age id="xAge">35age>
        <address id="xAddr">SHaddress>
    student>
    
    • ajax2.html
    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Titletitle>
        <script src="../js/jquery-1.12.4.min.js">script>
        <script>
            $(function () {
                //parse
                $('button').click(function () {
                    //1. create XMLHTTPRequest obj
                    var xmlHttp = new XMLHttpRequest();
                    //2. use open to get connection to server
                    var method = 'get';
                    var url = 'txt/ajax.xml';
                    xmlHttp.open(method, url);
                    //3. use send method to send request to server
                    xmlHttp.send();
                    //4. use onreadystatechange to get state
                    xmlHttp.onreadystatechange = function () {
                        //when readystate=4 status=200
                        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                            var xml=xmlHttp.responseXML;
                            var name=xml.getElementById('xName');
                            var age=xml.getElementById('xAge');
                            var addr=xml.getElementById('xAddr');
                            $("#div1").text(name.innerHTML);
                            $("#div2").text(age.innerHTML);
                            $("#div3").text(addr.innerHTML);
                        }
                    }
                });
            })
        script>
    head>
    <body>
    <button>clickbutton>
    <p>p>
    <div id="div1">div>
    <div id="div2">div>
    <div id="div3">div>
    body>
    html>
    
    • MOVIE EXAMPLE
    • jackson-annotation download
    • jackson-core download
    • jackson-databind download
    • junit-4.9.jardownload
      JQuery Ajax Maven [A]_第4张图片
    • MySQL
    CREATE TABLE `movies` (
      `id` int NOT NULL,
      `title` varchar(255) DEFAULT NULL,
      `director` varchar(255) DEFAULT NULL,
      `actor` varchar(255) DEFAULT NULL,
      `time` datetime DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    

    JQuery Ajax Maven [A]_第5张图片
    JQuery Ajax Maven [A]_第6张图片

    • MovieDao.java
    package com.abc.ajax.dao;
    import java.sql.Connection;
    import java.util.List;
    import com.abc.ajax.po.Movie;
    import com.abc.ajax.util.JDBCUtil;
    public class MovieDao {
    public List<Movie> queryList(String movieName){
    	Connection connection=JDBCUtil.getConnection();
    	String sql="select * from movies where title like ?";
    	List<Movie> list=null;
    	try {
    		list = JDBCUtil.queryT(connection,sql, "%"+movieName+"%");
    		System.out.println(sql+"%"+movieName+"%");
    		System.out.println(list);
    		return list;
    	} catch (Exception e) {
    		// TODO Auto-generated catch block
    		e.printStackTrace();
    	}finally{
    		JDBCUtil.close(connection);
    	}
    	return null;
    }
    }
    
    • Movie.java
    package com.abc.ajax.po;
    import java.util.Date;
    public class Movie {
    	private int id;
    	private String title;
    	private String director;
    	private String actor;
    	private Date time;
    	public Movie(int id, String title, String director, String actor, Date time) {
    		super();
    		this.id = id;
    		this.title = title;
    		this.director = director;
    		this.actor = actor;
    		this.time = time;
    	}
    
    	public int getId() {
    		return id;
    	}
    
    	public void setId(int id) {
    		this.id = id;
    	}
    
    	public String getTitle() {
    		return title;
    	}
    
    	public void setTitle(String title) {
    		this.title = title;
    	}
    
    	public String getDirector() {
    		return director;
    	}
    
    	public void setDirector(String director) {
    		this.director = director;
    	}
    
    	public String getActor() {
    		return actor;
    	}
    
    	public void setActor(String actor) {
    		this.actor = actor;
    	}
    
    	public Date getTime() {
    		return time;
    	}
    
    	public void setTime(Date time) {
    		this.time = time;
    	}
    
    	@Override
    	public String toString() {
    		return "Movie [id=" + id + ", title=" + title + ", director=" + director + ", actor=" + actor + ", time=" + time
    				+ "]";
    	}
    }
    
    • ListServlet.java
    package com.abc.ajax.servlet;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import com.abc.ajax.dao.MovieDao;
    import com.abc.ajax.po.Movie;
    import com.fasterxml.jackson.databind.ObjectMapper;
    public class ListServlet extends HttpServlet {
    	@Override
    	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    		System.out.println("ListServlet.service");
    		String value = req.getParameter("movieName");
    		System.out.println(value);
    //		List list = new ArrayList();
    //		list.add(new Movie(1, "American Con", "null", "null", new Date()));
    //		list.add(new Movie(2, "American Con", "null", "null", new Date()));
    		MovieDao dao=new MovieDao();
    		List<Movie> list=dao.queryList(value);
    		if(list!=null){
    			ObjectMapper mapper = new ObjectMapper();
    			String valueAsStr = mapper.writeValueAsString(list);
    			resp.setCharacterEncoding("utf-8");
    			resp.getWriter().write(valueAsStr);
    		}
    	}
    }
    
    • JDBCUtil.java
    package com.abc.ajax.util;
    import java.io.IOException;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    import java.util.Properties;
    import com.abc.ajax.po.Movie;
    import com.mchange.v2.c3p0.ComboPooledDataSource;
    public class JDBCUtil {
    	private static ComboPooledDataSource ds = null;
    	// get properties from c3p0
    	static {
    		ds = new ComboPooledDataSource("jdbc_c3p0");
    	}
    	// get connection
    	public static Connection getConnection() {
    		try {
    			System.out.println("connection: "+ds.getConnection());
    			return ds.getConnection();
    		} catch (SQLException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		return null;
    	}
    	// close connection
    	public static void close(Connection conn) {
    		try {
    			if (conn != null) {
    				conn.close();
    			}
    		} catch (SQLException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    	// perform sql
    	public static List<Movie> queryT(Connection conn, String sql, String RegEx) {
    		PreparedStatement ps = null;
    		ResultSet rs = null;
    		List<Movie> list = new ArrayList<Movie>();
    		try {
    			ps = conn.prepareStatement(sql);
    			ps.setString(1, RegEx);
    			rs = ps.executeQuery();
    			while (rs.next()) {
    				// 1, "American Con", "null", "null", new Date())
    				int id = rs.getInt("id");
    				String title = rs.getString("title");
    				String director = rs.getString("director");
    				String actor= rs.getString("actor");
    				Date time= rs.getDate("time");
    				System.out.println(id+" "+director+" "+actor+" "+time);
    				list.add(new Movie(id, title, director, actor,time));				
    			}
    			rs.close();
    			ps.close();
    			return list;
    		} catch (SQLException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		return null;
    
    	}
    }
    
    • c3p0-config.xml
    
    <c3p0-config>
    	
    	<default-config>
    		<property name="initialPoolSize">10property>
    		<property name="maxPoolSize">100property>
    		<property name="minPoolSize">10property>
    		<property name="driverClass">com.mysql.cj.jdbc.Driverproperty>
    		<property name="jdbcUrl">jdbc:mysql://localhost:3306/movies?serverTimezone=UTCproperty>
    		<property name="user">rootproperty>
    		<property name="password">12345property>
    	default-config>
    	
    	<named-config name="jdbc-c3p0">
    		<property name="initialPoolSize">10property>
    		<property name="maxPoolSize">100property>
    		<property name="minPoolSize">10property>
    		<property name="driverClass">com.mysql.cj.jdbc.Driverproperty>
    		<property name="jdbcUrl">jdbc:mysql://localhost:3306/movies?serverTimezone=UTCproperty>
    		<property name="user">rootproperty>
    		<property name="password">12345property>
    	named-config>
    c3p0-config>
    
    • web.xml
    
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    	id="WebApp_ID" version="3.1">
    	<display-name>webappjq2display-name>
    	<servlet>
    		<servlet-name>ListServletservlet-name>
    		<servlet-class>com.abc.ajax.servlet.ListServletservlet-class>
    	servlet>
    	<servlet-mapping>
    		<servlet-name>ListServletservlet-name>
    		<url-pattern>/list.actionurl-pattern>
    	servlet-mapping>
    web-app>
    
    • search.html
    DOCTYPE html>
    <html>
    <head>
    <title>search.htmltitle>
    <meta name="keywords" content="keyword1,keyword2,keyword3">
    <meta name="description" content="this is my page">
    <meta name="content-type" content="text/html; charset=UTF-8">
    <script type="text/javascript" src="js/jquery-1.12.4.min.js">script>
    <script type="text/javascript">
    	$(function() {
    		$('#movieInput').focus(function() {
    			//getJSON get data
    			var url = "list.action";
    			var args = {
    				"movieName" : $('#movieInput').val()
    			};
    			$.getJSON(url, args, function(result) {
    				//delete previous option data
    				$('option').remove();
    				//result get List result
    				for (var i = 0; i < result.length; i++) {
    					//1. create 
    					var $option = $(');
    					//2. set $option value
    					$option.attr("value", result[i].title);
    					//3. add to datalist
    					$('datalist').append($option);
    				}
    			});
    		});
    	})
    script>
    head>
    <body>
    	<input list="movieSearch" id="movieInput" name="movieName">
    	<datalist id="movieSearch">
    	datalist>
    body>
    html>
    
    • AREA EXAMPLE: UNSUCCESSFUL: jstl core did not work therefore couldn’t use lists to properly display using JQ
    • only lists tables from sql…? did not find why
    • SQL
    CREATE TABLE `city` (
      `id` int NOT NULL,
      `city_name` varchar(255) DEFAULT NULL,
      `state_id` int DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    

    JQuery Ajax Maven [A]_第7张图片

    CREATE TABLE `country` (
      `ID` int NOT NULL,
      `Country_Name` varchar(255) DEFAULT NULL,
      PRIMARY KEY (`ID`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    

    JQuery Ajax Maven [A]_第8张图片

    CREATE TABLE `state` (
      `id` int NOT NULL,
      `state_name` varchar(255) DEFAULT NULL,
      `country_id` int DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    

    JQuery Ajax Maven [A]_第9张图片

    • java: webappjq3
      JQuery Ajax Maven [A]_第10张图片

    • ListDao.java

    package com.abc.ajax.po;
    public class city {
    private int id;
    private String cityName;
    private int stateId;
    public city(int id, String cityName, int stateId) {
    	super();
    	this.id = id;
    	this.cityName = cityName;
    	this.stateId = stateId;
    }
    public int getId() {
    	return id;
    }
    public void setId(int id) {
    	this.id = id;
    }
    public String getCityName() {
    	return cityName;
    }
    public void setCityName(String cityName) {
    	this.cityName = cityName;
    }
    public int getStateId() {
    	return stateId;
    }
    public void setStateId(int stateId) {
    	this.stateId = stateId;
    }
    @Override
    public String toString() {
    	return "city [id=" + id + ", cityName=" + cityName + ", stateId=" + stateId + "]";
    }
    }
    
    • city.java
    package com.abc.ajax.po;
    public class city {
    private int id;
    private String cityName;
    private int stateId;
    public city(int id, String cityName, int stateId) {
    	super();
    	this.id = id;
    	this.cityName = cityName;
    	this.stateId = stateId;
    }
    public int getId() {
    	return id;
    }
    public void setId(int id) {
    	this.id = id;
    }
    public String getCityName() {
    	return cityName;
    }
    public void setCityName(String cityName) {
    	this.cityName = cityName;
    }
    public int getStateId() {
    	return stateId;
    }
    public void setStateId(int stateId) {
    	this.stateId = stateId;
    }
    @Override
    public String toString() {
    	return "city [id=" + id + ", cityName=" + cityName + ", stateId=" + stateId + "]";
    }
    }
    
    • country.java
    package com.abc.ajax.po;
    public class country {
    private int id;
    private String countryName;
    public country(int id, String countryName) {
    	super();
    	this.id = id;
    	this.countryName = countryName;
    }
    public int getId() {
    	return id;
    }
    public void setId(int id) {
    	this.id = id;
    }
    public String getCountryName() {
    	return countryName;
    }
    public void setCountryName(String countryName) {
    	this.countryName = countryName;
    }
    @Override
    public String toString() {
    	return "country [id=" + id + ", countryName=" + countryName + "]";
    }
    
    }
    
    • state.java
    package com.abc.ajax.po;
    public class state {
    	private int id;
    	private String stateName;
    	private int countryId;
    	public state(int id, String stateName, int countryId) {
    		super();
    		this.countryId=countryId;
    		this.id = id;
    		this.stateName = stateName;
    	}
    	public int getId() {
    		return id;
    	}
    	public void setId(int id) {
    		this.id = id;
    	}
    	public String getStateName() {
    		return stateName;
    	}
    	public void setStateName(String stateName) {
    		this.stateName = stateName;
    	}
    	public int getCountryId() {
    		return countryId;
    	}
    	public void setCountryId(int countryId) {
    		this.countryId = countryId;
    	}
    	@Override
    	public String toString() {
    		return "state [id=" + id + ", stateName=" + stateName + ", countryId=" + countryId + "]";
    	}
    }
    
    • ListServlet.java
    package com.abc.ajax.servlet;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import com.abc.ajax.dao.ListDao;
    import com.abc.ajax.po.city;
    import com.abc.ajax.po.country;
    import com.abc.ajax.po.state;
    public class ListServlet extends HttpServlet {
    	ListDao dao = new ListDao();
    	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    		resp.setCharacterEncoding("utf-8");
    		String method = req.getParameter("method");
    		if (method.equals("cList")) {
    			System.out.println("listServlet" + method);
    			List<state> listS = queryS();
    			List<country> listCo = queryCo();
    			List<city> listC = queryC();
    			if (listCo != null ) {
    				System.out.println(listCo.toString());
    				System.out.println(listS.toString());
    				System.out.println(listC.toString());
    				req.setAttribute("countryList", listCo);
    				req.setAttribute("stateList", listCo);
    				req.setAttribute("cityList", listC);
    				req.getRequestDispatcher("list.jsp").forward(req, resp);
    			}
    		}
    	}
    	private List<country> queryCo() {
    		List<country> list = dao.queryCountry();
    		System.out.println(" dao.queryCountry");
    		return list;
    	}
    	private List<state> queryS() {
    		List<state> list = dao.queryState();
    		System.out.println("dao.queryState");
    		return list;
    	}
    	private List<city> queryC() {
    		List<city> list = dao.queryCity();
    		System.out.println("dao.queryCity");
    		return list;
    	}
    }
    
    • JDBCUtil.java
    package com.abc.ajax.util;
    import java.io.IOException;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    import java.util.Properties;
    import com.abc.ajax.po.city;
    import com.abc.ajax.po.country;
    import com.abc.ajax.po.state;
    import com.mchange.v2.c3p0.ComboPooledDataSource;
    public class JDBCUtil {
    	private static ComboPooledDataSource ds = null;
    	// get properties from c3p0
    	static {
    		ds = new ComboPooledDataSource("jdbc_c3p0");
    	}
    	// get connection
    	public static Connection getConnection() {
    		try {
    			System.out.println("connection: " + ds.getConnection());
    			return ds.getConnection();
    		} catch (SQLException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		return null;
    	}
    	// close connection
    	public static void close(Connection conn) {
    		try {
    			if (conn != null) {
    				conn.close();
    			}
    		} catch (SQLException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    	// perform sql
    	public static List<country> queryCountry(Connection conn, String sql, String RegEx) {
    		PreparedStatement ps = null;
    		ResultSet rs = null;
    		List<country> list = new ArrayList<country>();
    		try {
    			ps = conn.prepareStatement(sql);
    			rs = ps.executeQuery();
    			System.out.println("JDBCUTIL" + sql);
    			while (rs.next()) {
    				int id = rs.getInt("id");
    				String countryName = rs.getString("countryName");
    				System.out.println(id + " " + countryName);
    				list.add(new country(id, countryName));
    			}
    			rs.close();
    			ps.close();
    			return list;
    		} catch (SQLException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		return null;
    	}
    	// state
    	public static List<state> queryState(Connection conn, String sql, int Cid) {
    		PreparedStatement ps = null;
    		ResultSet rs = null;
    		List<state> list = new ArrayList<state>();
    		try {
    			ps = conn.prepareStatement(sql);
    			if (Cid >0) {
    				ps.setInt(1, Cid);
    			}
    			rs = ps.executeQuery();
    			System.out.println("JDBCUTIL" + sql);
    
    			while (rs.next()) {
    				int id = rs.getInt("id");
    				String stateName = rs.getString("stateName");
    				int countryId = rs.getInt("countryId");
    				System.out.println(id + " " + stateName + " " + countryId);
    				list.add(new state(id, stateName, countryId));
    			}
    			rs.close();
    			ps.close();
    			return list;
    		} catch (SQLException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		return null;
    	}
    	// city
    	public static List<city> queryCity(Connection conn, String sql, int Sid) {
    		PreparedStatement ps = null;
    		ResultSet rs = null;
    		System.out.println("JDBCUTIL" + sql);
    
    		List<city> list = new ArrayList<city>();
    		try {
    			ps = conn.prepareStatement(sql);
    			if (Sid >0) {
    				ps.setInt(1, Sid);
    			}
    			rs = ps.executeQuery();
    			while (rs.next()) {
    				int id = rs.getInt("id");
    				String cityName = rs.getString("cityName");
    				int stateId = rs.getInt("stateId");
    				System.out.println(id + " " + cityName + " " + stateId);
    				list.add(new city(id, cityName, stateId));
    			}
    			rs.close();
    			ps.close();
    			return list;
    		} catch (SQLException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		return null;
    	}
    }
    
    • c3p0-config.xml
    
    <c3p0-config>
    	
    	<default-config>
    		<property name="initialPoolSize">10property>
    		<property name="maxPoolSize">100property>
    		<property name="minPoolSize">10property>
    		<property name="driverClass">com.mysql.cj.jdbc.Driverproperty>
    		<property name="jdbcUrl">jdbc:mysql://localhost:3306/area?serverTimezone=UTCproperty>
    		<property name="user">rootproperty>
    		<property name="password">12345property>
    	default-config>
    	
    	<named-config name="jdbc-c3p0">
    		<property name="initialPoolSize">10property>
    		<property name="maxPoolSize">100property>
    		<property name="minPoolSize">10property>
    		<property name="driverClass">com.mysql.cj.jdbc.Driverproperty>
    		<property name="jdbcUrl">jdbc:mysql://localhost:3306/area?serverTimezone=UTCproperty>
    		<property name="user">rootproperty>
    		<property name="password">12345property>
    	named-config>
    c3p0-config>
    
    
    • web.xml
    
    DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
    <web-app>
    	<display-name>webappjq3display-name>
    	<description>areaListdescription>
    	<servlet>
    		<servlet-name>ListServletservlet-name>
    		<servlet-class>com.abc.ajax.servlet.ListServletservlet-class>
    	servlet>
    	<servlet-mapping>
    		<servlet-name>ListServletservlet-name>
    		<url-pattern>*.actionurl-pattern>
    	servlet-mapping>
    web-app>
    
    • index.jsp
    <%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">    
        <title>My JSP 'index.jsp' starting pagetitle>
    	<meta http-equiv="pragma" content="no-cache">
    	<meta http-equiv="cache-control" content="no-cache">
    	<meta http-equiv="expires" content="0">    
    	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    	<meta http-equiv="description" content="This is my page">
    	
      head>
      <body>
        This is my JSP page. <br>
        <% response.sendRedirect("listServlet.action?method=cList");
        %>
      body>
    html>
    
    • list.jsp
    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <%@ page import="com.abc.ajax.po.country"%>
    <%@ page import="com.abc.ajax.po.state"%>
    <%@ page import="com.abc.ajax.po.city"%>
    DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>
    <title>My JSP 'List.jsp' starting pagetitle>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    
    head>
    <body>
    	<%
    		List<country> coList = (List<country>) request.getAttribute("countryList");
    		List<state> sList = (List<state>) request.getAttribute("stateList");
    		List<city> cList = (List<city>) request.getAttribute("cityList");
    		out.println(coList.toString());
    		out.println(sList.toString());
    		out.println(cList.toString());
    	%>
    	<select id="co">
    		<option selected="selected">COUNTRYoption>
    				<option value="">option>
    					select>   
    	<select id="st">
    		<option selected="selected">STATEoption>
    				<option value="">option>
    	select>   
    	<select id="ci">
    			<option selected="selected">CITYoption>
    		<option value="">option>
    	select>
    	<br>
    body>
    html>
    
    • SOLVE SQL & Navicat 2003 - can’t connect to mysql server on localhost(10061)
    • services.mscJQuery Ajax Maven [A]_第11张图片
    • connect with cmd as admin
    D:\Program Files\mysql\bin>mysql -u root -p
    Enter password: *****
    Welcome to the MySQL monitor.  Commands end with ; or \g.
    
    • SOLVE Several ports (8005, 8080, 8009) required by Tomcat v7.0 Server at localhost are already in use
    d:\>netstat -ano|findstr 4012
      UDP    127.0.0.1:1900         *:*                                    4012
    d:\>taskkill /pid 4012 /f
    

    Maven

    JQuery Ajax Maven [A]_第12张图片

    • organize Jars, project management, comprehension tool (Project Object Model) POM
    • maven
    • environment variables: system: add: name: MAVEN_HOME value: D:\Program Files\apache-maven-3.6.3
    • environment variables: system: add to path: ;%MAVEN_HOME%\bin;
    • other environment variables
      JQuery Ajax Maven [A]_第13张图片
    C:\Users\Administrator>mvn -v
    Apache Maven 3.6.3 (cecedd343002696d0abb50b32b541b8a6ba2883f)
    Maven home: D:\Program Files\apache-maven-3.6.3\bin\..
    Java version: 1.8.0_112, vendor: Oracle Corporation, runtime: C:\Program Files\Java\jdk1.8
    .0_112\jre
    Default locale: zh_CN, platform encoding: GBK
    OS name: "windows 8", version: "6.2", arch: "amd64", family: "windows"
    D:\Program Files\mysql\bin>java -version
    java version "9"
    Java(TM) SE Runtime Environment (build 9+181)
    Java HotSpot(TM) 64-Bit Server VM (build 9+181, mixed mode)
    
    • bin: executables ; boot: framework; conf: included packages; lib: java files
    • mvn help: system : print all system environment variable
    • project structure
    • POM location 在这里插入图片描述
      JQuery Ajax Maven [A]_第14张图片
    • cmd: shift right mouse click: open cmd from this location
      <repositories>
        <repository>
          <id>central</id>
          <name>Central Repository</name>
          <url>https://repo.maven.apache.org/maven2</url>
          <layout>default</layout>
          <snapshots>
            <enabled>false</enabled>
          </snapshots>
        </repository>
      </repositories>
    
    • conf/settings.xml
      <!-- localRepository
       | The path to the local repository maven will use to store artifacts.
       |
       | Default: ${user.home}/.m2/repository
      <localRepository>/path/to/local/repo</localRepository>
      -->
    
    • download from maven central repository
    • basic file structure
    maven01 
    	--src
    		--main
    			--java
    				--package: HelloWorldMVN.java
    			--resources
    		--testMVN
    			--java		
    				--package: HelloWorldMVNTest.java
    			--resources
    	--pom.xml
    	--[target]
    
    • maven compile: create target file under maven01
    D:\test\maven01> maven compile
    ...Downloading from central: https://repo.maven.apache.org/maven2/junit/junit/4.3/junit-4.3.pom...
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    D:\test\maven01> maven test
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    D:\test\maven01>mvn test-compile
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    D:\test\maven01>mvn help:evaluate -Dexpression=settings.localRepository
    C:\Users\Administrator\.m2\repository
    
    • D:\Program Files\apache-maven-3.6.3\conf\settings.xml
    • repo2
      <mirror>
          <id>repo2id>
          <mirrorOf>centralmirrorOf>
          <name>Human Readable Name for this Mirror.name>
          <url>https://repo.maven.apache.org/maven2/url>
        mirror>
    
    • dependencies

      1. groupId
      1. artifactId
      1. version
      1. package: zip, war, jar
      1. classfier
    • Hbase: hadoop database, uses rowkey, columnkey

    • maven

    • maven search

    • MAVEN01 project
      JQuery Ajax Maven [A]_第15张图片

    • pom.xml
      JQuery Ajax Maven [A]_第16张图片

    
    
    <project>
      <modelVersion>4.0.0modelVersion>
      
      
     <groupId>com.abc.mavengroupId>
       
     <artifactId>maven-demo1artifactId>
       
         
     <version>1.0.0SNAPSHOT version>
       
    <dependencies>
    <dependency>
        <groupId>junitgroupId>
        <artifactId>junitartifactId>
        <version>4.3version>
    dependency>
    dependencies>
    project>
    
    
    • HelloWorldMVN.java
      JQuery Ajax Maven [A]_第17张图片
    package com.abc.maven.helloworld;
    public class HelloWorldMVN{
    public String helloMaven(){
    return "Hello maven";}
    }
    
    • HelloworldmvnTest.java
      JQuery Ajax Maven [A]_第18张图片
    package com.abc.maven.helloworld;
    import org.junit.*;
    public class HelloWorldMVNTest{
    @Test
    public void testHello(){
    	Assert.assertEquals("Hello maven", new HelloWorldMVN().helloMaven());
    }	
    }
    
    • com.abc.maven.helloworld.HelloWorldMVNTest.txt
      JQuery Ajax Maven [A]_第19张图片
    -------------------------------------------------------------------------------
    Test set: com.abc.maven.helloworld.HelloWorldMVNTest
    -------------------------------------------------------------------------------
    Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.02 sec
    
    • add jar package into classpath (mvn install…mvn clean) …import…using pom.xml
      JQuery Ajax Maven [A]_第20张图片
      JQuery Ajax Maven [A]_第21张图片

    • get info from .pom file

    • groupId+artifactId(com.abc.maven.maven-demo1)

     <groupId>com.abc.mavengroupId>
     <artifactId>maven-demo1artifactId>
     <version>1.0.0SNAPSHOT version>
    
    • compile then test
    D:\test\maven01>mvn install
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    D:\test\maven01>mvn clean
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    D:\test\maven01>cd ..\maven02
    D:\test\maven02>mvn compile
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    D:\test\maven02>mvn clean compile test
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    

    JQuery Ajax Maven [A]_第22张图片

    • pom.xml
    
    <project>
      <modelVersion>4.0.0modelVersion>
      
     <groupId>com.abc.mavengroupId>
     <artifactId>maven-demo2artifactId>
     <version>0.0.1SNAPSHOT version>
    <dependencies>
    <dependency>
        <groupId>junitgroupId>
        <artifactId>junitartifactId>
        <version>4.9version>
    dependency>
    <dependency>
     <groupId>com.abc.mavengroupId>
     <artifactId>maven-demo1artifactId>
     <version>1.0.0SNAPSHOT version>
    dependency>
    dependencies>
    project>
    

    JQuery Ajax Maven [A]_第23张图片

    package com.abc.maven02.hellomaven;
    import  com.abc.maven.helloworld.HelloWorldMVN;
    public class HelloMaven{
    	public String sayMaven(){
    		return new HelloWorldMVN().helloMaven();
    	}
    }
    

    JQuery Ajax Maven [A]_第24张图片

    package com.abc.maven02.hellomaven;
    import org.junit.*;
    public class HelloMavenTest{
    	@Test
    	public void testSayMave(){
    		Assert.assertEquals("Hello maven", new HelloMaven().sayMaven());
    	}
    }  
    

    JQuery Ajax Maven [A]_第25张图片

    -------------------------------------------------------------------------------
    Test set: com.abc.maven02.hellomaven.HelloMavenTest
    -------------------------------------------------------------------------------
    Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.035 sec
    
    • archetype:generate create file structure
    • maven-archetype-quickstart
    • mvn archetype:generate -DgroupId=com.abc.maven04 -DartifactId=maven-demo04 -Dversion=1.0-SNAPSHOT
    D:\test\maven03>mvn archetype:generate
    ...
    Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): 1758:
    Choose org.apache.maven.archetypes:maven-archetype-quickstart version:
    1: 1.0-alpha-1
    2: 1.0-alpha-2
    3: 1.0-alpha-3
    4: 1.0-alpha-4
    5: 1.0
    6: 1.1
    7: 1.3
    8: 1.4
    Choose a number: 8:
    Define value for property 'groupId': com.abc.maven03
    Define value for property 'artifactId': maven-demo03
    Define value for property 'version' 1.0-SNAPSHOT: :
    Define value for property 'package' com.abc.maven03: :
    Confirm properties configuration:
    groupId: com.abc.maven03
    artifactId: maven-demo03
    version: 1.0-SNAPSHOT
    package: com.abc.maven03
     Y: : y
    [INFO] ----------------------------------------------------------------------------
    [INFO] Using following parameters for creating project from Archetype: maven-archetype-qui
    ckstart:1.4
    [INFO] ----------------------------------------------------------------------------
    [INFO] Parameter: groupId, Value: com.abc.maven03
    [INFO] Parameter: artifactId, Value: maven-demo03
    [INFO] Parameter: version, Value: 1.0-SNAPSHOT
    [INFO] Parameter: package, Value: com.abc.maven03
    [INFO] Parameter: packageInPathFormat, Value: com/abc/maven03
    [INFO] Parameter: package, Value: com.abc.maven03
    [INFO] Parameter: version, Value: 1.0-SNAPSHOT
    [INFO] Parameter: groupId, Value: com.abc.maven03
    [INFO] Parameter: artifactId, Value: maven-demo03
    [INFO] Project created from Archetype in dir: D:\test\maven03\maven-demo03
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    
    • result
      JQuery Ajax Maven [A]_第26张图片
    • Dpackage=com.abc.maven; DgroupId=company+project; DartifactId=project+module; Dversion=version
    • archetype 1. quickstart 2. webapp 3. simple
    • repository> mvn archetype:crawl (generate archetype-catalog.xml)
    • put file under .m2 folder
    • maven03> mvn archetype:generate -DarchetypeCatalog=local
      JQuery Ajax Maven [A]_第27张图片
    test>mvn archetype:generate -DgroupId=com.abc.maven04 -DartifactId=maven-demo04 -Dversion=1.0-SNAPSHOT -Dpackage=com.abc.maven04
    ...
    Choose a number or apply filter (format: [groupId:]artifactId, case sensitive contains): 1
    758:
    Choose org.apache.maven.archetypes:maven-archetype-quickstart version:
    1: 1.0-alpha-1
    2: 1.0-alpha-2
    3: 1.0-alpha-3
    4: 1.0-alpha-4
    5: 1.0
    6: 1.1
    7: 1.3
    8: 1.4
    Choose a number: 8: 6
    Downloading from central: https://repo.maven.apache.org/maven2/org/apache/maven/archetypes
    /maven-archetype-bundles/4/maven-archetype-bundles-4.pom
    Downloaded from central: https://repo.maven.apache.org/maven2/org/apache/maven/archetypes/
    maven-archetype-bundles/4/maven-archetype-bundles-4.pom (3.6 kB at 9.0 kB/s)
    Downloading from central: https://repo.maven.apache.org/maven2/org/apache/maven/archetype/
    maven-archetype/2.0-alpha-5/maven-archetype-2.0-alpha-5.pom
    Downloaded from central: https://repo.maven.apache.org/maven2/org/apache/maven/archetype/m
    aven-archetype/2.0-alpha-5/maven-archetype-2.0-alpha-5.pom (8.7 kB at 23 kB/s)
    [INFO] Using property: groupId = com.abc.maven04
    [INFO] Using property: artifactId = maven-demo04
    [INFO] Using property: version = 1.0-SNAPSHOT
    [INFO] Using property: package = com.abc.maven04
    Confirm properties configuration:
    groupId: com.abc.maven04
    artifactId: maven-demo04
    version: 1.0-SNAPSHOT
    package: com.abc.maven04
     Y: : y
    [INFO] ----------------------------------------------------------------------------
    [INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-arc
    hetype-quickstart:1.1
    [INFO] ----------------------------------------------------------------------------
    [INFO] Parameter: basedir, Value: D:\test
    [INFO] Parameter: package, Value: com.abc.maven04
    [INFO] Parameter: groupId, Value: com.abc.maven04
    [INFO] Parameter: artifactId, Value: maven-demo04
    [INFO] Parameter: packageName, Value: com.abc.maven04
    [INFO] Parameter: version, Value: 1.0-SNAPSHOT
    [INFO] project created from Old (1.x) Archetype in dir: D:\test\maven-demo04
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    ...
    C:\Users\Administrator\.m2>mvn archetype:crawl 
    ...
    
    D:\test\maven-demo04>mvn install archetype:update-local-catalog
    [INFO] --- maven-archetype-plugin:3.2.0:update-local-catalog (default-cli) @ maven-demo04
    ---
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    
    • result
      JQuery Ajax Maven [A]_第28张图片

    • platforms: 1. myEclipse 2.intelj

    • myEclipse: install new software
      JQuery Ajax Maven [A]_第29张图片

    • myEclipse: window: preference
      JQuery Ajax Maven [A]_第30张图片
      JQuery Ajax Maven [A]_第31张图片
      JQuery Ajax Maven [A]_第32张图片
      JQuery Ajax Maven [A]_第33张图片
      JQuery Ajax Maven [A]_第34张图片
      JQuery Ajax Maven [A]_第35张图片

    • drop in jar file, restart
      在这里插入图片描述

    • error: could not get the value for parameter encoding for plugin execution default-resources

    1. Close Eclipse.
    2. Navigate to user home directory. (For example: “C:\Users\YourUserName.m2”) ; Delete the “repository” folder.
    3. Re-open Eclipse.
    4. Click on the Maven project that has an issue and go to “Project” --> “Clean”.
    5. Right-click on the project and go to “Maven” --> “Update Project…”.
    6. Close Eclipse. Open Eclipse.
    7. Click on the project folder in the “Project Explorer” window (usually on the left).
    8. Hit the “F5” key to Refresh your project.
    • error: POM: org.apache.maven.archiver.MavenArchiver.getManifest(org.apache.maven.project.MavenProject, org.apache.maven.archiver.MavenArchiveConfiguration)

    • https://repo1.maven.org/maven2/.m2e/connectors/m2eclipse-mavenarchiver/0.17.2/N/LATEST/JQuery Ajax Maven [A]_第36张图片

      1. Close Eclipse. Open Eclipse.
      1. Click on the project folder in the “Project Explorer” window (usually on the left).
      1. Hit the “F5” key to Refresh your project.
      1. recreate maven project
      1. choose :
        JQuery Ajax Maven [A]_第37张图片
    • error: -Dmaven.multiModuleProjectDirectory system is not set

    • right click JRE system library>build path> configure build path
      JQuery Ajax Maven [A]_第38张图片

      1. eclipse> window> show view> other> problems
      1. window> preferences>maven>installations> add
      1. window>preferences>maven>User Settings
      1. new>other>maven project
      1. run as> 1.maven build (clean test)
        JQuery Ajax Maven [A]_第39张图片
    • result

    [INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ maven-demo01 ---
    [INFO] Surefire report directory: D:\MEWorkspace\maven-demo01\target\surefire-reports
    -------------------------------------------------------
     T E S T S
    -------------------------------------------------------
    Running com.abc.maven.maven_demo01.AppTest
    Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.005 sec
    Results :
    Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    
    • 3 classpath: compile, test, runtime

    • 6 dependency scope:

      1. compile: default (all three)
      1. provided: compile, test, servlet api
      1. runtime: test, runtime, JDBC driver
      1. test: cannot use junit
      1. system: use system path instead of maven repository
      1. import
    • code for dependency

     <dependencies>
        <dependency>
          <groupId>junitgroupId>
          <artifactId>junitartifactId>
          <version>3.8.1version>
          <scope>testscope>
        dependency>
      dependencies>
    
    • left column> upper row
      JQuery Ajax Maven [A]_第40张图片

      1. coordinates
      1. dependency scope
      1. dependency delivery
      1. dependency conflict: short route first (a>b>c>d)vs (a>b>d) ; same distance must declare precedence
      1. dependency life cycle : clean>test>install/build
      1. dependency life cycle ( clean: pre-clean>clean>post-clean)
      1. dependency life cycle (default: validate>compile>test>package>integration0test>verify>install>deploy)
      1. dependency life cycle (site: pre-site>site>post-site>site-deploy)
      1. maven plugins (maven source plugin )
      1. collections and inheritence
    • example

    • employee > manager > boss

    • maven clean> maven install> maven build

    JQuery Ajax Maven [A]_第41张图片

    • company-boss pom.xml
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0modelVersion>
      <groupId>com.abc.mavengroupId>
      <artifactId>company-bossartifactId>
      <version>0.0.1-SNAPSHOTversion>
      <packaging>jarpackaging>
      <name>company-bossname>
      <url>http://maven.apache.orgurl>
      <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
      properties>
      <dependencies>
        <dependency>
          <groupId>junitgroupId>
          <artifactId>junitartifactId>
          <version>3.8.1version>
          <scope>testscope>
        dependency>
      dependencies>
    project>
    
    
    • company-manager pom.xml
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    	<modelVersion>4.0.0modelVersion>
    	<groupId>com.abc.mavengroupId>
    	<artifactId>company-managerartifactId>
    	<version>0.0.1-SNAPSHOTversion>
    	<packaging>jarpackaging>
    	<name>company-managername>
    	<url>http://maven.apache.orgurl>
    	<properties>
    		<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    	properties>
    	<dependencies>
    		<dependency>
    			<groupId>junitgroupId>
    			<artifactId>junitartifactId>
    			<version>3.8.1version>
    			<scope>testscope>
    		dependency>
    				
    		<dependency>
    			<groupId>com.abc.mavengroupId>
    			<artifactId>company-bossartifactId>
    			<version>0.0.1-SNAPSHOTversion>
    		dependency>
    	dependencies>
    project>
    
    • company-employee pom.xml
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0modelVersion>
    
      <groupId>com.abc.mavengroupId>
      <artifactId>company-employeeartifactId>
      <version>0.0.1-SNAPSHOTversion>
      <packaging>jarpackaging>
      <name>company-employeename>
      <url>http://maven.apache.orgurl>
      <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
      properties>
      <dependencies>
        <dependency>
          <groupId>junitgroupId>
          <artifactId>junitartifactId>
          <version>3.8.1version>
          <scope>testscope>
        dependency>
        
          <dependency>
    		  <groupId>com.abc.mavengroupId>
    		  <artifactId>company-managerartifactId>
    		  <version>0.0.1-SNAPSHOTversion>
        dependency>
      dependencies>
    project>
    
    • for employee not to rely on boss and only employee add in dependency for company-manager:
         <dependency>
    		  <groupId>com.abc.mavengroupId>
    		  <artifactId>company-managerartifactId>
    		  <version>0.0.1-SNAPSHOTversion>
    			<exclusions>
    				<exclusion>
    						<groupId>com.abc.mavengroupId>
    						<artifactId>company-bossartifactId>
    				exclusion>
    			exclusions>    
    	dependency>
    
    • result
    -------------------------------------------------------
     T E S T S
    -------------------------------------------------------
    Running com.abc.maven.company_employee.AppTest
    Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.005 sec
    
    Results :
    
    Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
    
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] -----------------------------------------------------------------
    
    • employee> manager(commons-io 2.0)>boss(commons-io 2.4)
    • boss has shortest path therefore 2.4 is used
    • added dependency
    		<dependency>
    			<groupId>commons-iogroupId>
    			<artifactId>commons-ioartifactId>
    			<version>2.?version>
    		dependency>
    
    • result
      JQuery Ajax Maven [A]_第42张图片
    • test plugin
    • add to maven-demo01 dom.xml
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0modelVersion>
      <groupId>com.abc.mavengroupId>
      <artifactId>maven-demo01artifactId>
      <version>0.0.1-SNAPSHOTversion>
      <packaging>jarpackaging>
      <name>maven-demo01name>
      <url>http://maven.apache.orgurl>
      <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
      properties>
      <dependencies>
        <dependency>
          <groupId>junitgroupId>
          <artifactId>junitartifactId>
          <version>3.8.1version>
          <scope>testscope>
        dependency>
      dependencies>
      	<build>
    		<plugins>
    			<plugin>
    				<groupId>org.apache.maven.pluginsgroupId>
    				<artifactId>maven-source-pluginartifactId>
    				<version>3.2.0version>
    				<executions>
    					<execution>
    						<phase>packagephase>
    						<goals>
    							<goal>jar-no-forkgoal>
    						goals>
    					execution>
    				executions>
    			plugin>
    		plugins>
    	build>
    project>
    
    • result
    [INFO] Building jar: D:\MEWorkspace\maven-demo01\target\maven-demo01-0.0.1-SNAPSHOT-sources.jar
    ...
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    
    • aggregation use modules for packages < packaging >pom…< modules >
      JQuery Ajax Maven [A]_第43张图片
      pom.xml
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    	<modelVersion>4.0.0modelVersion>
    	<groupId>com.abc.mavengroupId>
    	<artifactId>company-aggregationartifactId>
    	<version>0.0.1-SNAPSHOTversion>
    	<packaging>pompackaging>
    	<name>company-aggregationname>
    	<url>http://maven.apache.orgurl>
    	<properties>
    		<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    	properties>
    	<modules>
    		<module>../company-bossmodule>
    		<module>../company-managermodule>
    		<module>../company-employeemodule>
    	modules>
    	<dependencies>
    		<dependency>
    			<groupId>junitgroupId>
    			<artifactId>junitartifactId>
    			<version>3.8.1version>
    			<scope>testscope>
    		dependency>
    	dependencies>
    project>
    
    • result
    [INFO] Reactor Summary for company-aggregation 0.0.1-SNAPSHOT:
    [INFO] 
    [INFO] company-boss ....................................... SUCCESS [  0.502 s]
    [INFO] company-manager .................................... SUCCESS [  0.020 s]
    [INFO] company-employee ................................... SUCCESS [  0.010 s]
    [INFO] company-aggregation ................................ SUCCESS [  0.005 s]
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    
    • inheritance
    • check for version junit : ctrl+ version
    • delete src/test/java
    • use dependencyManagement < junit.version>4.10< /junit.version> < version>${junit.version}< /version>
    • dependency passed to children projects (dependencies)

    在这里插入图片描述

    • company-parent pom.xml
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0modelVersion>
      <groupId>com.abc.mavengroupId>
      <artifactId>company-parentartifactId>
      <version>0.0.1-SNAPSHOTversion>
      <packaging>pompackaging>
      <name>company-parentname>
      <url>http://maven.apache.orgurl>
      <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        <junit.version>4.10junit.version>
      properties> 
    <dependencyManagement>
      <dependencies>
        <dependency>
          <groupId>junitgroupId>
          <artifactId>junitartifactId>
          <version>${junit.version}version>
          <scope>testscope>
        dependency>
      dependencies>
      dependencyManagement>
    project>
    
    • changes to other (boss, manager, employee pom.xml)
    • remove < groupId>com.abc.maven< /groupId> ; < version>0.0.1-SNAPSHOT< /version>
      <parent>
        <groupId>com.abc.mavengroupId>
      <artifactId>company-parentartifactId>
      <version>0.0.1-SNAPSHOTversion>
      parent>
    	<dependencies>
    		<dependency>
    			<groupId>junitgroupId>
    			<artifactId>junitartifactId>
    		dependency>
    
    • result
    [INFO] Building company-parent 0.0.1-SNAPSHOT
    [INFO] --------------------------------[ pom ]---------------------------------
    [INFO] 
    [INFO] --- maven-install-plugin:2.4:install (default-install) @ company-parent ---
    [INFO] Installing D:\MEWorkspace\company-parent\pom.xml to C:\Users\Administrator\.m2\repository\com\abc\maven\company-parent\0.0.1-SNAPSHOT\company-parent-0.0.1-SNAPSHOT.pom
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    
    • MAVEN WEB
      JQuery Ajax Maven [A]_第44张图片

    • error : the superclass “javax.servlet.http.HttpServlet” was not found…

    • java Servlet

    • add dependency to pom.xml < groupId>javax.servlet…< artifactId>… < version> …

    • change scope to provided < scope> provided …for servlet…dependency

    • change maven project to web project: project> properties> project facet> convert to facet form> dynamic web module

    • select java 1.8

    • check src>main>webapp>WEB-INF
      JQuery Ajax Maven [A]_第45张图片

    • remove test/ from properties/deployment assembly
      JQuery Ajax Maven [A]_第46张图片

    • add new source folder to maven-web: src/test/resources
      JQuery Ajax Maven [A]_第47张图片
      JQuery Ajax Maven [A]_第48张图片

    • check build path
      JQuery Ajax Maven [A]_第49张图片

    • maven-web
      JQuery Ajax Maven [A]_第50张图片

    • maven-web pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    	<modelVersion>4.0.0modelVersion>
    	<groupId>com.abc.mavengroupId>
    	<artifactId>maven-webartifactId>
    	<packaging>warpackaging>
    	<version>0.0.1-SNAPSHOTversion>
    	<name>maven-web Maven Webappname>
    	<url>http://maven.apache.orgurl>
    	<dependencies>
    		<dependency>
    			<groupId>junitgroupId>
    			<artifactId>junitartifactId>
    			<version>3.8.1version>
    			<scope>testscope>
    		dependency>
    		
    		<dependency>
    			<groupId>javax.servletgroupId>
    			<artifactId>javax.servlet-apiartifactId>
    			<version>4.0.1version>
    			<scope>providedscope>
    		dependency>
    	dependencies>
    	<build>
    		<finalName>maven-webfinalName>
    	build>
    project>
    
    • result
    [INFO] Installing D:\MEWorkspace\maven-web\pom.xml to C:\Users\Administrator\.m2\repository\com\abc\maven\maven-web\0.0.1-SNAPSHOT\maven-web-0.0.1-SNAPSHOT.pom
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    
    • run maven web deployment: jetty: lightweight web server : jetty maven
      JQuery Ajax Maven [A]_第51张图片

    • add to pom.xml

    ...
    	<packaging>warpackaging>
    ...
    	<build>
    		<finalName>maven-webfinalName>
    		<plugins>
    			<plugin>
    				<groupId>org.eclipse.jettygroupId>
    				<artifactId>jetty-maven-pluginartifactId>
    				<version>9.4.8.v20180619version>		
    			plugin>		
    		plugins>
    	build>
    
    • use “jetty:run” as maven build goal
    • result:
    [INFO] jetty-9.4.8.v20180619, build timestamp: 2018-06-21T07:55:30+08:00, git hash: ...
    [INFO] Started o.e.j.m.p.JettyWebAppContext@29138d3a{/,file:///D:/MEWorkspace/maven-web/src/main/webapp/,AVAILABLE}{file:///D:/MEWorkspace/maven-web/src/main/webapp/}
    [INFO] Started ServerConnector@58437801{HTTP/1.1,[http/1.1]}{0.0.0.0:8080}
    [INFO] Started @46013ms
    [INFO] Started Jetty Server
    
    • result
      在这里插入图片描述
    • use “package” as maven build goal
    • add to pom.xml
    ...
    	<packaging>warpackaging>
    ...
    <build>
    		<finalName>maven-webfinalName>
    		<plugins>
    			<plugin>
    				<groupId>org.eclipse.jettygroupId>
    				<artifactId>jetty-maven-pluginartifactId>
    				<version>9.4.8.v20180619version>
    				<executions>
    					<execution>
    						<phase>packagephase>
    						<goals>
    							<goal>rungoal>
    						goals>
    					execution>
    				executions>
    			plugin>
    		plugins>
    	build>
    
    • run maven web deployment: tomcat : tomcat plugin
    • get rid of jetty plugin
    • add to pom.xml
    			<plugin>
    				
    				<groupId>org.apache.tomcat.mavengroupId>
    				<artifactId>tomcat7-maven-pluginartifactId>
    				<version>2.2version>
    				<executions>
    					<execution>
    						<phase>packagephase>
    						<goals>
    							<goal>rungoal>
    						goals>
    					execution>
    				executions>
    			plugin>
    
    • error: Failed to initialize end point associated with ProtocolHandler [“http-bio-8080”] java.net.BindException: Address already in use: JVM_Bind < null>:8080
    • cmd
    D:\>netstat -ano|findstr 8080
      TCP    0.0.0.0:8080           0.0.0.0:0              LISTENING       30664
      TCP    [::]:8080              [::]:0                 LISTENING       30664
    D:\>taskkill /pid 30664 /f
    成功: 已终止 PID 为 30664 的进程。
    
    • result
    三月 31, 2021 6:58:53 上午 org.apache.coyote.AbstractProtocol init
    信息: Initializing ProtocolHandler ["http-bio-8080"]
    三月 31, 2021 6:58:53 上午 org.apache.catalina.core.StandardService startInternal
    信息: Starting service Tomcat
    三月 31, 2021 6:58:53 上午 org.apache.catalina.core.StandardEngine startInternal
    信息: Starting Servlet Engine: Apache Tomcat/7.0.47
    三月 31, 2021 6:58:54 上午 org.apache.coyote.AbstractProtocol start
    信息: Starting ProtocolHandler ["http-bio-8080"]
    
    • result:
      JQuery Ajax Maven [A]_第52张图片

    • problems gbk>utf-8

    • solve

    <properties>
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    properties>
    ...
    <plugin>
    <artifactId>maven-compiler-pluginartifactId>
    <configuration> 
    <source>1.6source>
    <target>1.6target>
    <encoding>utf8encoding>
    configuration>
    plugin> 
    
    • problems xxx.jar was cached in the local repository, resolution will not be reattempted until…

    • solve:

    • < updatePolicy>always< /updatePolicy> under settings.xml ( not recommeded) (always, daily, interval:X min, never)

    • or…delete lastUpdated file, update file…

    • or…delete org.apache.plugin:maven-source-plugin, redownload

    • problems connection refused; connection timeout

    • solve:

    • dos: ping www.something.com

    • install jar offline: put jar in .m2/repository

    • tips: use QuickFix

    • Update Project

    • Configure build path

    • problem: change to 1.5 instead of 1.8 or higher

    • solve:

    • add to pom.xml

    <plugin>
    <groupId>org.apache.maven.pluginsgroupId>
    <artifactId>maven-compiler-pluginartifactId>
    <version>3.1version>
    <configuration>
    <source>1.8source>
    <target>1.8target>
    <encoding>utf8encoding>
    configuration>
    plugin>
    
    • /pom.xml :: < packaging>pom< /packaging>

    • /common-lib/ :: < packaging>jar< /packaging>

    • /public-webapp/ :: < packaging>war< /packaging> < dependency>common-lib

    • /admin-webapp/ :: < packaging>war< /packaging> < dependency>common-lib< /dependency>

    • /corporate-webapp/ :: < packaging>war< /packaging> < dependency>common-lib< /dependency>

    • COMMANDS

    • maven commands: 1. mvn -v or mvn -version

    • maven commands: 2. mvn help: system (MAVEN_HOME=D:\Program Files\apache-maven-3.6.3\bin…)

    • maven commands: 3. mvn compile (downloading: http://repo…)

    • maven commands: 4. mvn test

    • maven commands: 5. mvn test-compile

    • maven commands: 6. mvn help:evaluate -Dexpression=settings.localRepository (find local repo)

    • maven commands: 7. mvn install (install current package into repository, add groupId, artifactId, version to pom.xml)

    • maven commands: 8. mvn clean compile test

    • maven commands: 9. mvn clean (clean file before install into jar file)

    • maven commands: 10. mvn archetype:generate (create file structure)

    • maven commands: 11.mvn archetype:generate -DgroupId=com.abc.maven04 -DartifactId=maven-demo04 -Dversion=1.0-SNAPSHOT -Dpackage=com.abc.maven04

    • maven commands: 12. mvn archetype:crawl (generate archetype-catalog.xml)

    • maven commands: 13. mvn archetype:generate -DarchetypeCatalog=local (generate testfile ???)

    • maven commands: 14. mvn install archetype:update-local-catalog


    你可能感兴趣的:(jquery,ajax,maven)