之前只是编写了Mapper接口的方法,现在来写控制层和业务层的代码
AccountController实现保存和查询全部的功能
package com.lh.controller;
import com.lh.domain.Account;
import com.lh.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.io.IOException;
import java.util.List;
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accountService;
//保存
@RequestMapping(value = "/save", produces = "text/html;charset=UTF-8")
@ResponseBody
public String save(Account account) throws IOException {
accountService.save(account);
return "保存成功!";
}
@RequestMapping("findAll")
//查询
public ModelAndView findAll() throws IOException {
List<Account> accountList = accountService.findAll();
ModelAndView mv = new ModelAndView();
mv.addObject("accountList",accountList);
mv.setViewName("accountList");
return mv;
}
}
业务层AccountServiceImpl实现保存和查询全部,其中AccountMapper由Spring容器帮我们为mapper创建实现类并注入
package com.lh.service.impl;
import com.lh.domain.Account;
import com.lh.mapper.AccountMapper;
import com.lh.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountMapper accountMapper;
@Override
public void save(Account account){
accountMapper.save(account);
}
@Override
public List<Account> findAll(){
List<Account> all = accountMapper.findAll();
return all;
}
}
测试:
将项目部署至tomcat并启动tomcat
输入http://localhost/account/findAll