答案是使用Spring Boot快速搭建在线投票平台,通过Spring MVC处理请求,JPA操作MySQL数据库,Thymeleaf渲染页面,实现投票主题展示、选项提交与结果统计功能。
要创建一个小型在线投票平台,Java可以结合Spring Boot、Thymeleaf(或JSP)、数据库(如MySQL)来快速搭建。整个系统包括用户发起投票、查看选项、提交投票和查看结果等功能。下面是一个简单可行的实现思路。
使用Spring Boot可以快速构建Web应用,简化配置。主要技术栈如下:
创建Maven项目,在pom.xml中引入关键依赖:
org.springframework.boot spring-boot-starter-weborg.springframework.boot spring-boot-starter-data-jpaorg.springframework.boot spring-boot-starter-thymeleafmysql mysql-connector-java
定义两个核心实体类:VoteTopic(投票主题)和VoteOption(选项)。
VoteTopic.java
@Entity
public class VoteTopic {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
@OneToMany(mappedBy = "topic", cascade = CascadeType.ALL)
private List options = new Arr
ayList<>();
// getter 和 setter
}
VoteOption.java
@Entity
public class VoteOption {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String optionText;
private int voteCount = 0;
@ManyToOne
@JoinColumn(name = "topic_id")
private VoteTopic topic;
// getter 和 setter
}
编写VoteController处理页面跳转和投票逻辑。
@Controller
public class VoteController {
@Autowired
private VoteTopicRepository topicRepo;
@GetMapping("/vote/{id}")
public String showVotePage(@PathVariable Long id, Model model) {
VoteTopic topic = topicRepo.findById(id).orElse(null);
if (topic == null) return "error";
model.addAttribute("topic", topic);
return "vote_page"; // 对应 templates/vote_page.html
}
@PostMapping("/vote/submit")
public String submitVote(@RequestParam Long optionId) {
Optional opt = optionRepo.findById(optionId);
if (opt.isPresent()) {
VoteOption option = opt.get();
option.setVoteCount(option.getVoteCount() + 1);
optionRepo.save(option);
}
return "redirect:/result/" + option.getTopic().getId();
}
@GetMapping("/result/{id}")
public String showResult(@PathVariable Long id, Model model) {
VoteTopic topic = topicRepo.findById(id).orElse(null);
model.addAttribute("topic", topic);
return "result_page";
}
}
在resources/templates/vote_page.html中显示投票项:
结果页result_page.html显示统计:
投票结果:
基本上就这些。启动类加上@SpringBootApplication,配置好数据库连接(application.properties),运行即可访问。