2 Servlet ( tạo server và cấu hình project) - PhucVM2019/java-servlet GitHub Wiki

servlet

Tạo server dùng apache tomcat trên eclipse

  • Dowload tomcat tại link
  • Giải nén thư mục vừa dowload vào 1 thư mục nào đấy trong ổ C or D tùy thích ✌️
  • mở Eclipse chọn Window/References -> Runtime Evinroments chọn Add chọn server tương ứng với file tomcat vừa tải, chọn đến thư mục chưa file tomcat vừa giải nén, add là xong 💃

Để add server cho project (sau khi tạo project)

  • Click chuột phải chọn Properties -> Java buil Part -> Libraries ->Maven Dependencies --> Add Libries -> Server Runtime -> tomcat vừa tạo (Xong)

Tạo project sử dụng maven

-sau khi tạo xong project sẽ có lỗi vì chưa có file WEB_INF/web.xml

1.Right click on Deployment Descriptor in Project Explorer.

2.Select Generate Deployment Descriptor Stub

==>It will generate WEB-INF folder in src/main/webapp and an web.xml in it.

sau khi tạo xong cấu hình cho project sử dụng dc java 8

<properties>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.source>1.8</maven.compiler.source>
  </properties>
  • thêm 1 đoạn này nữa
<build>
     <plugins>
          <plugin>
               <groupId>org.apache.maven.plugins</groupId>
               <artifactId>maven-compiler-plugin</artifactId>
               <version>3.6.1</version>
               <configuration>
                   <source>1.8</source>
                   <target>1.8</target>
              </configuration>
          </plugin>
     </plugins>
</build>

có 2 đoạn trên thì elipse biên dịch sẽ chạy dc trên jdk 8

Xây dựng project theo MVC

  • tạo thư mục WEB_INF 👍 xem thêm
  • trong thư mục webapp tạo 1 thư mục WEB-INF trong thư mục WEB-INF tạo 1 file web.xml đồng thời trong webapp tạo 1 folder views
  • trong web.xml chi tiết tham khảo thêm tại
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
	      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	      version="3.0">
  <display-name>tên dự án</display-name>

  <welcome-file-list>  
     <welcome-file>index.jsp</welcome-file>  
     <welcome-file>default.html</welcome-file>  
  </welcome-file-list> 
</web-app>
  • trong thư mục web-app tạo 1 file jsp có tên là index.jsp
  • đoạn <welcome-file-list> được thêm trong web-app mục đích là những file mặc định sẽ chạy đầu tiên khi start project ở đây là file index.jsp hoặc file default.html (chỉ cần 1 trong 2)
  • khi làm việc với servlet thì luôn làm việc với 2 library luôn luôn phải có là jsp api servlet API. Để maven có thể dowload về thì cần có
  <dependencies>
    <!-- https://mvnrepository.com/artifact/javax.servlet/jsp-api -->
    <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>jsp-api</artifactId>
          <version>2.0</version>
          <scope>provided</scope>
      </dependency>
     <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
     <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
    </dependency>

     <!-- https://mvnrepository.com/artifact/jstl/jstl -->
     <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
     </dependency>
     <!-- https://mvnrepository.com/artifact/opensymphony/sitemesh -->
		<dependency>
			<groupId>opensymphony</groupId>
			<artifactId>sitemesh</artifactId>
			<version>2.4.2</version>
		</dependency>
   </dependencies>

trong properties có thể tự định nghĩa các version của các thư viện rồi gọi lại trong thư viện bằng ${định nghĩa version}

tạo controller

tạo 1 packages com.phucvm.controller (tenmien.domain.controller) chú ý phân biệt controller cho user và cho admin nếu thiết kế 2 phần này trên cùng 1 project 👍 (com.phucvm.controller.user && com.phucvm.controller.admin) xong tạo class có tên HomeController để sử dụng được HomeController thì cần extends HttpServlet (xem thêm tại)

  • thay vì dùng servlet-mapping trong file web.xml để có thể định nghĩa và gọi được controller. Thì có thể dùng Annotation khá là đơn giản đấy là @WebServlet (chi tiết)
  • trong controller tạo doGetdoPost

