1. 程式人生 > 實用技巧 >Java從入門到實戰之(7)SSH框架整合

Java從入門到實戰之(7)SSH框架整合

一:前後端互動編碼方式

1.urlencoded

form表單預設是urlencoded編碼格式傳輸資料

資料格式:username=Darker&password=123456

django會將該格式的資料 自動解析並打包到request.POST

2.form-data

資料分為2部分:資料檔案

資料部分:username=Darker&password=123456
-----分隔-----
檔案部分(二進位制)

資料 自動解析並打包到request.POST

檔案 自動解析並打包到request.FILES

3.json

django後端針對json格式資料 並不會做任何的處理

,而是直接放在request.body

# request.body

{
    "username": "Darker",
    "password": "123456"
}

二:Django模板使用的2種方式

# 模板

<div class="panel panel-default">
    <div class="panel-heading text-center"><h1>{{ word }}</h1></div>
    <div class="panel-body text-center">
    	<h1>{{ current_time }}</h1>
    </div>
</div>

方式1

import datetime

def test(request):
    now = datetime.datetime.now()
    return render(request, 'test.html', context={'current_time': str(now), 'word': 'Hello World'})

方式2 - 頁面靜態化

import datetime

def test(request):
    now=datetime.datetime.now()
    from mysite import settings
    import os
    path=os.path.join(settings.BASE_DIR,'templates','test.html')
    ss=open(path,'r',encoding='utf-8').read()
    t=Template(ss)
    c=Context({'current_date':str(now),'word': 'Hello World'})
    html=t.render(c)  # html是渲染後的字串
    return HttpResponse(html)now=datetime.datetime.now()

三:變數

DTL:Django Template Language(Django模板語言)

def test(request):
    x_num = 666
    x_str = 'Hello World'
    x_bool = True
    x_list = ['Nice', 'Beautiful', {'usr': 'root', 'pwd':123}, 7]
    x_dict = {'name': 'Darker', 'age': 18, 'gender': 'male'}
    x_set = {1, 2, 3, 4, 5}
    x_tuple = (9, 8, 7, 6, 5)

    def x_func():
        print('I\'m function-print')
        return 'I\'m function-return'

    class X_Info(object):
        def __init__(self, name):
            self.name = name

        def print_name(self):
            return self.name

        def __str__(self):
            return self.name

    x_obj = X_Info('Darker')

    return render(request, 'test.html', locals())  # locals() 把當前作用域下所有的變數,都傳到context中
# test.html

<div class="panel panel-default">
    <div class="panel-heading text-center"><h1>變數</h1></div>
    <div class="panel-body ">
        <ul style="line-height: 30px;">
            <li>Num:{{ x_num }}</li>
            <li>Str:{{ x_str }}</li>
            <li>Bool:{{ x_bool }}</li>
            <li>List:{{ x_list }}</li>
            <li>Dict:{{ x_dict }}</li>
            <li>Set:{{ x_set }}</li>
            <li>Tuple:{{ x_tuple }}</li>
            <li>Function:{{ x_func }}</li>
            <li>Class:{{ X_Info }}</li>
            <li>Class_Obj:{{ x_obj }}</li>
        </ul>
    </div>
</div>

結論:

  • 基本資料型別都可以傳輸
  • 函式需要retuen
  • 類無法傳輸,也無法列印記憶體地址
  • 類例項化的物件可以傳輸,但是需要在類中定義__str__

四:句點符查詢

直接用.來操作

# views.py


from django.utils.safestring import mark_safe

def test(request):
    x_list = ['Nice', 'Beautiful', {'usr': 'root', 'pwd':123}, 7]
    x_dict = {'name': 'Darker', 'age': 18, 'gender': 'male'}
    x_set = {1, 2, 3, 4, 5}
    x_tuple = (9, 8, 7, 6, 5)
    x_link1 = '<a href="http://www.xuexianqi.top">Click Here</a>'
    x_link2 = mark_safe(x_link1)
    x_inp1 = '<br><input type="text" name="name">'
    x_inp2 = mark_safe(x_inp1)
    x_script1 = '<script>alert("彈窗警告!")</script>'
    x_script2 = mark_safe(x_script1)

    def x_func():
        print('I\'m function-print')
        return 'I\'m function-return'

    class X_Info(object):
        def __init__(self, name):
            self.name = name

        def print_name(self):
            return self.name

        def __str__(self):
            return self.name

    x_obj = X_Info('Darker')

    return render(request, 'test.html', locals())
