บทที่ 4 spring web application database connection mysql web app action.pdf ·...

12
44 บทที4 Spring Web Application Database Connection การเชื่อมต่อกับฐานข้อมูลโดยใช้ spring นั ้นจาเป็นต ้องเพิ่ม dependency สาหรับการเชื่อมต่อระบบ ฐานข้อมูล ในตัวอย่างนี ้จะใช้ระบบฐานข้อมูล MySQL ดังนั ้นจาเป็นต ้องเพิ่ม mysql-connector java เข้า มาก่อนเป็นอันดับแรก สร้างคลาสสาหรับจัดการติดต่อกับฐานข้อมูลโดยสร้าง Package ชื่อว่า com.springmvc.model และตั ้ง ชื่อคลาสว่า DatabaseConnection package com.springmvc.model; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DatabaseConnection { Connection conn; String url = "jdbc:mysql://localhost:3306/EmployeeDB? characterEncoding=UTF-8"; String uname = "root"; String pwd = "itmju";

Upload: others

Post on 21-Jun-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: บทที่ 4 Spring Web Application Database Connection MySQL Web App Action.pdf · สร้างคลาสสาหรับจัดการติดต่อกับฐานข้อมูลโดยสร้าง

44

บทท 4 Spring Web Application Database Connection

การเชอมตอกบฐานขอมลโดยใช spring นนจ าเปนตองเพม dependency ส าหรบการเชอมตอระบบฐานขอมล ในตวอยางนจะใชระบบฐานขอมล MySQL ดงนนจ าเปนตองเพม mysql-connector java เขามากอนเปนอนดบแรก

สรางคลาสส าหรบจดการตดตอกบฐานขอมลโดยสราง Package ชอวา com.springmvc.model และตงชอคลาสวา DatabaseConnection

package com.springmvc.model;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

public class DatabaseConnection {

Connection conn;

String url = "jdbc:mysql://localhost:3306/EmployeeDB?

characterEncoding=UTF-8";

String uname = "root";

String pwd = "itmju";

Page 2: บทที่ 4 Spring Web Application Database Connection MySQL Web App Action.pdf · สร้างคลาสสาหรับจัดการติดต่อกับฐานข้อมูลโดยสร้าง

45

public Connection getConnection(){

conn = null;

try{

Class.forName("com.mysql.jdbc.Driver");

conn = DriverManager.

getConnection(url,uname,pwd);

}catch(ClassNotFoundException ex){

ex.printStackTrace();

}catch(SQLException ex){

ex.printStackTrace();

}

return conn;

}

public void closeConnection() {

try {

conn.close();

}catch(Exception ex) {

ex.printStackTrace();

}

}

}

สรางหนาจอ login ทประกอบไปดวย username, password และ ปม submit โดยก าหนดให action ไปท

"/login" ดวย method=post

<%@ page language="java" contentType="text/html; charset=ISO-

8859-1" pageEncoding="ISO-8859-1"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01

Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html;

charset=ISO-8859-1">

<title>Login Page</title>

</head>

<body>

<form action="${pageContext.request.contextPath}/login"

method="post">

username : <input type="text" name="uname"> <br>

password : <input type="password" name="pwd"> <br>

<input type="submit" value="login">

<input type="reset">

</form>

</body>

</html>

Page 3: บทที่ 4 Spring Web Application Database Connection MySQL Web App Action.pdf · สร้างคลาสสาหรับจัดการติดต่อกับฐานข้อมูลโดยสร้าง

46

สรางคลาส LoginBean ส าหรบเกบขอมลทรบคามาจากหนาจอ login.jsp

package com.springmvc.model;

public class LoginBean {

private String username;

private String password;

public LoginBean() {

super();

}

public LoginBean(String username, String password) {

super();

this.username = username;

this.password = password;

}

public String getUsername() {

return username;

}

public void setUsername(String username) {

this.username = username;

}

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

}

Page 4: บทที่ 4 Spring Web Application Database Connection MySQL Web App Action.pdf · สร้างคลาสสาหรับจัดการติดต่อกับฐานข้อมูลโดยสร้าง

47

สรางคลาส LoginManager ส าหรบน า username และ password เขาไปคนหาในฐานขอมล ซงจะคนคาการเขาสระบบหาก username และ password ตรงกบขอมลในฐานขอมล ตาราง Login

package com.springmvc.controller;

import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import com.springmvc.model.DatabaseConnection;

import com.springmvc.model.LoginBean;

public class LoginManager {

public String do_login_process(LoginBean login) {

DatabaseConnection dbcon = new DatabaseConnection();

Connection conn = dbcon.getConnection();

Statement stmt = null;

ResultSet rs = null;

try{

String sql = "select count(username) from " +

"Login where username = '" +

login.getUsername() +

"' and password = '" +

login.getPassword() + "'";

stmt = conn.createStatement();

rs = stmt.executeQuery(sql);

int count = 0;

if (rs.next()){

count = rs.getInt(1);

}

if (count == 1) {

return "login success";

}else {

return "username or password does't match";

}

}catch(Exception ex){

return "Login error, please try again!!";

}finally{

try {

rs.close();

stmt.close();

conn.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}

}

Page 5: บทที่ 4 Spring Web Application Database Connection MySQL Web App Action.pdf · สร้างคลาสสาหรับจัดการติดต่อกับฐานข้อมูลโดยสร้าง

48

ในสวนของ Login_Controller เพมเมธอดส าหรบจดการกบการรบคาจากหนาจอ login.jsp โดยเพม เมธอด do_login โดยสงพารามเตอร HttpServletRequest และ Model และก าหนด Annotation ส าหรบ RequestMapping เมอมการเรยกใชดวยเมธอด POST

@RequestMapping(value="/login", method=RequestMethod.POST)

public String do_login(HttpServletRequest request, Model md){ try {

String uname = request.getParameter("uname"); String pwd = request.getParameter("pwd"); LoginBean login = new LoginBean(uname,pwd); LoginManager lmg = new LoginManager(); String message = lmg.do_login_process(login); if (message.equals("login success")) { md.addAttribute("emp_username",login.getUsername()); return "myprofile";

}else{ md.addAttribute("error_msg", message);

} return "login"; }catch(Exception ex) {

return "login"; }

}

หากมการ login ผานจะใหไปแสดงผลทหนา myprofile.jsp โดยสงคา username ไปพรอมกบคลาส Model หาก login ไมผานจะใหไปแสดงผลทหนา login.jsp โดยสงคา message ไปแสดงผลทหนาจอ login.jsp เพอแจงใหกบผใชวาไมสามารถ login ไดดวยเหตผลใด

หนาจอ login.jsp มการเพม label ส าหรบแสดงผล message ทไดรบจากผลการ login ดงน

<body>

<label style="color:red;">${error_msg}</label>

<form action="${pageContext.request.contextPath}/login"

method="post">

username : <input type="text" name="uname"> <br>

password : <input type="password" name="pwd"> <br>

<input type="submit" value="login">

<input type="reset">

</form>

</body>

Page 6: บทที่ 4 Spring Web Application Database Connection MySQL Web App Action.pdf · สร้างคลาสสาหรับจัดการติดต่อกับฐานข้อมูลโดยสร้าง

49

หนาจอ myprofile.jsp มการน าคา username มาแสดงผลดงน

<%@ page language="java" contentType="text/html; charset=ISO-

8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01

Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html;

charset=ISO-8859-1">

<title>My Profile</title>

</head>

<body>

My Profile </br>

=================== </br>

Hello <label>${emp_username}</label>

</body>

</html>

Page 7: บทที่ 4 Spring Web Application Database Connection MySQL Web App Action.pdf · สร้างคลาสสาหรับจัดการติดต่อกับฐานข้อมูลโดยสร้าง

50

กรณทตองการสงคาไปท myprofile.jsp สามารถใชรปแบบของ Session เขามาจดการไดเชนกน โดยการประกาศพารามเตอร HttpSession ในเมธอด do_login และท าการก าหนดคาตวแปรทตองการจดเกบขอมลไวใน Session โดยใชค าสง setAttribute(key, value) ดงน

@RequestMapping(value="/login", method=RequestMethod.POST)

public String do_login(HttpServletRequest request,

Model md, HttpSession session){

try {

//System.out.println("login post has been called");

String uname = request.getParameter("uname");

String pwd = request.getParameter("pwd");

LoginBean login = new LoginBean(uname,pwd);

LoginManager lmg = new LoginManager();

String message = lmg.do_login_process(login);

if (message.equals("login success")) {

session.setAttribute("emp_username",

login.getUsername());

return "myprofile";

}else{

md.addAttribute("error_msg", message);

}

return "login";

}catch(Exception ex) {

return "login";

}

}

จากน น เพ มคลาส MyProfileController เพ อจดการกบ url ท เ ร ยกใช /myprofile โดยก าหนด

MappingRequest ดวย เมธอด GET ต ง ชอ เมธอด loadProfilePage โดยก าหนดพาราม เตอร เ ปน HttpSession ซงดงน

package com.springmvc.controller;

import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.servlet.ModelAndView;

public class MyProfileController {

@RequestMapping(value="/myprofile",

method=RequestMethod.GET)

Page 8: บทที่ 4 Spring Web Application Database Connection MySQL Web App Action.pdf · สร้างคลาสสาหรับจัดการติดต่อกับฐานข้อมูลโดยสร้าง

51

public ModelAndView loadProfilePage(HttpSession session){

ModelAndView mav = new ModelAndView("myprofile"); String uname =(String)session.getAttribute("emp_username");

mav.addObject("emp_username", uname); return mav; }

}

สวนของการจดการกบระบบฐานขอมลในตวอยางถดไปจะเปนการเพมขอมลลงในระบบฐานขอมลโดยจะยกตวอยางดวยระบบการลงทะเบยน Sign Up โดยเรมแรกใหท าการเพม Link ในหนา index.jsp ส าหรบเปดไปยงหนาจอเพอท าการลงทะเบยนผใช

<body>

My First Spring Web App <br><br>

<a href="${pageContext.request.contextPath}/login">

Login</a><br>

<a href="${pageContext.request.contextPath}/register">

Register</a><br>

</body>

จากนนสราง register.jsp และสราง Controller ส าหรบจดการการลงทะเบยน

package com.springmvc.controller;

import org.springframework.stereotype.Controller;

import

org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

@Controller

public class RegisterController {

@RequestMapping(value="/register",

method=RequestMethod.GET)

public String loadRegisterPage(){

return "register";

}

}

Page 9: บทที่ 4 Spring Web Application Database Connection MySQL Web App Action.pdf · สร้างคลาสสาหรับจัดการติดต่อกับฐานข้อมูลโดยสร้าง

52

ในสวนของหนาจอ register.jsp ก าหนดขอมลทจะรบคาเขาไปและก าหนด Form Action เมอมการกดปมลงทะเบยน ในกรณท มการ upload file จ า เ ปนตองก าหนดรปแบบการเขารหส enctype= “multipart/form-data”

<body>

<form name="frm" method="post"

enctype="multipart/form-data"

action="${pageContext.request.contextPath}/register">

Username : <input type="text" name="txtuname"></br>

Password : <input type="password" name="txtpwd"></br>

FullName : <input type="text" name="txtfullname"></br>

Gender : <input type="radio" name="rdoGender"

value="M"> male

<input type="radio" name="rdoGender"

value="F"> female</br>

Upload : <input type="file" name="profile_pic">

</br></br>

<input type="submit" value="Register">

</form>

</body>

เมอมการ upload file จ าเปนตองเพม Library ส าหรบจดการไฟลตาง ๆ โดยจะตองเพม Dependency เขาไปอก 1 ตวคอ commons-fileupload ใน pom.xml

<dependency>

<groupId>commons-fileupload</groupId>

<artifactId>commons-fileupload</artifactId>

<version>1.3.2</version>

</dependency>

Page 10: บทที่ 4 Spring Web Application Database Connection MySQL Web App Action.pdf · สร้างคลาสสาหรับจัดการติดต่อกับฐานข้อมูลโดยสร้าง

53

ในสวนของ LoginBean ก าหนดใหเพมแอททรบวสเขาไปอก 3 รายการดงน จากนนเพมเมธอด Setter, Getter และ Constructor ส าหรบคลาส LoginBean

public class LoginBean {

private String username;

private String password;

private String fullname;

private String gender;

private String image;

...

}

ในสวนของ RegisterController สรางเมธอดส าหรบการรบคาลงทะเบยนจากหนาจอ โดยต งชอวา do_register ดงน

@RequestMapping(value="/register", method=RequestMethod.POST)

public ModelAndView do_register(HttpServletRequest

request) {

String message = "";

ModelAndView mav = new ModelAndView("register");

if (ServletFileUpload.isMultipartContent(request)) {

try {

List<FileItem> data = new ServletFileUpload(

new DiskFileItemFactory())

.parseRequest(request);

String uname = data.get(0).getString();

String pwd = data.get(1).getString();

String fullname = data.get(2).getString();

String gender = data.get(3).getString();

String image = new File(data.get(4).getName())

.getName();

LoginBean login =

new LoginBean(uname,pwd,fullname,gender,image);

RegisterManager rm = new RegisterManager();

message = rm.doSignUp(login);

String path = request.getSession()

.getServletContext().getRealPath("/") +

"//WEB-INF//images//";

data.get(4).write(new File(path +

File.separator + image));

Page 11: บทที่ 4 Spring Web Application Database Connection MySQL Web App Action.pdf · สร้างคลาสสาหรับจัดการติดต่อกับฐานข้อมูลโดยสร้าง

54

} catch (Exception e) {

e.printStackTrace();

message = "Please try again....";

}

}

mav.addObject("message", message);

return mav;

}

สวนของ RegisterManager ส าหรบตดตอกบฐานขอมล โดยการเพมเมธอดส าหรบเพมขอมลลงใน

ตาราง Login ดงน

package com.springmvc.controller;

import java.sql.Connection;

import java.sql.Statement;

import com.springmvc.model.DatabaseConnection;

import com.springmvc.model.LoginBean;

public class RegisterManager {

public String doSignUp(LoginBean login)

{

try{ DatabaseConnection dbcon = new DatabaseConnection();

Connection conn = dbcon.getConnection();

Statement statment = conn.createStatement();

statment.execute("insert into login values('" + login.getUsername()+"','"+login.getPassword()+

"','" + login.getFullname() + "','" + login.getGender()+"','"+login.getImage()+"')");

conn.close();

return "Register Successfully...";

}catch(Exception e){ System.out.println(e);

return "Something went wrong please try again!!!";

} }

}

Page 12: บทที่ 4 Spring Web Application Database Connection MySQL Web App Action.pdf · สร้างคลาสสาหรับจัดการติดต่อกับฐานข้อมูลโดยสร้าง

55

เพม Label ส าหรบแสดงผลลพธจากการเพมขอมล ในหนาจอ register.jsp

<body>

<label>${message}</label>

<form name="frm" method="post" enctype="multipart/form-data" action="${pageContext.request.contextPath}/register" > Username : <input type="text" name="txtuname"></br> Password : <input type="password" name="txtpwd"></br> FullName : <input type="text" name="txtfullname"></br> Gender : <input type="radio" name="rdoGender" value="M">

male <input type="radio" name="rdoGender" value="F">

female</br>

Upload : <input type="file" name="profile_pic"> </br> </br> <input type="submit" value="Register"> </form>

</body>