承接上一篇文章(http://my.oschina.net/ritchielei/blog/645049),继续说明SpringMVC的一些用法
一、业务类的注解定义
在上一章中,我们用到了 customerservice ,当时我们是在构造函数中明确New出来的,其实在SpringMVC里有更方便的做法。
1) 在Service类上增加 @Service 注解
2) 在调用类中使用 @Autowired 进行自动构造
修改后的代码
CustomerService.java
增加如上代码 |
CustomerController.java 修改为
|
在 SpringMVC配置文件中,增加Service包扫描
<context:component-scan base-package="org.happy.smvcdemo.controller" />
<context:component-scan base-package="org.happy.smvcdemo.service" />
再次运行程序,功能如常。说明这个修改成功!
当有多个Service时候,需要在控制层明确指定Service名字。
比如,如果增加了
@Service(value = "userService")
public class UserService {
public List<User> getUserList() {
String sql = "SELECT * FROM user";
List<User> cl = new ArrayList<User>();
// TODO
return cl;
}
}
import org.springframework.stereotype.Service;
// 需要修改
@Service(value = "customerService")
public class CustomerService {
public List<Customer> getCustomerList() {
String sql = "SELECT * FROM customer";
需要在UserController中明确指定Service
import javax.annotation.Resource;
@Controller
public class CustomerController {
// 明确指定
@Resource(name = "customerService")
private CustomerService serv;
二、使用 ModelAndView作返回
上一节中我们使用 model.addAttribute(.., ...) 来把对象放入JSP中。其实在SpringMVC里还可以用 ModelAndView来返回。
示例: 在CustomerController 中添加如下函数
@RequestMapping(value = "customers", method = RequestMethod.GET)
public ModelAndView listCustomers() {
List customerList = serv.getCustomerList();
ModelAndView mv = new ModelAndView();
mv.setViewName("customers.jsp");
mv.addObject("customerList",customerList);
return mv;
}
运行程序,然后访问 http://localhost:8080/smvcdemo-1.0/customers.do
可以看到一样能获得所有的客户信息。