Cho phép tùy chọn Giao diện trong Spring Web MVC framework

Công Nghệ
Cho phép tùy chọn Giao diện trong Spring Web MVC framework
Bài viết được sự cho phép của tác giả Trần Thị Thu Hà Để tăng độ hài lòng của khách truy cập, trang web có thêm tùy chọn Giao diện theo ý muốn của người dùng. Trong bài viết này, chúng mình sẽ chia sẻ với bạn cách xây dựng...

Bài viết được sự cho phép của tác giả Trần Thị Thu Hà

Để tăng độ hài lòng của khách truy cập, trang web có thêm tùy chọn Giao diện theo ý muốn của người dùng. Trong bài viết này, chúng mình sẽ chia sẻ với bạn cách xây dựng một ứng dụng Spring Web MVC như thế.

Bạn cần khởi tạo project bằng Maven archetype có tên maven-archetype-webapp, nếu bạn chưa rõ cách khởi tạo hãy xem bài viết Kỹ thuật Autowiring sử dụng annotation trong Spring Framework. Cấu trúc thư mục của ứng dụng sẽ như sau:

Cho phép tùy chọn Giao diện trong Spring Web MVC frameworkCho phép tùy chọn Giao diện trong Spring Web MVC framework

Chúng ta sẽ tạo 14 files mã nguồn bao gồm:

  1. JobController.java
  2. Job.java
  3. beach.properties
  4. classic.properties
  5. modern.properties
  6. beach.css
  7. classic.css
  8. modern.css
  9. addjob.jsp
  10. resultJob.jsp
  11. springmvc-servlet.xml
  12. web.xml
  13. index.jsp
  14. pom.xml

Sau khi Maven tự động tạo cho bạn một số thư mục có sẵn, bạn cần tạo thêm thư mục java, css, pages như trong ảnh chụp màn hình. Sửa lại file pom.xml có nội dung như sau:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>vn.smartjob.demospring</groupId>
<artifactId>themes-option</artifactId>
<packaging>war</packaging>
<version>1.0.0-SNAPSHOT</version>
<name>Spring Web MVC themes option</name>
<url>https://smartjob.vn</url>

<properties>
<spring.version>4.2.6.RELEASE</spring.version>
<junit.version>4.12</junit.version>
<hibernate.validator.version>5.2.4.Final</hibernate.validator.version>
</properties>

<developers>
<developer>
<name>Do Nhu Vy</name>
<email>vydn@dcv.vn</email>
</developer>
</developers>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate.validator.version}</version>
</dependency>
</dependencies>
<build>
<finalName>theme</finalName>
</build>
</project>

Ứng dụng Spring Web MVC cần tối thiểu các dependencies là: spring-core, spring-beans, spring-context, spring-web, spring-webmvc. Chúng ta bổ sung thêm thư viện JUnit để sau này viết Unit test, bổ sung thêm hibernate-validator để validate dữ liệu nhập vào qua form. Tất cả các dependency đều được khai báo 3 tham số GAV (GroupId – ArtifactId – Version). Khi khao báo version cho dependency, chúng ta sử dụng cách tổng quát hóa, khai báo số phiên bản qua properties trong pom.xml, đây là best practice, giả sử khi Spring Framework phát hành phiên bản 4.3.0.RELEASE, thì chúng ta chỉ cần thay đổi giá trị phiên bản này trong 1 vị trí chứ không phải 5 vị trí:

<spring.version>4.2.6.RELEASE</spring.version>