# test.html

<div class="panel panel-default">
    <div class="panel-heading text-center"><h1>變數</h1></div>
    <div class="panel-body ">
        <ul style="line-height: 30px;">
            <li>列表的第2個元素:{{ x_list.1 }}</li>
            <li>列表第3個元素的值:{{ x_list.2.usr }}</li>
            <li>字典中name的值:{{ x_dict.name }}</li>
            <li>集合的第4個元素:{{ x_set.3 }}</li>
            <li>元組的第5個元素:{{ x_tuple.4 }}</li>
            <li>執行函式x_func:{{ x_func }}</li>
            <li>呼叫物件x_obj的方法:{{ x_obj.print_name }}</li>
            <li>呼叫物件x_obj的屬性:{{ x_obj.name }}</li>
            <li>a標籤字串1:{{ x_link1 }}</li>
            <li>a標籤字串2:{{ x_link2 }}</li>
            <li>輸入框1:{{ x_inp1 }}</li>
            <li>彈窗警告1:{{ x_script1 }}</li>
            <li>彈窗警告2:{{ x_script2 }}</li>
        </ul>
    </div>
</div>

結論:

  • 列表、元組、集合 可以.索引取值
  • 集合無法.索引取值,因為集合是無序的
  • 字典取值直接.,而不是.get()或者[]
  • 函式和類可以.屬性和方法來執行
  • mark_safe()包裹的標籤 被認為是安全的,可以被渲染
  • mark_safe()需要匯入:from django.utils.safestring import mark_safe

五:過濾器

語法:{{obj|filter__name:param}} 變數名字|過濾器名稱:變數

default - 設定預設值

如果一個變數是false或者為,使用給定的預設值。否則,使用變數的值。

語法:{{ value|default:"nothing" }}

# views.py

def test(request):
    x_num0 = 0
    x_num1 = 1
    x_bool_t = True
    x_bool_f = False
    x_emp_dic = {}
    x_emp_list = []

    return render(request, 'test.html', locals())
# test.html

<div class="panel panel-default">
    <div class="panel-heading text-center"><h1>default</h1></div>
    <div class="panel-body ">
        <ul style="line-height: 30px;">
            <li>x_num0:{{ x_num0|default:"我是預設值" }}</li>
            <li>x_num1:{{ x_num1|default:"我是預設值" }}</li>
            <li>x_bool_t:{{ x_bool_t|default:"我是預設值" }}</li>
            <li>x_bool_f:{{ x_bool_f|default:"我是預設值" }}</li>
            <li>x_emp_dic:{{ x_emp_dic|default:"我是預設值" }}</li>
            <li>x_emp_list:{{ x_emp_list|default:"我是預設值" }}</li>
        </ul>
    </div>
</div>

結論:

  • bool值為False,使用預設值
  • 數值為0,使用預設值
  • 空列表,使用預設值
  • 空字典,使用預設值
  • 其餘全部使用變數原來的值

length - 返回長度

返回值的長度,對可迭代物件有效

# views.py

def test(request):
    x_num = 666
    x_str = 'Hello World'
    x_bool = True
    x_list = ['Nice', 'Beautiful', {'usr': 'root', 'pwd': 123}, 7]
    x_dict = {'name': 'Darker', 'age': 18, 'gender': 'male'}
    x_set = {1, 2, 3, 4, 5}
    x_tuple = (9, 8, 7, 6, 5)

    return render(request, 'test.html', locals())
# test.html

