SpringMVC构建WEB应用(二)


承接上一篇文章(http://my.oschina.net/ritchielei/blog/645049),继续说明SpringMVC的一些用法 


一、业务类的注解定义

     在上一章中,我们用到了 customerservice ,当时我们是在构造函数中明确New出来的,其实在SpringMVC里有更方便的做法。

     1) 在Service类上增加 @Service 注解

     2) 在调用类中使用 @Autowired 进行自动构造

      修改后的代码

CustomerService.java

import org.springframework.stereotype.Service;

@Service
public class CustomerService {

增加如上代码

CustomerController.java 修改为

@Controller
public class CustomerController {
   @Autowired
   private CustomerService serv;

   /*
   public CustomerController() {
       this.serv = new CustomerService();
   } */



在 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

  可以看到一样能获得所有的客户信息。



转载于:https://my.oschina.net/ritchielei/blog/645146

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值