Là một ứng dụng web, nên trước khi xây dựng ứng dụng, bạn cần để ý đến file web.xml (deployment descriptor file). Từ dòng 7 – 18 là nội dung filter, filter này đảm bảo cho việc truyền dữ liệu ký tự Unicode tiếng Việt được đúng. Nếu bỏ qua thiết lập này, ứng dụng của bạn sẽ bị lỗi Font tiếng Việt. Filter có tên encodingFilter  này tác động đến tất cả các đường dẫn ứng dụng (được mô tả bằng <urlpatter>/*</urlpattern> ). Dòng 26 và 31 là đặc biệt quan trọng, để Spring Web MVC xử lý luồng đi của ứng dụng web.

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/webapp_3_1.xsd"
version="3.1">

<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.mvc</url-pattern>
</servlet-mapping>

</web-app>

Tạo thực thể Job (công việc). Các quy tắc kiểm tra tính hợp lệ dữ liệu đầu vào được thiết lập bằng annotation: @Size, @NotNull. Hibernate Validator phụ trách việc này.Một công việc có 8 thuộc tính là:

  1. title: Tiêu đề công việc
  2. company: Công ty tuyển dụng
  3. companyAddress: Địa chỉ công ty, nơi làm việc
  4. content: Chi tiết về yêu cầu tuyển dụng, chế độ đãi ngộ, thời gian làm việc, v.v..
  5. startDate: Ngày đăng tin
  6. endDate: Ngày gỡ tin tuyển dụng
  7. salary: Tiền lương
  8. createDate: Thời điểm tạo bản tin tuyển dụng
package vn.smartjob.demospring.domain;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.math.BigDecimal;
import java.util.Date;

/**
* Job entity.
*/
public class Job {

@Size(min = 32, max = 256)
@NotNull
String title;

@NotNull
@Size(max = 256)
String company;

@NotNull
String companyAddress;

@NotNull
@Size(min = 128)
String content;

@NotNull
Date startDate;

@NotNull
Date endDate;

@NotNull
BigDecimal salary;

@NotNull
Date createDate;

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getCompany() {
return company;
}

public void setCompany(String company) {
this.company = company;
}

public String getCompanyAddress() {
return companyAddress;
}

public void setCompanyAddress(String companyAddress) {
this.companyAddress = companyAddress;
}

public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}

public Date getStartDate() {
return startDate;
}

public void setStartDate(Date startDate) {
this.startDate = startDate;
}

public Date getEndDate() {
return endDate;
}

public void setEndDate(Date endDate) {
this.endDate = endDate;
}

public BigDecimal getSalary() {
return salary;
}

public void setSalary(BigDecimal salary) {
this.salary = salary;
}

public Date getCreateDate() {
return createDate;
}

public void setCreateDate(Date createDate) {
this.createDate = createDate;
}

}

Controller:

package vn.smartjob.demospring.controller;

import vn.smartjob.demospring.domain.Job;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class JobController {

@RequestMapping(value = "/form")
public ModelAndView job() {
return new ModelAndView("addJob", "job", new Job());
}

@RequestMapping(value = "/result", method = RequestMethod.POST)
public ModelAndView processJob(Job job, BindingResult result) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("j", job);
if (result.hasErrors()) {
modelAndView.setViewName("addJob");
} else {
modelAndView.setViewName("resultJob");
}
return modelAndView;
}

}

Cấu hình bean cho Spring Framework. Nghiệp vụ tùy chọn giao diện (theme) của người dùng được xử lý ở dòng thứ 24-26.

Class  org.springframework.web.servlet.theme.ThemeChangeInterceptor chịu trách nhiệm về việc này. Giao diện (theme) mặc định là modern (Hiện đại), là giao diện xuất hiện khi người dùng chưa đưa ra tùy chọn riêng cho mình.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

<context:component-scan base-package="vn.smartjob.demospring"/>
<context:annotation-config/>
<mvc:annotation-driven/>

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>

<bean id="themeSource" class="org.springframework.ui.context.support.ResourceBundleThemeSource"/>

<bean id="themeResolver" class="org.springframework.web.servlet.theme.SessionThemeResolver">
<property name="defaultThemeName" value="modern"/>
</bean>

<mvc:interceptors>
<bean id="themeChangeInterceptor" class="org.springframework.web.servlet.theme.ThemeChangeInterceptor">
<property name="paramName" value="theme"/>
</bean>
</mvc:interceptors>

</beans>


Chúng ta sẽ tạo 3 giao diện có tên là:

  • Classic: Cổ điển
  • Modern: Hiện đại
  • Beach: Bờ biển

3 tập tin css tương ứng là:

File classic.css

body {
background-color: #ffcab3;
color: #ffe48e;
}

.error {
background-color: gainsboro;
}
table{
width: 600px;
background-color: #2898ff;
}
td{
width: 300px;
}

File modern.css

body {
background-color: white;
color: black;
}

.error {
background-color: lime;
}
table{
width: 600px;
background-color: darkcyan;
}
td{
width: 300px;
}

File beach.css

body {
background-color: #28e2ff;
color: green;
}

.error {
background-color: beige;
}
table{
width: 600px;
background-color: lightblue;
}
td{
width: 300px;
}

Tạo 3 tập tin *.properties nằm trong thư mục resources:

