Web 开发插件
LCGYL Framework 提供了轻量级的 Web 开发支持。
插件列表
| 插件 | 说明 | 适用场景 |
|---|---|---|
| lcgyl-web-plugin | Web 服务器、路由、控制器 | RESTful API |
| lcgyl-web-reactive | 响应式 Web | 高并发场景 |
快速开始
添加依赖
gradle
dependencies {
implementation 'com.lcgyl:lcgyl-web-plugin:2.2.0'
}创建控制器
java
@Controller
@RequestMapping("/api/users")
public class UserController {
@Inject
private UserService userService;
@GetMapping
public List<User> list() {
return userService.findAll();
}
@GetMapping("/{id}")
public User get(@PathVariable Long id) {
return userService.findById(id);
}
@PostMapping
public User create(@RequestBody User user) {
return userService.save(user);
}
@PutMapping("/{id}")
public User update(@PathVariable Long id, @RequestBody User user) {
user.setId(id);
return userService.update(user);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id) {
userService.deleteById(id);
}
}配置
yaml
lcgyl:
web:
server:
port: 8080
context-path: /api
cors:
enabled: true
allowed-origins: "*"路由
路径参数
java
@GetMapping("/users/{id}")
public User get(@PathVariable("id") Long userId) {
return userService.findById(userId);
}查询参数
java
@GetMapping("/users")
public List<User> search(
@RequestParam(required = false) String name,
@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "10") int size) {
return userService.search(name, page, size);
}请求体
java
@PostMapping("/users")
public User create(@RequestBody CreateUserRequest request) {
return userService.create(request);
}中间件
java
@Component
public class LoggingMiddleware implements Middleware {
@Override
public void handle(Request request, Response response, MiddlewareChain chain) {
long start = System.currentTimeMillis();
chain.next(request, response);
long duration = System.currentTimeMillis() - start;
logger.info("{} {} - {}ms", request.getMethod(), request.getPath(), duration);
}
}异常处理
java
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(NotFoundException.class)
public ResponseEntity<ErrorResponse> handleNotFound(NotFoundException e) {
return ResponseEntity.status(404)
.body(new ErrorResponse(404, e.getMessage()));
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleException(Exception e) {
return ResponseEntity.status(500)
.body(new ErrorResponse(500, "Internal Server Error"));
}
}下一步
- Web Reactive - 响应式 Web
- 安全插件 - 认证授权