12.7 控制层功能实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| package com.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
/MyBookApp/src/com/controller/UserController.java1 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
| package com.controller;
import javax.servlet.http.HttpSession; 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.RequestMapping; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.view.RedirectView; import com.domain.User; import com.service.UserService;
@Controller public class UserController{
@Autowired @Qualifier("userService") private UserService userService;
@RequestMapping("/login") public ModelAndView login(String loginname,String password,ModelAndView mv,HttpSession session){ System.out.println("com.controller.UserController.login(String, String, ModelAndView, HttpSession)"); User user = userService.login(loginname, password); if(user != null){ System.out.println("登录成功:" + user); session.setAttribute("user", user); mv.setView(new RedirectView("/MyBookApp/main")); }else{ mv.addObject("message", "登录名或密码错误,请重新输入!"); mv.setViewName("loginForm"); } return mv; } }
|
BookController.java
/MyBookApp/src/com/controller/BookController.java1 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
| package com.controller;
import java.util.List; 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; import com.domain.Book; import com.service.BookService;
@Controller public class BookController {
@Autowired @Qualifier("bookService") private BookService bookService;
@RequestMapping(value = "/main") public String main(Model model) { System.out.println("com.controller.BookController.main(Model)"); List<Book> book_list = bookService.getAllBooks(); model.addAttribute("book_list", book_list); return "main"; } }
|
控制层使用了Spring
的@Autowired
注解自动注入服务层的Service
对象,@Qualifier
注解用于指明需要注入的具体类型,并且使用@Controller
注解将类注释成为Spring
的Controller
。