@[TOC]Spring 之页面跳转
Spring 项目中的页面跳转之实现
涉及技术栈
Springboot 的controller层
Thymeleaf 的th:action标签涉及到的Springboot注解:
@RequestMapping @GetMapping @PostMapping @Controller
Spring 的redirect 重定向的使用
具体实现
- Controller层代码的实现
@Controller
@RequestMapping("")
public class UserController {
@Resource
private UserService userService;
@GetMapping({"/login"})
public String login()
{
return "login";
}
@PostMapping(value="/login")
public String checkLogin(@RequestParam("username") String username,
@RequestParam("password") String password,
Map<String,Object> map){
User loginUser = userService.selectUserByName(username);
String userPassword = loginUser.getPassword();
System.out.println(userPassword);
if(userPassword.equals(password)){
return "redirect:/index";
}else {
map.put("msg","用户名密码错误");
return "login";
}
}
@GetMapping({"/index"})
public String index(){
//request.setAttribute("path","index");
return "index";
}
}
上面代码中的知识点
- 类上面的@RequestMapping 加上类中方法前的@GetMapping注解可以实现在注解中的路径拼接起来构成的网址的访问;
- redirect重定向可以实现从login.html访问到index.html访问的跳转,倘若不使用redirect直接书写: return “index”; 虽也能实现页面的跳转,但我们网址的url不会变
依然是(eg:localhost:28088/login) - 在前端的login.html文件中,使用thymeleaf标签
th:action=”@{login}” method=“post”
才能走到使用@PostMapping修饰的方法checkLogin里;即
@PostMapping(value="/login")
public String checkLogin(@RequestParam("username") String username,
@RequestParam("password") String password,
Map<String,Object> map){
// User exampleUser = userMapper.selectById(username);
User loginUser = userService.selectUserByName(username);
String userPassword = loginUser.getPassword();
System.out.println(userPassword);
// String userPassword = exampleUser.getPassword();
if(userPassword.equals(password)){
return "redirect:/index";
}else {
map.put("msg","用户名密码错误");
return "login";
}
}
综上才能实现页面的跳转。
- return 里面的语句,例如 return “index”; 代表的是,resource(默认templates)下的文件路径
问题
@Controller
@RequestMapping("")
public class UserController {
@Resource
private UserService userService;
//这是正确的
在上面的代码中若使用@Resource注解 ,如果我们把引入的UserService 对象命名为userMapper ,使用IDEA运行工程,则会报JDK动态代理错误;
@Controller
@RequestMapping("")
public class UserController {
@Resource
private UserService userMapper;
//这会报错
而若使用@Autowired注解,命名对象为userMapper(即瞎命名)则不会报错,网站正常起。
@Controller
@RequestMapping("")
public class UserController {
@Autowired
private UserService userMapper;
//虽错,但也能起
???
版权声明:本文为emmastone原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。