SpringBoot中@Controller和@ResponseBody的区别

1,@Controller表明该类所有的方法返回页面路径,但是在方法上加了@ResponseBody后,该方法返回的是数据。
2,@RestController则相当于@Controller和@ResponseBody同时使用的效果,返回的也是数据,不是界面
3,如果我们还想返回界面可以使用ModelAndView方法

	@RequestMapping("/")
	public ModelAndView index(){
		ModelAndView  model = new ModelAndView();
		model.setViewName("/xxx")//界面路径
		return  model;

}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个基于 Spring Boot 的用户登录案例: 1. 创建 User 实体类 ```java @Data public class User { private String username; private String password; } ``` 2. 创建 UserService 接口和实现类 ```java public interface UserService { User login(String username, String password); } @Service public class UserServiceImpl implements UserService { @Override public User login(String username, String password) { // 在这里校验用户名和密码是否正确,省略实现 return new User(username, password); } } ``` 3. 创建 UserController 控制器 ```java @Controller public class UserController { @Autowired private UserService userService; @PostMapping("/login") @ResponseBody public String login(@RequestBody User user) { User loginUser = userService.login(user.getUsername(), user.getPassword()); if (loginUser != null) { return "登录成功"; } else { return "用户名或密码错误"; } } } ``` 4. 配置 mybatis 和数据库信息 在 application.properties 文件添加以下配置: ``` spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false&maxReconnects=10 spring.datasource.username=root spring.datasource.password=root mybatis.mapper-locations=classpath:mapper/*.xml ``` 5. 创建 UserMapper 接口和 XML 映射文件 ```java @Mapper public interface UserMapper { User selectByUsernameAndPassword(@Param("username") String username, @Param("password") String password); } ``` 在 mapper 文件夹下创建 UserMapper.xml 文件,编写 SQL 语句: ```xml <mapper namespace="com.example.demo.mapper.UserMapper"> <resultMap id="BaseResultMap" type="com.example.demo.entity.User"> <id column="username" property="username" /> <result column="password" property="password" /> </resultMap> <select id="selectByUsernameAndPassword" resultMap="BaseResultMap"> select * from user where username=#{username} and password=#{password} </select> </mapper> ``` 6. 编写测试代码 ```java @RunWith(SpringRunner.class) @SpringBootTest public class UserControllerTests { @Autowired private UserController userController; @Test public void testLogin() { User user = new User(); user.setUsername("admin"); user.setPassword("123456"); String result = userController.login(user); assertEquals("登录成功", result); } } ``` 以上就是一个基于 Spring Boot 的用户登录案例的实现过程,希望对你有所帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值