GET/POST注解

在之前编写的实际代码中,通过请求获取值的方法都是GET,我在文字里提了一下使用POST也是可以的。

在实际开发中,一般提交表单都是POST请求,很多方法也需要区分接受的POST还是GET请求。

区分GET和POST方法,可以在@RequestMapping的参数中使用method进行设置。如果不在@RequestMapping中显式的设置方法,则这个控制器方法对于GET和POST请求都会进行处理。

从Spring 4.3开始,还引入了@GetMapping@PostMapping两个注解,用于直接标示GET和POST方法,不符合要求的请求就会被忽略。

引入这两个注解主要是因为后边我们要用到的修改数据和新增数据,都要使用POST请求,而显示列表一般使用的是GET请求。

所以现在我们就把显示customer列表的方法改成@GetMapping,在之后编写控制器方法的时候,都会具体指定请求的种类。

@Controller
@RequestMapping(value = "/customer")
public class CustomerController {

    @Autowired
    private CustomerDAO customerDAO;


    <span style="color: red">@GetMapping(value = "/list")</span>
    public String test(Model model) {

        List<Customer> customers = customerDAO.getCustomers();
        for (Customer c : customers) {
            System.out.println(c);
        }
        model.addAttribute("customers", customers);

        return "list-customers";
    }
}

Service层

看最开始的那副架构图,我们直接把DAO对象注入到了控制器对象中。实际并不是这样,而是要再多一层业务层。

由于我们现在的应用比较简单,业务逻辑都在控制层内完成,实际上控制层负责的是视图和与请求之间的交互,而数据处理和业务逻辑,都需要单独在业务层内进行。

通过新增加一层业务层,也将控制层和DAO层彻底分离,方便切换不同的业务和数据组件,还可以通过业务层,同时使用多个DAO层,极大的扩展了Web应用。

于是现在的结构变成:向Service层注入DAO对象,向控制层注入Service层对象。

对于Service对象,Spring也提供了一个注解@Service,同样也继承了@Component注解,和另外两个类似。

现在来创建一个Service类实现的接口,以及一个Service实现类,并注入DAO对象。创建cc.conyli.service包,在其中先编写接口:

package cc.conyli.service;

import cc.conyli.entity.Customer;

import java.util.List;

public interface CustomerService {

    public List<Customer> getCustomers(); 
}

这里的抽象方法也是返回List<Customer>对象,用于继续向控制层返回。

再来编写实现类:

package cc.conyli.service;

import cc.conyli.dao.CustomerDAO;
import cc.conyli.entity.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    private CustomerDAO customerDAO;

    @Override
    @Transactional
    public List<Customer> getCustomers() {
        return customerDAO.getCustomers();
    }
}

@Service注解外加注入CustomerDAO对象对我们来说已经司空见惯了,这里的关键是@Transactional注解被移动到了Service层的方法上,这也是一个传统做法,即一次性完成这个功能。这里就从DAO对象去掉相应的注解,代码就省略了。

然后我们需要修改Controller对象,注入的不再是DAO对象,而是Service对象:

@Controller
@RequestMapping(value = "/customer")
public class CustomerController {

    @Autowired
    private CustomerService customerService;


    @GetMapping(value = "/list")
    public String test(Model model) {

        List<Customer> customers = customerService.getCustomers();
        for (Customer c : customers) {
            System.out.println(c);
        }
        model.addAttribute("customers", customers);

        return "list-customers";
    }
}

在控制层修改注入对象,然后更新一下调用的对象名称即可。重新启动项目,可以发现正常工作了。

这里需要注意Spring的开发组不推荐大家直接使用域注入,还是使用构造器注入比较好,今后编写代码时可以注意一下。

现在我们就按照标准Web应用的控制层-业务层-DAO层创建好了项目结构,剩下的各个功能,就在此基础上继续添加了。