Upload
others
View
4
Download
0
Embed Size (px)
Citation preview
1
ธระยทธ ทองเครอ
ภาควชาวทยาการคอมพวเตอร คณะวทยาศาสตร
มหาวทยาลยขอนแกน
บทท 5
MVC
(Model-View-Controller)
สถาปตยกรรม MVCMVC คอ รปแบบการสรางแอปพลเคชนทแบงสวนการท างานออกเปน 3 สวน
Controller ตวกลางในการรบ-สงขอมลระหวางสวน View และสวน Model Model ประมวลผล Business Logic เชน การประมวลผลกบฐานขอมล ปรบปรง
แกไข เพม หรอดงขอมล ผลลพธจาก Model มกจะเปนขอมลทจะสงไปใหสวน View แสดงผล
View คอ ชดค าสงส าหรบ Render หนา Interface กบผใช โดยใชขอมลจาก Model
เปาหมายของ MVC การแบงสวนการท างานของระบบอยางชดเจน งายตอการท างานเปนทม งายตอการ maintenance ในอนาคต
2
3
Controller(Servlet)
DatabaseView(JSP)
Model(DAO &
JavaBeans)
Client
Server
JavaBeans
Request
JavaBeans
สถาปตยกรรม MVC
1
2
34
567
Spring MVC
Framework ทใชสรางเวบแอปพลเคชน โดยแยกสวนระหวางชน model และชน view เพอให front-end developer และ back-end developer สามารถท างานไปพรอม ๆ กนได
ท างานอยบน Spring Boot ซงเปน Application หนงทชวยใหประมวลผลแอปพลเคชนตามกรอบของ Spring Framework ไดงาย มชด Starter Library ทรวบรวมชด Library ทเกยวของมาใหพรอมใช เชน
spring-boot-starter-web ใชส าหรบสรางเวบแอปพลเคชน ม Auto Configuration เพอลดขนตอนการก าหนดคาตางๆ ม Built-in web server เชน Tomcat
4
การสราง Project ทโปรแกรม Eclipse เลอกเมน File > New > Maven Project
5
ชอ Project
ชอองคกรก าหนดใหสรางโปรเจค
โดยไมใชแมแบบ
การ import template
6
1. คลกขวาทชอโปรเจคทสรางขน เลอก Import... และ เลอกไฟลแบบบบอด
2. น าเขาไฟล template ทโหลดจากhttps://dev.cs.kku.ac.th/jw/resource/spring-template.zip
3. เลอกทน
โครงสราง Project
7
โฟลเดอรส าหรบเกบคลาสจาวา
ควรสราง package ส าหรบเกบคลาสเสมอ
คลาสหลก Spring Boot Application
โฟลเดอรเกบไฟล css, js, html, รปภาพ
ไฟล Configuration เชน URL ของฐานขอมล
โฟลเดอรเกบไฟล jsp
ไฟลระบ library ทใชในโปรเจค
<project xmlns="…"><modelVersion>4.0.0</modelVersion><groupId>civilizedland</groupId><artifactId>firstspring</artifactId><version>0.0.1-SNAPSHOT</version>
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.0.5.RELEASE</version>
</parent>
<dependencies><dependency>
<groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency><groupId>org.apache.tomcat.embed</groupId><artifactId>tomcat-embed-jasper</artifactId><scope>provided</scope>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><optional>true</optional>
</dependency></dependencies>
</project>
ไฟล pom.xml
8
ก าหนด dependency เรมตนของ Spring Boot Application
ส าหรบพฒนา Web Application
ส าหรบการประมวลผล JSP
Developer Tools ชวย restart server อตโนมต เมอมการเปลยนแปลงโคด
กรณเกด Error: not up-to-date
หาก Save ไฟล pom.xml แลว Project ม Error ดงภาพ ใหคลกขวาท Project เลอกเมน Maven > Update Project…
แลวเลอกท “Force Update of Snapshots/Release” และกดปม OK
9
ไฟล application.properties
10
spring.mvc.view.prefix=/jsp/spring.mvc.view.suffix=.jsp
ระบโฟลเดอรทเกบไฟล jsp
ก าหนดใหอางถงไฟล jsp ไดโดยไมตองลงทายดวย .jsp
import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplicationpublic class MainApp {
public static void main(String[] args) {SpringApplication.run(MainApp.class, args);
}
}
คลาสหลกของ Spring Boot
11
สงใหคลาส MainApp เรมท างาน
คลาสหลกตองมเมธอด main( )
ก าหนดใหคลาสนเปนคลาสหลก
การรนจะเรมรนทคลาสน โดยรนแบบ Java Application ไมไดรนบน Serverเพราะ Spring Boot ม Tomcat Web Server ตดมาอยแลว
คลาส Controllerimport org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class FirstController {
@GetMapping("/")
public String welcome(Model model) {
model.addAttribute("message", "Civilized Land");
return "/home";
}
}
12
ระบวาใหคลาสนเปน Controller
ก าหนด Path ทใชเขาถงเมธอดนแบบ GET
ก าหนดชอไฟล jsp ทจะสงไปแสดงผล
ตวแปร model ส าหรบบรรจขอมลเพอใชแสดงผลในหนา jsp
สราง attribute ชอ message ใหเกบสตรง "Civilized Land"
home.jsp
13
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" %>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<h1>Welcome to ${message}</h1>
<img src="green.jpg" width="600">
</body>
</html>
ดงคา attribute ชอ message จากController ออกมาแสดงผล
การรน Spring Boot Applicationคลกขวาทคลาสหลก (MainApp) เลอก Run As > Java Application
14
ตวอยาง
15
การรบขอมลของ Controller รบผาน URL Parameter ใช @RequestParam ก ากบ
http://localhost:8080/search?name=jim&age=20
รบผาน Path ใช @PathVariable ก ากบhttp://localhost:8080/customer/10/jim
16
@GetMapping("/search")String add(@RequestParam("name") String name, @RequestParam("age") Integer age, Model model) {
System.out.println("name=" + name);System.out.println("age=" + age);return "/home";
}
@GetMapping("/customer/{id}/{cname}")String check(@PathVariable("id") String cid, @PathVariable("cname") String name, Model model) {
System.out.println("id=" + cid);System.out.println("cname=" + name);return "/home";
}
การรบขอมลเกบลง JavaBeans
17
@Controllerpublic class TestController {
@GetMapping("/computeArea")public String computeArea(@ModelAttribute Triangle t, Model model) {
float area = (float)0.5 * t.getBase() * t.getHeight();model.addAttribute("area", area);return "triangle-area";
}}
triangle-area.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%><html><head><meta charset="utf-8"></head><body><b>พนทสามเหลยม คอ ${area}</b></body></html>
JavaBeanspublic class Triangle {
private float base;private float height;public float getBase() {
return base;}public void setBase(float base) {
this.base = base;}public float getHeight() {
return height;}public void setHeight(float height) {
this.height = height;}
}
ก าหนดชอใน URL Parameter ทมชอเดยวกบตวแปรใน JavaBean
ใช @ModelAttribute และก ำหนดตวแปร JavaBeans ทตองกำรใชเกบขอมลจำก URL
ขอมลจำก URL จะถกเกบลงตวแปร t ทประกำศไว
รปแบบคลาส Controller
18
@Controller@RequestMapping("/ชอ path ของ controller")public class XxxxxController {
@GetMapping("/ชอ path เขาถงเมธอด")public String ชอเมธอดใดๆดได(@RequestParam("param1") String p1, ..., Model model) {
// เรยกเมธอดตางๆ จาก DAO/Repository// หรอประมวลผล Business Logic
model.addAttribute("ชอขอมลทจะสงไปยง view", ตวแปรทจะสงไปยง view);model.addAttribute("...", ...);model.addAttribute("...", ...);
return "ชอ jsp ทใช render สวน view โดยไมตองใสนามสกล";หรอ "redirect:/ชอ path ทจะสงตอ";
}
อาจไมใส annotation นกได
ระบ annotation เพอก าหนดใหคลาสนเปน Controller (คลาสทสามารถรบ request และสง response ได)
ดงขอมลจาก request parameter มาเกบในตวแปร จะมกตวกได
ก าหนด Model เปน parameter ทกครง เมอตองการบรรจขอมลส าหรบน าไปใชแสดงผลบน view
เกบ object ตางๆ ลงใน modelทตองการให Template Engine น าไปแสดงผล
เมธอด return คาเปน String
การก าหนดรปแบบการเขาถง Controller @RequestMapping ใชก าหนด path ในการรบ request ทกชนด เชน
@RequestMapping("/addcustomer") หรอ@RequestMapping(value="/addcustomer", method=RequestMethod.POST)
@GetMapping ใชก าหนด path ทรบ request แบบ GET เชน@GetMapping("/listProduct")
@PostMapping ใชก าหนด path ทรบ request แบบ POST เชน@PostMapping("/checkLogin")
@PutMapping ใชก าหนด path ทรบ request แบบ Put มกใชใน Web API @PutMapping("/updateUser")
@DeleteMapping ใชก าหนด path ทรบ request แบบ Delete มกใชใน Web API @DeleteMapping("/deleteUser")
19
กจกรรมจงสรางเวบส าหรบบวกเลขดวย Spring MVC โดยสง request ใหกบ Controller 2 คา
ไดแก a และ b หลงจากนนใหสวน Controller บวกคา และสงไปแสดงผลยงไฟล JSP
20
สงคาทาง URL
กจกรรมจงสรางเวบไซตส าหรบ Sign In เขาสระบบดวย Spring MVC ก าหนดให username
เปน “bobby” และ password เปน “1234” เปนขอมลทเขาสระบบได โดยสงผลการตรวจสอบไปแสดงผลทไฟล JSP
21
กรณ user และ password ถกตอง
กรณ user และ password ไมถกตอง
ระบบแนะน าเครองดม
22
ฟอรม HTML ทจะสงไปยง Controller
ผลลพธทสรางจาก View
ระบบแนะน าเครองดม
23
Controller(BeerController)
View(result.jsp)
Model(BeerExpert)
Client
Server
brands
HTTP Requestcolor=amber
brandscolor=amber
ฟอรมส าหรบสงขอมล (สง request)
24
<html><body><form action="/BeerSelector">
Select beer charateristics<br>Color: <select name="color">
<option value="light">light</option><option value="amber">amber</option><option value="brown">brown</option><option value="dark">dark</option>
</select><input type="submit">
</form></body></html>
ชอ Path ของ Controller ทใชรบคา
@Controllerpublic class DrinkingController {
@GetMapping("/BeerSelector")public String select(@RequestParam("color") String color, Model model) {
BeerExpert beerExpert = new BeerExpert();ArrayList<String> brands = beerExpert.getBrands(color);
model.addAttribute("brandList", brands);return "result";
}
}
สราง BeerExpert objectและสงสทผใชเลอกเพอขอขอมล
สวน Controller
25
น าผลลพธเกบไวใน model object พรอมกบระบชอ เพอใชอางองในสวน view
ดงขอมลจาก request parameter ชอ color มาเกบในตวแปร color
ชอไฟล jsp ทใช render เปนผลลพธ
ตวแปร model ใชส าหรบเกบขอมลเพอใชในสวน view ไมเกยวของกบสวน model ใน MVC
สวน Model
26
import java.util.ArrayList;
public class BeerExpert {
public ArrayList<String> getBrands(String color) {
ArrayList<String> brands = new ArrayList<String>();
if (color.equals("amber")) {brands.add("Singha");brands.add("Asahi");
} else {brands.add("Carlsberg");brands.add("Heineken");brands.add("Tiger");
}return brands;
}
}
สราง object ส าหรบเกบผลลพธ
ตรวจสอบเงอนไขเพอเกบขอมลลงใน object
เพมขอมล String ลงใน ArrayList object
สง ArrayList object กลบ
สวน View (result.jsp)
27
<%@ page import="java.util.ArrayList"%><html><body><h2>Beer Recommendation</h2><%ArrayList<?> brandList = (ArrayList<?>)request.getAttribute("brandList");
for(int i=0; i<brandList.size(); i++) {out.println(brandList.get(i) + "<br>");
}
%></body></html>
ดงผลลพธทก าหนดไวใน Controller
วนลปน า String จาก ArrayListมาสรางเปนผลลพธ HTML
เอกสารอางองBryan Basham, Kathy Sierra, and Bert Bates. Head First Servlets and JSP, 2nd
Edition, United States of America, O'Reilly Media, 2008.
28