12.7 控制层功能实现

12.7 控制层功能实现

FormController.java

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.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
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{
/**
* 自动注入UserService
*/
@Autowired
@Qualifier("userService")
private UserService userService;

/**
* 处理/login请求
*/
@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);
// 登录成功,将User对象 放置到HttpSession作用域中
session.setAttribute("user", user);
//
mv.setView(new RedirectView("/MyBookApp/main"));
// mv.setViewName("loginForm");
// mv.setViewName("redirect:/main");
}else{
mv.addObject("message", "登录名或密码错误,请重新输入!");
mv.setViewName("loginForm");
}
return mv;
}
}

BookController.java

/MyBookApp/src/com/controller/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
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 {
/**
* 自动注入BookService.
*/
@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注解将类注释成为SpringController