使用Spring框架,写一个完整的项目
时间: 2024-03-14 17:46:36 浏览: 156
好的,我会给你一个简单的Spring项目示例,包括基本的Spring MVC和Spring Data JPA。
1. 创建一个Maven项目,添加以下依赖:
```xml
<dependencies>
<!-- Spring Core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<!-- Spring Web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<!-- Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<!-- Spring Data JPA -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.3.4.RELEASE</version>
</dependency>
<!-- H2 Database Engine -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
</dependency>
</dependencies>
```
2. 创建一个实体类,例如:
```java
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "age")
private Integer age;
// constructors, getters, setters
}
```
3. 创建一个JPA仓库接口,例如:
```java
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
```
4. 创建一个控制器类,例如:
```java
@Controller
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping("/users")
public String getAllUsers(Model model) {
List<User> users = userRepository.findAll();
model.addAttribute("users", users);
return "users";
}
@GetMapping("/users/add")
public String addUserForm(Model model) {
model.addAttribute("user", new User());
return "addUserForm";
}
@PostMapping("/users/add")
public String addUser(@ModelAttribute User user) {
userRepository.save(user);
return "redirect:/users";
}
}
```
5. 创建一个视图文件,例如:
```html
<!-- users.html -->
<!DOCTYPE html>
<html>
<head>
<title>Users</title>
</head>
<body>
<h1>Users</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr th:each="user : ${users}">
<td th:text="${user.id}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.age}"></td>
</tr>
</tbody>
</table>
<a href="/users/add">Add User</a>
</body>
</html>
<!-- addUserForm.html -->
<!DOCTYPE html>
<html>
<head>
<title>Add User</title>
</head>
<body>
<h1>Add User</h1>
<form method="post" th:action="@{/users/add}">
<label for="name">Name:</label>
<input type="text" id="name" name="name" /><br />
<label for="age">Age:</label>
<input type="number" id="age" name="age" /><br />
<input type="submit" value="Add" />
</form>
</body>
</html>
```
6. 创建一个Spring配置类,例如:
```java
@Configuration
@EnableWebMvc
@EnableJpaRepositories(basePackages = "com.example.demo.repository")
@EntityScan(basePackages = "com.example.demo.entity")
public class AppConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
}
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.build();
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(dataSource());
emf.setPackagesToScan("com.example.demo.entity");
emf.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
emf.setJpaProperties(jpaProperties());
return emf;
}
private Properties jpaProperties() {
Properties props = new Properties();
props.setProperty("hibernate.hbm2ddl.auto", "create-drop");
props.setProperty("hibernate.show_sql", "true");
props.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
return props;
}
@Bean
public JpaTransactionManager transactionManager() {
JpaTransactionManager tm = new JpaTransactionManager();
tm.setEntityManagerFactory(entityManagerFactory().getObject());
return tm;
}
}
```
7. 运行项目,在浏览器中访问http://localhost:8080/users即可查看所有用户,并通过http://localhost:8080/users/add添加新用户。
这是一个非常简单的Spring项目,实现了基本的增删改查功能。当然,在实际开发中,需要更多的配置和复杂的业务逻辑。
阅读全文