Establishing the project foundation involves defining a clear module structure. The dao and pojo directories host auto-generated mapper interfaces and corresponding entity models. Business logic resides in service, while controller manages inbound HTTP requests. Utility functions are grouped under util. Frontend styling and scripts are segregated into static, whereas server-rendered views occupy templates. The interface layer utilizes Layui for component rendering.
Dependency Resolution & Build Configuration
A robust Maven setup prevents runtime failures regarding missing resources. The pom.xml must declare starter dependencies for web development, relational database connectivity, ORM mapping, and template rendering. Additionally, custom resource filters guarantee that XML mappers and static assets compile correctly.
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.3.0</version>
<configuration>
<nonFilteredFileExtensions>
<nonFilteredFileExtension>ttf</nonFilteredFileExtension>
<nonFilteredFileExtension>woff</nonFilteredFileExtension>
<nonFilteredFileExtension>woff2</nonFilteredFileExtension>
</nonFilteredFileExtensions>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*</include>
</includes>
<excludes>
<exclude>application.yml</exclude>
</excludes>
</resource>
</resources>
</build>
Environment Configuration
Runtime parameters control data source connectivity and template engine behavior. Using YAML simplifies hierarchical property definitions. Thymeleaf requires cache disablement during development to reflect immediate template changes. Database credentials should never be hardcoded in production environments; environment variables or secret managers are preferred.
spring:
datasource:
url: jdbc:mysql://localhost:3306/class_db?useSSL=false&serverTimezone=UTC&characterEncoding=utf8
username: db_admin
password: secure_pass
driver-class-name: com.mysql.cj.jdbc.Driver
servlet:
multipart:
max-file-size: 10MB
max-request-size: 20MB
thymeleaf:
prefix: classpath:/templates/
suffix: .html
mode: HTML
encoding: UTF-8
cache: false
mybatis:
type-aliases-package: com.app.management.pojo
mapper-locations: classpath:mapper/**/*.xml
Routing & Template Rendering
Thymeleaf decouples URL paths from physical file locations. Anchor tags and form actions must reference controller mappings rather than HTML filenames. Direct file access bypasses the request cycle, triggering 404 errors when controllers expect mapped endpoints.
<!-- Correct routing reference -->
<a href="/dashboard/students">View Class Roster</a>
Form submissions should utilize asynchronous JavaScript to prevent page reloads and enable dynamic response handling. Sending raw POST requests ensures the backend processes payloads consistently.
document.getElementById('submitBtn').addEventListener('click', function() {
const formData = new FormData(document.getElementById('regForm'));
fetch('/api/auth/register', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.status === 'success') window.location.href = '/dashboard';
else alert(data.message);
});
});
Controllers bridge request handlers and view models. Returning a ModelAndView instance allows seamless data injection into Thymeleaf templates.
@GetMapping("/dashboard")
public ModelAndView renderDashboard(HttpSession session) {
StudentEntity currentUser = (StudentEntity) session.getAttribute("active_user");
ModelAndView mv = new ModelAndView("index");
mv.addObject("display_name", currentUser.getName());
return mv;
}
Persistent Mapping & Generator Setup
MyBatis Generator automates entity creation and mapper interface definition. Executing the Maven plugin parses existing database schemas and produces boilerplate code. Developers must manually annotate generated interfaces with @Mapper to enable component scanning. Missing annotations break context initialization.
Regular builds require cleaning target directories before regeneration. Appending updated XMLs to previous versions causes duplicate ID conflicts within result map collections.
Security Interception & Session Validation
Unauthenticated access prevention relies on HandlerInterceptor. The implementation overrides preHandle to inspect session attributes before request execution. Whitelisted paths for login pages and static assets skip validation loops.
@Configuration
public class WebSecurityConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new AuthInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/login", "/register", "/static/**");
}
}
public class AuthInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession(false);
if (session != null && session.getAttribute("active_user") != null) {
return true;
}
response.sendRedirect("/login");
return false;
}
}
Multipart File Processing
Document uploads require explicit configuration within the main application class or via properties. Spring Boot's auto-configuration handles dispatcher registration automatically when thresholds are set. Controller methods accept MultipartFile arguments, extract destination paths, and execute safe save operations.
@PostMapping("/upload/documents")
public ResponseEntity<String> handleUpload(@RequestParam("file") MultipartFile uploadedFile) {
try {
String destPath = System.getProperty("user.dir") + "/uploads/" + uploadedFile.getOriginalFilename();
uploadedFile.transferTo(new File(destPath));
return ResponseEntity.ok("{\"code\": \"0\", \"msg\": \"Upload complete\"}");
} catch (IOException e) {
return ResponseEntity.status(500).body("{\"code\": \"1\", \"msg\": \"Process failed\"}");
}
}
Ensuring proper MIME type verification and size restrictions mitigates payload abuse vulnerabilities. Structured JSON responses standardize client-side parsing logic across disparate endpoints.