<div class="panel panel-default">
    <div class="panel-heading text-center"><h1>default</h1></div>
    <div class="panel-body ">
        <ul style="line-height: 30px;">
            <li>x_num:{{ x_num|length }}</li>
            <li>x_str:{{ x_str|length }}</li>
            <li>x_bool:{{ x_bool|length }}</li>
            <li>x_list:{{ x_list|length }}</li>
            <li>x_dict:{{ x_dict|length }}</li>
            <li>x_set:{{ x_set|length }}</li>
            <li>x_tuple:{{ x_tuple|length }}</li>
        </ul>
    </div>
</div>

結論:

  • 數字、布林型別 不能計算長度
  • 列表、字典、元組、集合、字串 都可以計算長度

filesizeformat - 返回大小

將值格式化為一個人類可讀的檔案尺寸

# views.py

def test(request):
    x_num1 = 1
    x_num2 = 8
    x_num3 = 1024
    x_num4 = 1024*10
    x_num5 = 1024**2
    x_num6 = 1024**3
    x_num7 = 1024**4
    x_num8 = 1024**5
    x_str = 'Hello World'
    x_bool = True
    x_list = ['Nice', 'Beautiful', {'usr': 'root', 'pwd': 123}, 7]
    x_dict = {'name': 'Darker', 'age': 18, 'gender': 'male'}
    x_set = {1, 2, 3, 4, 5}
    x_tuple = (9, 8, 7, 6, 5)

    return render(request, 'test.html', locals())
# test.html

<div class="panel panel-default">
    <div class="panel-heading text-center"><h1>default</h1></div>
    <div class="panel-body ">
        <ul style="line-height: 30px;">
            <li>x_num1:{{ x_num1|filesizeformat }}</li>
            <li>x_num2:{{ x_num2|filesizeformat }}</li>
            <li>x_num3:{{ x_num3|filesizeformat }}</li>
            <li>x_num4:{{ x_num4|filesizeformat }}</li>
            <li>x_num5:{{ x_num5|filesizeformat }}</li>
            <li>x_num6:{{ x_num6|filesizeformat }}</li>
            <li>x_num7:{{ x_num7|filesizeformat }}</li>
            <li>x_num8:{{ x_num8|filesizeformat }}</li>
            <li>x_str:{{ x_str|filesizeformat }}</li>
            <li>x_bool:{{ x_bool|filesizeformat }}</li>
            <li>x_list:{{ x_list|filesizeformat }}</li>
            <li>x_dict:{{ x_dict|filesizeformat }}</li>
            <li>x_set:{{ x_set|filesizeformat }}</li>
            <li>x_tuple:{{ x_tuple|filesizeformat }}</li>
        </ul>
    </div>
</div>

結論:

  • filesizeformat主要用於數字型別
  • 最小單位是1位元組(1bit)
  • bool值True相當於數字1,所以是1位元組
  • 列表、字典、元組、集合、字串 都無法計算大小

date - 返回日期

格式化日期

# views.py

from datetime import datetime

def test(request):
    x_time = datetime.now()

    return render(request, 'test.html', locals())
# test.html

<div class="panel panel-default">
    <div class="panel-heading text-center"><h1>date</h1></div>
    <div class="panel-body ">
        <ul style="line-height: 30px;">
            <li>x_time:{{ x_time|date:"Y-m-d" }}</li>
            <li>x_time:{{ x_time|date:"Y-m-d H-i-s" }}</li>
            <li>x_time:{{ x_time|date:"Y-m-d | H-i-s" }}</li>
            <li>x_time:{{ x_time|date:"Y年m月d日" }}</li>
            <li>x_time:{{ x_time|date:"Y年m月d日 H時i分s秒" }}</li>
            <li>x_time:{{ x_time|date:"Y年m月d日 | H時i分s秒" }}</li>
        </ul>
    </div>
</div>

結論:

  • YH需要大寫,其餘全部小寫
  • date:後面不能出現空格

slice - 切片

顧頭不顧尾

# views.py

def test(request):
    x_str1 = '123456789'
    x_str2 = '八進位制和十進位制其實也差不多,如果你少了兩根手指頭的話。'
    x_str3 = 'Base eight is just like base ten really, if you\'re missing two fingers.'

    return render(request, 'test.html', locals())