File classic.properties

style=css/classic.css

File modern.properties

style=css/modern.css

File beach.properties

style=css/beach.css

Cần 2 trang JSP, một trang để thêm công việc mới và một trang để hiển thị kết quả:

Trang thêm mới công việc addJob.jsp . Bạn phải nhớ khai báo thư viện tag sử dụng như ở dòng 2 và dòng 3. Hãy để ý vào dòng 8, 13 và 14. Khi người dùng bấm chọn Giao diện, thì đường dẫn đến file css giao diện thay đổi, được xử lý bởi tag <spring> .

<%@ page contentType="text/html;charset=UTF-8" %>
<%@taglib prefix="mvc" uri="http://www.springframework.org/tags/form" %>
<%@taglib prefix="spring" uri="http://www.springframework.org/tags" %>

<html>
<head>
<title>Thêm công việc mới</title>
<link rel="stylesheet" href="<spring:theme code="style"/>" type="text/css"/>
</head>
<body>

<h2>Thêm công việc mới</h2>
Giao diện: <a href="?theme=classic">Cổ điển</a> - <a href="?theme=modern">Hiện đại</a> - <a href="?theme=beach">Bờ
biển</a><br/>

<mvc:form modelAttribute="job" action="result.mvc">
<table>
<tr>
<td><mvc:label path="title">Tiêu đề công việc</mvc:label></td>
<td><mvc:input path="title" cssErrorClass="error"/></td>
<td><mvc:errors path="title"/></td>
</tr>
<tr>
<td><mvc:label path="company">Công ty</mvc:label></td>
<td><mvc:input path="company" cssErrorClass="error"/></td>
<td><mvc:errors path="company"/></td>
</tr>
<tr>
<td><mvc:label path="companyAddress">Địa chỉ làm việc</mvc:label></td>
<td><mvc:input path="companyAddress" cssErrorClass="error"/></td>
<td><mvc:errors path="companyAddress"/></td>
<td></td>
</tr>
<tr>
<td><mvc:label path="content">Nội dung tuyển dụng</mvc:label></td>
<td><mvc:textarea path="content" cssErrorClass="error"/></td>
<td><mvc:errors path="content"/></td>
</tr>
<tr>
<td><mvc:label path="salary">Mức lương</mvc:label></td>
<td><mvc:input path="salary" cssErrorClass="error"/></td>
<td><mvc:errors path="salary"/></td>
</tr>
<tr>
<td><mvc:label path="startDate">Ngày bắt đầu đăng tin (mm/dd/yyyy)</mvc:label></td>
<td><mvc:input path="startDate" cssErrorClass="error"/></td>
<td><mvc:errors path="startDate"/></td>
</tr>
<tr>
<td><mvc:label path="endDate">Ngày gỡ bỏ tin (mm/dd/yyyy)</mvc:label></td>
<td><mvc:input path="endDate" cssErrorClass="error"/></td>
<td><mvc:errors path="endDate"/></td>
</tr>
<tr>
<td colspan="3">
<input type="submit" value="Gửi">
</td>
</tr>
</table>
</mvc:form>

</body>
</html>

Trang hiển thị kết quả resultJob.jsp

<%@ page contentType="text/html;charset=UTF-8" %>
<%@taglib prefix="mvc" uri="http://www.springframework.org/tags/form" %>
<%@taglib prefix="spring" uri="http://www.springframework.org/tags" %>

<html>
<head>
<title>Kết quả</title>
<link rel="stylesheet" href="<spring:theme code="style"/>" type="text/css" />
</head>
<body>

<h2>Nội dung công việc đã gửi</h2>
<table>
<tr>
<td>Tiêu đề công việc</td>
<td>${j.title}</td>
</tr>
<tr>
<td>Công ty</td>
<td>${j.company}</td>
</tr>
<tr>
<td>Địa chỉ làm việc</td>
<td>${j.companyAddress}</td>
</tr>
<tr>
<td>Nội dung</td>
<td>${j.content}</td>
</tr>
<tr>
<td>Mức lương</td>
<td>${j.salary}</td>
</tr>
<tr>
<td>Ngày bắt đầu đăng tin</td>
<td>${j.startDate}</td>
</tr>
<tr>
<td>Ngày gỡ bỏ tin</td>
<td>${j.endDate}</td>
</tr>
</table>
</body>
</html>

Trang chủ index.jsp sẽ trỏ về trang thêm mới công việc

