12.7 控制层功能实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| package org.fkit.controller;
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping;
@Controller public class FormController { @RequestMapping( value = "/loginForm") public String loginForm() { return "loginForm"; } }
|
UserController.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| package org.fkit.controller;
import javax.servlet.http.HttpSession; import org.fkit.domain.User; import org.fkit.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.view.RedirectView;
@Controller public class UserController {
@Autowired @Qualifier("userService") private UserService userService;
@PostMapping(value = "/login") public ModelAndView login(String loginname, String password, ModelAndView mv, HttpSession session) { User user = userService.login(loginname, password); if (user != null) { session.setAttribute("user", user); mv.setView(new RedirectView("/fkbookapp/main")); } else { mv.addObject("message", "登录名或密码错误,请重新输入!"); mv.setViewName("loginForm"); } return mv; } }
|
BookController.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| package org.fkit.controller;
import java.util.List; import org.fkit.domain.Book; import org.fkit.service.BookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping;
@Controller public class BookController {
@Autowired @Qualifier("bookService") private BookService bookService;
@RequestMapping( value = "/main") public String main(Model model) { List<Book> book_list = bookService.getAll(); model.addAttribute("book_list", book_list); return "main"; } }
|
控制层使用了Spring
的@Autowired
注解自动注入服务层的Service
对象,@Qualifier
注解用于指明需要注入的具体类型,并且使用@Controller
注解将类注释成为Spring
的Controller
。
原文链接: 12.7 控制层功能实现