# test.html

<div class="panel panel-default">
    <div class="panel-heading text-center"><h1>slice</h1></div>
    <div class="panel-body ">
        <ul style="line-height: 30px;">
            <li>x_str1  0:5:{{ x_str1|slice:"0:5" }}</li>
            <li>x_str1  1:3:{{ x_str1|slice:"1:3" }}</li>
            <li>x_str1  3:7:{{ x_str1|slice:"3:7" }}</li>
            <li>x_str2  0:5:{{ x_str2|slice:"0:5" }}</li>
            <li>x_str2  1:3:{{ x_str2|slice:"1:3" }}</li>
            <li>x_str2  3:7:{{ x_str2|slice:"3:7" }}</li>
            <li>x_str3  0:5:{{ x_str3|slice:"0:5" }}</li>
            <li>x_str3  1:3:{{ x_str3|slice:"1:3" }}</li>
            <li>x_str3  3:7:{{ x_str3|slice:"3:7" }}</li>
        </ul>
    </div>
</div>

結論:

  • 這個切片和python的切片用法相同,都是顧頭不顧尾,下標就是索引0開始的
  • 中英文字元都一樣

truncatechars - 最大可現實的字數

如果字串字元多於指定的字元數量,那麼會被截斷

截斷的字串將以可翻譯的省略號序列(“...”)結尾。

# views.py

def test(request):
    x_str1 = '123456789'
    x_str2 = '八進位制和十進位制其實也差不多,如果你少了兩根手指頭的話。'
    x_str3 = 'Base eight is just like base ten really, if you\'re missing two fingers.'

    return render(request, 'test.html', locals())
# test.html

<div class="panel panel-default">
    <div class="panel-heading text-center"><h1>truncatechars</h1></div>
    <div class="panel-body ">
        <ul style="line-height: 30px;">
            <li>x_str1:{{ x_str1|truncatechars:"1" }}</li>
            <li>x_str1:{{ x_str1|truncatechars:"2" }}</li>
            <li>x_str1:{{ x_str1|truncatechars:"3" }}</li>
            <li>x_str1:{{ x_str1|truncatechars:"4" }}</li>
            <li>x_str1:{{ x_str1|truncatechars:"5" }}</li>
            <li>x_str2:{{ x_str2|truncatechars:"3" }}</li>
            <li>x_str2:{{ x_str2|truncatechars:"10" }}</li>
            <li>x_str2:{{ x_str2|truncatechars:"15" }}</li>
            <li>x_str3:{{ x_str3|truncatechars:"3" }}</li>
            <li>x_str3:{{ x_str3|truncatechars:"10" }}</li>
            <li>x_str3:{{ x_str3|truncatechars:"15" }}</li>
        </ul>
    </div>
</div>

結論:

  • 1、2、3都一樣............
  • 其餘都要減個3
  • 中英文都一樣

safe - 語法標籤轉義

Django的模板中會對HTML標籤和JS等語法標籤進行自動轉義`,原因顯而易見,這樣是為了安全`。

但是有的時候我們可能不希望這些HTML元素被轉義,這時候就用到了safe過濾器了

# views.py

def test(request):
    x_str1 = 'Hello World'
    x_str2 = '<u>Hello World</u>'
    x_str3 = '<a href="https://www.baidu.com">Hello World</a>'

    return render(request, 'test.html', locals())
# test.html

<div class="panel panel-default">
    <div class="panel-heading text-center"><h1>safe</h1></div>
    <div class="panel-body ">
        <ul style="line-height: 30px;">
            <li>x_str1 已轉義:{{ x_str1 }}</li>
            <li>x_str1 未轉義:{{ x_str1|safe }}</li>
            <li>x_str2 已轉義:{{ x_str2 }}</li>
            <li>x_str2 未轉義:{{ x_str2|safe }}</li>
            <li>x_str3 已轉義:{{ x_str3 }}</li>
            <li>x_str 未轉義3:{{ x_str3|safe }}</li>
        </ul>
    </div>