<% response.sendRedirect("form.mvc"); %>

Đến nay chúng ta đã tạo đủ 14 file và project đã hoàn tất, chạy ứng dụng trên Apache Tomcat để thấy kết quả:

Giao diện mặc định là Hiện đại (Modern) được thiết lập ở dòng 25 trong file springmvc-servlet.xml

Cho phép tùy chọn Giao diện trong Spring Web MVC frameworkCho phép tùy chọn Giao diện trong Spring Web MVC framework

Bấm chọn và đổi giao diện, ta có giao diện Cổ điển (classic):

Giao diện Bờ biển (beach):

Cho phép tùy chọn Giao diện trong Spring Web MVC frameworkCho phép tùy chọn Giao diện trong Spring Web MVC framework

Sau khi bấm nút Gửi, nếu dữ liệu hợp lệ, sẽ trả về trang kết quả:

Cho phép tùy chọn Giao diện trong Spring Web MVC frameworkCho phép tùy chọn Giao diện trong Spring Web MVC framework

(Nội dung xuất hiện trong tất cả ảnh chụp màn hình chỉ mang tính chất minh họa)

Tải về mã nguồn từ server SmartJob: theme hoặc GitHub: https://github.com/SmartJobVN/spring_theme

Đỗ Như Vý – Bài viết gốc được đăng tải tại smartjob.vn

Có thể bạn quan tâm:

Xem thêm Jobs Developer hấp dẫn trên Station D

Bài viết liên quan

Ngành IT: Làm việc “trên mây” kiếm nhiều tiền nhất hiện nay

Ngành IT: Làm việc “trên mây” kiếm nhiều tiền nhất hiện nay

Kết quả từ cuộc khảo sát đầu năm của Station D về lương bổng của lập trình viên cho thấy nhiều thay đổi đã và đang diễn ra trong ngành IT – cuộc khảo sát tập trung vào các câu hỏi về khối lượng công việc, triển vọng cũng như...

By stationd
Đâu chỉ mỗi Bitcoin, công nghệ Blockchain còn nhiều ứng dụng hơn thế!

Đâu chỉ mỗi Bitcoin, công nghệ Blockchain còn nhiều ứng dụng hơn thế!

Khi nhắc đến blockchain , lập tức mọi người thường nghĩ ngay đến các loại tiền mã hóa, chẳng hạn như bitcoin. Tuy nhiên, blockchain lại là công nghệ tạo ra tiền mã hóa nhưng bản thân công nghệ này không phải là tiền mã hóa như cách mà chúng...

By stationd
Mock phương thức static trong Unit Test sử dụng PowerMock

Mock phương thức static trong Unit Test sử dụng PowerMock

Bài viết được sự cho phép của tác giả Nguyễn Hữu Khanh Trong bài viết này, mình sẽ hướng dẫn các bạn Mock các phương thức static trong Unit Test các bạn nhé! Nếu bạn nào chưa biết về Mock trong Unit Test thì mình có thể nói sơ qua...

By stationd
Một "thuật ngữ ma" đã tồn tại 75 năm trên internet, nó đang "ám" vào các mô hình AI, và sẽ còn tiếp tục tồn tại cho đến vĩnh cửu

Một "thuật ngữ ma" đã tồn tại 75 năm trên internet, nó đang "ám" vào các mô hình AI, và sẽ còn tiếp tục tồn tại cho đến vĩnh cửu

Một lời cảnh báo cho những người thích trích dẫn kiểu "nguồn sưu tầm", "nguồn internet" hay "nguồn AI", họ có thể sẽ đào lên được những "hóa thạch số" vô nghĩa.

By admin
Cảnh Báo Malware Giả Mạo Hợp Đồng Việc Làm: Tập Tin .EXE Nguy Hiểm Đội Lốt PDF/Word

Cảnh Báo Malware Giả Mạo Hợp Đồng Việc Làm: Tập Tin .EXE Nguy Hiểm Đội Lốt PDF/Word

Kẻ xấu đang lợi dụng nhu cầu tìm việc để phát tán phần mềm độc hại (malware) dưới dạng tệp 'hợp đồng' giả mạo. Hãy cảnh giác với những file có icon Word/PDF nhưng thực chất là .exe. Nếu mở, máy tính của bạn có thể bị đánh cắp toàn bộ thông tin cá nhân, cookie và mật khẩu.

By admin