chú ý : @WebServlet chỉ dùng được khi javax.servlet-apiversion 3.0.x trở lên

@WebServlet(urlPatterns = {"/trang-chu"})
public class HomeController extends HttpServlet{
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}
}

Tạo View

trong thư mục webapp/views tạo file home.jsp trong jsp có 1 library là jstl để có thể sử dụng jstl cần import thư viện (thư viện import jstl) trong file thư mục webap/index.jsp thêm

<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %> 
<c:redirect url = "/trang-chu"/>
  • trong servlet để có thể trả về view thì cần làm quen với RequestDispatcher trong doGet của HomController
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
   RequestDispatcher rd = req.getDispatcher("/views/home.jsp");
   rd.forward(req, resp);
}

ghép giao diện

  • Sử dụng sitemesh decorator (link chi tiết) để phân chia view thành các Partial View

trong WEB-INF tạo 1 file decorators.xml

<?xml version="1.0" encoding="UTF-8"?>
<decorators defaultdir="/decorators">
    <!-- Any urls that are excluded will never be decorated by Sitemesh -->
    <excludes>
        <pattern>/api*</pattern>
    </excludes>
    
    <!-- apply Sitemesh default template -->
    <decorator name="admin" page="admin.jsp">
        <pattern>/admin*</pattern>
    </decorator>
    
    <decorator name="web" page="web.jsp">
        <pattern>/*</pattern>
    </decorator>
    
    <decorator name="login" page="login.jsp">
        <pattern>/dang-nhap</pattern>
    </decorator>
</decorators>

decorators để định nghĩa và phân chia bố cục website theo partial view như trong asp.net :)

  • trong thư mục tạo 1 thư mục decorators trong webapp/decorators, tạo 2 file web.jspadmin.jsp thì đây là 2 trang master layout tạo 1 folder decorators nằm trong webapp/decorators (là trang master layout của user) có sử dụng
<%@ taglib prefix="decorator" uri="http://www.opensymphony.com/sitemesh/decorator" %> <!--decorator : dùng để quy định gọi trong masterPage-->

là thư viện của decorators tương tự như jstl và để sử dụng định nghĩa body thì dùng có pháp

   <decorator:body />   <!--decoratorlà biến khai báo trong taglib prefix="decorator"-->

cú pháp trên để website có thể hiểu nơi nào được định nghĩa <decorator:body /> thì nơi đó nội dung sẽ được thay đổi theo các trang, còn các trang có phần giống nhau thì được <%@include file=" " %>

  • các trang partial view được tạo : trong common tạo thư mục partial (common/partial) trong đó tạo các partial dùng chung. để **decorator **có thể hiểu được website đang đc chạy vào url nào thì trong web.xml cần thêm đoạn sau
	<filter>
		<filter-name>sitemesh</filter-name>
		<filter-class>com.opensymphony.module.sitemesh.filter.PageFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>sitemesh</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
  • các trang có view thay đổi được tạo trong webapp/views (vidu:webapp/views/home.jsp)

Như vậy là đã có thể chạy 1 project cơ bản và có thể in ra hello world 💯

để build project thì cần chạy mvn clean install trong terminal (click chuột phải project chọn show in local terminal)

Tiếp theo để tương tác được với model

tạo model com.phucvm.modal (tenmien.domain.controller) và tạo 1 class News

package common.phucvm.model;

import java.sql.Timestamp;

public class News {
	private long id;
	private long id_category;
	private String title;
	private String description;
	private String content;
	private long id_user;
	private int status;
	private Timestamp createddate;
	private Timestamp modifieddate;
	private Timestamp createdby;
	private Timestamp modifiedby;
	
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public long getId_category() {
		return id_category;
	}
	public void setId_category(long id_category) {
		this.id_category = id_category;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public long getId_user() {
		return id_user;
	}
	public void setId_user(long id_user) {
		this.id_user = id_user;
	}
	public int getStatus() {
		return status;
	}
	public void setStatus(int status) {
		this.status = status;
	}
	public Timestamp getCreateddate() {
		return createddate;
	}
	public void setCreateddate(Timestamp createddate) {
		this.createddate = createddate;
	}
	public Timestamp getModifieddate() {
		return modifieddate;
	}
	public void setModifieddate(Timestamp modifieddate) {
		this.modifieddate = modifieddate;
	}
	public Timestamp getCreatedby() {
		return createdby;
	}
	public void setCreatedby(Timestamp createdby) {
		this.createdby = createdby;
	}
	public Timestamp getModifiedby() {
		return modifiedby;
	}
	public void setModifiedby(Timestamp modifiedby) {
		this.modifiedby = modifiedby;
	}
}

để controller có thể tương tác được với model

@WebServlet(urlPatterns = {"/trang-chu"}
public class HomeController extends HttpServlet{
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        UserModel UserModel  = new UserModel();
        UserModel.setFullName("hello Phuc");
        request.setAttribute("model", UserModel);
        RequestDispatcher rd = req.getDispatcher("/views/home.jsp");
        rd.forward(req, resp);
    }
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}
}

trong request.setAttribute("model", UserModel); model ở đây là biến trả kết quả ra view phía view để lấy ra được kết quả chúng ta vẫn sử dụng jstl. Trong file home.jsp

<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %> 
<!DOCTYPE html>
<html>
   <head>
   <meta charset="UTF-8">
   <title>Trang chủ</title>
   </head>
   <body>
      <p>${model.fullName}</p>
   </body>
</html>

Tạo file dùng chung chứa các thư viện hay dùng cho view

Để xử lý những phần hay dùng trong view ví dụ: <%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %> thì ta nên tạo 1 thư mục webapp/common/taglib.jsp trong taglib.jsp chứa tất cả các thư viện dùng chung

<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
...

ở đâu có sử dụng chỉ cần include taglib vào bằng cú pháp sau

<%@include file="common/taglib.jsp" %>

Basic nhất để tương tác với model 👍

_note : để nhúng link file js hay css trong jsp _

<link rel="stylesheet" type="text/css" href="<c:url value='_link file_' ">
<script type="text/javascript" src="<c:url value='_link file_'"></script>

Tạo tầng DAO

project sẽ chia theo 3 tầng
    -Presentation layer (MVC| controller, model, view)
    -business Logic    : tầng sử lý logic
    -data access layer (DAO): kết nối trực tiếp với csdl 

tạo packages cho các tầng sử lý logic(business Logic) có tên com.phucvm.service và tầng Dao(data access layer) com.phucvm.dao

Trong tầng Dao tạo 1 packages com.phucvm.dao.impl

  • trong com.phucvm.dao tạo các interface có tên bắt đầu bằng i, vidu : iUserName
  • trong com.phucvm.dao.impl tạo tầng dao UserName implements iUserName**
  • mục đích của tạo interface dựa vào cái này Dependency inversion principle
  • Trong jdbc thì kết quả trả về là 1 đối tượng Result Sets

Trong tầng service tạo interface có tên bắt đầu bằng i +name + service vidu: iUserNameService

Tạo packages trong com.phucvm.service.impl cũng implements iUserNameService xong cấu trúc đơn giản theo đúng mô hình 3 tầng

  • Lý do phải có 1 lớp interFace riêng vì code theo chuẩn Dependency injection đọc thử

  • tạo 1 tầng Service(Xử lý logic) có nhiệm vụ return tầng DAO

  • Controller chỉ làm nhiệm vụ duy nhất : trả về view và nó return model (Data) còn model data lấy từ tầng service(tầng logic).

Để maven có thể dowload thư viện JDB thì cần có thư viện JDBC trên máy trước, không như sql hay mysql chỉ cần coppy vào maven là có thể dowload thì orcl phải dowload về local chạy rồi mới có thể dùng nếu không sẽ bị lỗi

xem thêm tại

mvn install:install-file -Dfile=d:/PhucVM/DOS/ojdbc6.jar -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=11.2.0.4 -Dpackaging=jar
⚠️ **GitHub.com Fallback** ⚠️