Giới thiệu
Trong bài viết này, chúng ta sẽ khám phá các khái niệm cơ bản của Java và SpringBoot thông qua các ví dụ cụ thể. Chúng tôi sẽ trình bày cách triển khai một số tính năng quan trọng như xử lý lỗi, quản lý session và cấu hình môi trường.
Cấu trúc DispatcherServlet trong Spring
Khi người dùng nhập URL vào trình duyệt, yêu cầu sẽ được gửi đến DispatcherServlet. Servlet này sau đó sẽ sử dụng HandlerMapping để tìm ra Controller phù hợp:
@RequestMapping("/doLogin")
@ResponseBody
public SysResult doLogin(User user, HttpServletResponse response, HttpServletRequest request) {
String userIP = IPUtil.getIpAddr(request);
String ticket = userService.findUserByUP(user, userIP);
if (StringUtils.isEmpty(ticket)) {
return SysResult.fail();
}
Cookie cookie = new Cookie("AUTH_TICKET", ticket);
cookie.setMaxAge(7 * 24 * 3600); // Hiệu lực trong 7 ngày
cookie.setPath("/");
cookie.setDomain("example.com");
response.addCookie(cookie);
return SysResult.success();
}
Spring Boot và Auto Configuration
Khi khởi chạy ứng dụng Spring Boot, framework tự động cấu hình dựa trên các file application.properties hoặc application.yml. Điều này giúp giảm thiểu việc cấu hình thủ công.
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Tính năng Caching trong MyBatis
MyBatis hỗ trợ caching để tăng hiệu suất bằng cách lưu trữ dữ liệu đã truy vấn trước đó. Có hai cấp độ cache chính:
- Level 1 Cache: Lưu trữ tại mức Session, chỉ tồn tại trong suốt thời gian sống của một
SqlSession. - Level 2 Cache: Lưu trữ tại mức Mapper, có thể chia sẻ giữa nhiều
SqlSession.
<!-- Level 1 Cache -->
<cache readOnly="false" />
<!-- Level 2 Cache -->
<cache type="org.mybatis.caches.ehcache.EhcacheCache" />
AOP trong Spring
AOP (Aspect-Oriented Programming) cho phép tách biệt logic nghiệp vụ khỏi các chức năng chung như logging hoặc transaction management. Dưới đây là ví dụ về việc sử dụng AOP để đo thời gian thực hiện phương thức:
@Aspect
@Component
public class ExecutionTimeAspect {
@Around("execution(* com.example.service.*.*(..))")
public Object measureExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.currentTimeMillis();
Object result = joinPoint.proceed();
long end = System.currentTimeMillis();
System.out.println("Method " + joinPoint.getSignature().getName() + " took " + (end - start) + " ms");
return result;
}
}
Quản lý phiên làm việc với Single Sign-On (SSO)
Để triển khai SSO, chúng ta cần tạo một hệ thống phân phối token khi người dùng đăng nhập thành công. Token này sau đó sẽ được lưu trữ trên client dưới dạng cookie:
@RequestMapping("/query/{token}/{username}")
public JSONPObject findUserByToken(@PathVariable String token,
@PathVariable String username,
HttpServletRequest request,
HttpServletResponse response,
String callback) {
String redisToken = jedisCluster.get("USER_" + username);
if (!redisToken.equals(token)) {
CookieUtil.deleteCookie("AUTH_TOKEN", "/", "example.com", response);
return new JSONPObject(callback, SysResult.fail());
}
Map userData = jedisCluster.hgetAll(token);
return new JSONPObject(callback, SysResult.success(userData));
}
Lập trình hướng đối tượng trong Java
Một lớp thực thể trong Java thường đại diện cho một bảng trong cơ sở dữ liệu. Ví dụ dưới đây minh họa một lớp Entity đơn giản:
@Entity
@Table(name = "sys_users")
public class UserEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
// Getters and Setters
}
Thiết lập môi trường Spring Boot
Để thiết lập môi trường Spring Boot, bạn cần thêm các dependencies cần thiết vào file pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>