Spring整合Mybatis 使用注册的用户名和密码进行登录,登录成功展示用户名.密码.角色名
时间: 2023-08-09 17:11:25 浏览: 87
spring 整合 mybatis 中数据源的几种配置方式(总结篇)
首先,您需要配置Spring和Mybatis的整合。这里提供一份示例配置文件:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd">
<!-- 数据源配置 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!-- Mybatis配置 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="com.example.entity"/>
<!-- mybatis配置文件 -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!-- Mapper接口扫描 -->
<mybatis-spring:scan base-package="com.example.mapper"/>
<!-- 事务管理器配置 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 开启注解事务 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- 开启Spring注解 -->
<context:annotation-config/>
<context:component-scan base-package="com.example"/>
</beans>
```
接下来,您需要编写登录功能的Service和DAO层代码。这里提供一个简单的示例:
```java
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User login(String username, String password) {
User user = userMapper.findByUsernameAndPassword(username, password);
return user;
}
}
@Mapper
public interface UserMapper {
User findByUsernameAndPassword(@Param("username") String username, @Param("password") String password);
}
```
最后,您需要编写Controller层代码来响应用户登录的请求,并返回相应的信息:
```java
@RestController
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/login")
public Map<String, Object> login(@RequestParam("username") String username, @RequestParam("password") String password) {
Map<String, Object> result = new HashMap<>();
User user = userService.login(username, password);
if (user != null) {
result.put("success", true);
result.put("username", user.getUsername());
result.put("password", user.getPassword());
result.put("role", user.getRole());
} else {
result.put("success", false);
result.put("message", "用户名或密码错误");
}
return result;
}
}
```
这样,当用户通过POST请求访问`/login`接口并传递正确的用户名和密码时,您将会得到一个JSON格式的响应,其中包含用户名、密码和角色名。
阅读全文