java如何设置前端
设置前端的基本方法
在Java中设置前端通常涉及使用模板引擎或前端框架。Thymeleaf是一个流行的Java模板引擎,适合与Spring Boot集成。以下是一个简单的配置示例:
@Controller
public class WebController {
@GetMapping("/")
public String index(Model model) {
model.addAttribute("message", "Hello World");
return "index";
}
}
使用Spring Boot配置静态资源
Spring Boot默认从src/main/resources/static目录提供静态资源。创建HTML文件并放置在static目录下即可直接访问。例如创建index.html:

<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>Welcome</h1>
</body>
</html>
集成前端框架
对于React或Vue等现代前端框架,可以使用构建工具如Webpack或Vite。在Spring Boot项目中,将构建后的文件放在static目录中。配置pom.xml添加前端构建插件:
<plugin>
<groupId>com.github.eirslett</groupId>
<artifactId>frontend-maven-plugin</artifactId>
<version>1.12.1</version>
<executions>
<execution>
<id>install node and npm</id>
<goals>
<goal>install-node-and-npm</goal>
</goals>
</execution>
<execution>
<id>npm install</id>
<goals>
<goal>npm</goal>
</goals>
</execution>
<execution>
<id>npm run build</id>
<goals>
<goal>npm</goal>
</goals>
<configuration>
<arguments>run build</arguments>
</configuration>
</execution>
</executions>
</plugin>
使用REST API与前端交互
创建REST控制器提供API接口供前端调用:

@RestController
@RequestMapping("/api")
public class ApiController {
@GetMapping("/data")
public ResponseEntity<String> getData() {
return ResponseEntity.ok("Data from backend");
}
}
前端可以使用Fetch或Axios调用这些API:
fetch('/api/data')
.then(response => response.text())
.then(data => console.log(data));
跨域问题处理
如果前端运行在不同端口,需要配置CORS。在Spring Boot中可以通过@CrossOrigin注解或全局配置:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/")
.allowedOrigins("*")
.allowedMethods("GET", "POST");
}
}






