运用spring boot框架用@RestController@RequestParam@Autowired@PostMapping@Service@Mapper@Data注解和xml<select>语句用resultType数据库mysql实现用户登录案例
时间: 2024-02-13 12:39:19 浏览: 176
以下是一个简单的spring boot框架下实现用户登录的示例代码:
User.java
```java
package com.example.demo.model;
import lombok.Data;
@Data
public class User {
private String username;
private String password;
}
```
UserMapper.java
```java
package com.example.demo.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import com.example.demo.model.User;
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user WHERE username=#{username} AND password=#{password}")
User login(@Param("username") String username, @Param("password") String password);
}
```
UserService.java
```java
package com.example.demo.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.demo.mapper.UserMapper;
import com.example.demo.model.User;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User login(String username, String password) {
return userMapper.login(username, password);
}
}
```
UserController.java
```java
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.model.User;
import com.example.demo.service.UserService;
@RestController
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/login")
public String login(@RequestParam String username, @RequestParam String password) {
User user = userService.login(username, password);
if (user == null) {
return "登录失败";
} else {
return "登录成功";
}
}
}
```
application.properties
```properties
spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
```
以上代码中,使用了@RestController注解将UserController声明为一个控制器,@PostMapping注解将login方法映射到/login接口,@RequestParam注解用于接收请求参数,@Autowired注解用于依赖注入,@Service注解用于声明UserService为一个服务,@Mapper注解用于声明UserMapper为一个Mapper,@Data注解用于自动生成getter、setter和toString方法。在UserMapper中使用了<select>语句和resultType属性实现了查询,同时使用了@Param注解指定参数名。application.properties中配置了数据库连接信息。这样,当用户访问/login接口时,会调用UserController的login方法,该方法调用了UserService的login方法,后者又调用了UserMapper的login方法,最终返回用户登录信息。
阅读全文