後端如何向前端返回資料
一、使用jquery發給控制器資料,經處理後返回JSON資料
<!DOCTYPE html>
<
html
>
<
head
>
<
meta
charset
=
“UTF-8”
>
<
title
>
查詢頁面
title
>
<
script
src
=
“/jquery_2_1。min。js”
>
script
>
head
>
<
body
>
<
form
id
=
“form-query”
>
姓名:
<
input
type
=
“text”
name
=
“xm”
><
br
>
聯絡電話:
<
input
type
=
“text”
name
=
“lxdh”
><
br
>
<
input
id
=
“btn-query”
type
=
“button”
value
=
“查詢”
/>
form
>
<
div
id
=
“listdata”
>
div
>
<
script
type
=
“text/javascript”
>
$
(
“#btn-query”
)。
click
(
function
() {
$
。
ajax
({
url
:
“/querytxl”
,
type
:
“get”
,
data
:
$
(
“#form-query”
)。
serialize
(),
dataType
:
“json”
,
success
:
function
(
data
) {
var
s
=
“”
;
for
(
var
i
=
0
,
l
=
data
。
length
;
i
<
l
;
i
++
) {
for
(
var
key
in
data
[
i
]) {
s
+=
data
[
i
][
key
]
+
‘,’
;
}
s
=
s
+
“
”
;
$
(
“#listdata”
)。
html
(
s
);
}
}
});
});
script
>
body
>
html
>
Controller
//查詢資料返回JSON
@ResponseBody
@GetMapping
(
“/querytxl”
)
public
List
<
Txl
>
getSelect
(
Txl
txl
) {
System
。
out
。
println
(
txl
);
List
<
Txl
>
txls
=
txlService
。
getSelect
(
txl
);
return
txls
;
}
2、使用Controller,定位到模板引擎的查詢頁面,控制器處理後再次顯示到模板頁面
// 定位到查詢頁面
@GetMapping
(
“/txlcx”
)
public
String
toQueryPage
() {
return
“txlquery”
;
}
查詢頁面,傳送給控制器
<!DOCTYPE html>
<
html
xmlns:th
=
“http://www。thymeleaf。org”
>
<
head
>
<
meta
charset
=
“UTF-8”
>
<
title
>
Insert title here
title
>
<
style
type
=
“text/css”
>
table
{
font
:
“宋體”
11px
;
color
:
#333333
;
text-align
:
center
;
border-collapse
:
collapse
;
}
table
td
{
border
:
1px
solid
#000
;
}
style
>
head
>
<
body
>
<
form
th:action
=
“@{/txlquery}”
method
=
“get”
>
姓名:
<
input
type
=
“text”
name
=
“xm”
><
br
/>
聯絡電話:
<
input
type
=
“text”
name
=
“lxdh”
><
br
/>
<
input
id
=
“btn-query”
type
=
“submit”
value
=
“查詢”
/>
form
>
<
div
>
<
table
>
<
tr
>
<
td
>
id
td
>
<
td
>
姓名
td
>
<
td
>
聯絡電話
td
>
<
td
>
出生日期
td
>
tr
>
<
tr
th:each
=
“txl:${txls}”
>
<
td
th:text
=
“${txl。id}”
>
td
>
<
td
th:text
=
“${txl。xm}”
>
td
>
<
td
th:text
=
“${txl。lxdh}”
>
td
>
<
td
th:text
=
“${#dates。format(txl。csrq,‘yyyy-MM-dd’)}”
>
td
>
tr
>
table
>
div
>
body
>
html
>
Controller
// 給前臺傳查詢資料
@GetMapping
(
“/txlquery”
)
public
String
queString
(
Model
model
,
Txl
txl
) {
List
<
Txl
>
txls
=
txlService
。
getSelect
(
txl
);
model
。
addAttribute
(
“txls”
,
txls
);
return
“txlquery”
;
}
3、以上兩種方式,都使用相同的mapper和servcice
<
select
id
=
“getSelect”
resultType
=
“com。gl。model。Txl”
parameterType
=
“com。gl。model。Txl”
>
select * from txl
<
where
>
<
if
test
=
“xm!=null”
>
xm like concat(‘%’,#{xm},‘%’)
if
>
<
if
test
=
“lxdh!=null”
>
AND lxdh like concat(‘%’,#{lxdh},‘%’)
if
>
where
>
select
>
這是一個動態SQL
// 根據條件查詢
public
List
<
Txl
>
getSelect
(
Txl
txl
) {
return
txlMapper
。
getSelect
(
txl
);
}
Service