Springboot+ajax+mybatis实现简易网页
要使用Spring Boot、Ajax和MyBatis实现一个简易的网页,你需要创建一个Spring Boot项目,并配置MyBatis。以下是一个简化的例子:
- 创建一个Spring Boot项目,并添加MyBatis和Web依赖。
<dependencies>
<!-- Spring Boot Web Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MyBatis Framework -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<!-- Database Driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
- 配置application.properties文件,包括数据库连接和MyBatis mapper位置。
spring.datasource.url=jdbc:mysql://localhost:3306/your_database
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis.mapper-locations=classpath:mapper/*.xml
- 创建一个简单的Controller。
@Controller
public class SimpleController {
@Autowired
private YourService yourService;
@RequestMapping("/greeting")
@ResponseBody
public String greeting() {
return yourService.getGreeting();
}
}
- 创建Service和Mapper。
@Service
public class YourService {
@Autowired
private YourMapper yourMapper;
public String getGreeting() {
return yourMapper.selectGreeting();
}
}
@Mapper
public interface YourMapper {
@Select("SELECT greeting FROM your_table LIMIT 1")
String selectGreeting();
}
- 创建HTML页面,并使用Ajax调用Spring Boot Controller。
<!DOCTYPE html>
<html>
<head>
<title>Simple Page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#loadGreeting").click(function() {
$.ajax({
url: "/greeting",
type: "GET",
success: function(response) {
评论已关闭