springboot实现一个美食网站的源代码
时间: 2023-05-14 09:00:35 浏览: 70
首先,为了实现一个美食网站,我们需要使用Spring Boot框架作为后端技术且需要使用HTML/CSS/JavaScript作为前端技术。接下来,我们将列出关于该美食网站的Spring Boot源代码:
1.配置文件
spring.datasource.url=jdbc:mysql://localhost:3306/food
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.initialization-mode=always
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
2.实体类
@Entity
public class Food {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "name")
private String name;
@Column(name = "description")
private String description;
@Column(name = "image_name")
private String imageName;
@Column(name = "category")
private String category;
@Column(name = "price")
private Double price;
@Column(name = "rating")
private Double rating;
//Getter和Setter方法
}
3.控制器类
@Controller
@RequestMapping("/food")
public class FoodController {
@Autowired
private FoodRepository foodRepository;
@GetMapping("/")
public String home(Model model) {
List<Food> foods = foodRepository.findAll();
model.addAttribute("foods", foods);
return "home";
}
@GetMapping("/{id}")
public String showFood(@PathVariable Long id, Model model) {
Food food = foodRepository.getOne(id);
model.addAttribute("food", food);
return "detail";
}
//获取JSON数据
@GetMapping("/api/")
@ResponseBody
public List<Food> getAllFoods() {
return foodRepository.findAll();
}
}
4.数据访问层类
@Repository
public interface FoodRepository extends JpaRepository<Food, Long> {
}
5.HTML页面
<!-- home.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Food Home</title>
</head>
<body>
<h1>Welcome to Our Food Site!</h1>
<div>
<h2>All Foods</h2>
<ul>
<li th:each="food : ${foods}">
<a th:href="@{/food/{id}(id=${food.id})}">
<img th:src="@{/images/${food.imageName}}" width="200"/>
<h3 th:text="${food.name}"></h3>
<p th:text="${food.description}"></p>
<div>
<span th:text="${food.rating}"></span> /
<span th:text="${food.price}"></span>
</div>
</a>
</li>
</ul>
</div>
</body>
</html>
<!-- detail.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Food Detail</title>
</head>
<body>
<h1 th:text="${food.name}"></h1>
<div>
<img th:src="@{/images/${food.imageName}}" width="500"/>
</div>
<p th:text="${food.description}"></p>
<div>
<span th:text="${food.rating}"></span> /
<span th:text="${food.price}"></span>
</div>
</body>
</html>
以上代码是一个简单的Spring Boot实例,但它可以实现一个美食网站的基本需求。如果需要更多功能,您可以通过添加更多实体、控制器和模板页面来扩展该网站。