</div>

結論:

  • 加上safe,就像之前的mark_safe()包裹住標籤一樣,被認為是安全的,可以被瀏覽器渲染

其他過濾器(瞭解)

過濾器 描述 示例
upper 以大寫方式輸出 {{ user.name|upper }}
add 給value加上一個數值 {{ user.age|add:”5” }}
addslashes 單引號加上轉義號
capfirst 第一個字母大寫 {{ ‘good’|capfirst }} 返回”Good”
center 輸出指定長度的字串,把變數居中 {{ “abcd”|center:”50” }}
cut 刪除指定字串 {{ “You are not a Englishman”|cut:”not” }}
date 格式化日期
default 如果值不存在,則使用預設值代替 {{ value|default:”(N/A)” }}
default_if_none 如果值為None, 則使用預設值代替
dictsort 按某欄位排序,變數必須是一個dictionary {% for moment in moments|dictsort:”id” %}
dictsortreversed 按某欄位倒序排序,變數必須是dictionary
divisibleby 判斷是否可以被數字整除 {{ 224|divisibleby:2 }} 返回 True
escape 按HTML轉義,比如將”<”轉換為”&lt”
filesizeformat 增加數字的可讀性,轉換結果為13KB,89MB,3Bytes等 {{ 1024|filesizeformat }} 返回 1.0KB
first 返回列表的第1個元素,變數必須是一個列表
floatformat 轉換為指定精度的小數,預設保留1位小數 {{ 3.1415926|floatformat:3 }} 返回 3.142 四捨五入
get_digit 從個位數開始擷取指定位置的數字 {{ 123456|get_digit:’1’}}
join 用指定分隔符連線列表 {{ [‘abc’,’45’]|join:’*’ }} 返回 abc*45
length 返回列表中元素的個數或字串長度
length_is 檢查列表,字串長度是否符合指定的值 {{ ‘hello’|length_is:’3’ }}
linebreaks <p><br>標籤包裹變數 {{ “Hi\n\nDavid”|linebreaks }} 返回<p>Hi</p><p>David</p>
linebreaksbr <br/>標籤代替換行符
linenumbers 為變數中的每一行加上行號
ljust 輸出指定長度的字串,變數左對齊 {{‘ab’|ljust:5}}返回 ‘ab ’
lower 字串變小寫
make_list 將字串轉換為列表
pluralize 根據數字確定是否輸出英文複數符號
random 返回列表的隨機一項
removetags 刪除字串中指定的HTML標記 {{value|removetags: “h1 h2”}}
rjust 輸出指定長度的字串,變數右對齊
slice 切片操作, 返回列表 {{[3,9,1]|slice:’:2’}} 返回 [3,9]
{{ 'asdikfjhihgie'|slice:':5' }} 返回 ‘asdik’
slugify 在字串中留下減號和下劃線,其它符號刪除,空格用減號替換 {{ '5-2=3and5 2=3'|slugify }} 返回 5-23and5-23
stringformat 字串格式化,語法同python
time 返回日期的時間部分
timesince 以“到現在為止過了多長時間”顯示時間變數 結果可能為 45days, 3 hours
timeuntil 以“從現在開始到時間變數”還有多長時間顯示時間變數
title 每個單詞首字母大寫
truncatewords 將字串轉換為省略表達方式 {{ 'This is a pen'|truncatewords:2 }}返回``This is ...
truncatewords_html 同上,但保留其中的HTML標籤 {{ '<p>This is a pen</p>'|truncatewords:2 }}返回``<p>This is ...</p>
urlencode 將字串中的特殊字元轉換為url兼容表達方式 {{ ‘http://www.xuexianqi.top/archives/136.html’|urlencode}}
urlize 將變數字串中的url由純文字變為連結
wordcount 返回變數字串中的單詞數
yesno 將布林變數轉換為字串yes, no 或maybe {{ True|yesno }} 返回yes
{{ False|yesno }} 返回no
{{ None|yesno }} 返回maybe