MVC中三层规范写法示例

经常会在web项目中用到MVC模式的写法

C:控制层Controller,负责对请求的url分发到不同的网址,处理请求的入口。
M:规范数据数据成Bean,并负责调用数据库
V:只负责从数据库获取数据,并显示。

此三层的设计充分得将数据显示与数据操作很好的分离开了,是一种极佳的面向对象的设计思路。下面把常见的MVC模式的规范写法总结如下:

model:

public class Question {
    private int id;
    private String title;
    private String content;
    private Date createDate;
    private int userId;
    private int commentCount;
    }

dao:执行SQL语句

@Mapper
public interface QuestionDao {
    String TABLE_NAME =" question ";
    String INSERT_FIELDS=" title,content,user_id,create_date,comment_count ";
    String SELECT_FIELDS =" id, "+INSERT_FIELDS;

    //使用mapper写法
    @Insert({"insert into " +TABLE_NAME+" ( " +INSERT_FIELDS +" ) "+
            "values( #{title} , #{content} , #{userId} , #{createDate}, #{commentCount} )"})
    int addQuestion(Question question);


    List<Question> selectLatestQuestions(@Param("userId") int userId,
                               @Param("offset") int offset,
                               @Param("limit") int limit);
}

service:直接调用dao层即可

@Service
public class QuestionService {

    @Autowired
    QuestionDao questionDao;

    public List<Question> getLatestQuestion(int userId,int offset,int limit){
        return questionDao.selectLatestQuestions(userId,offset,limit);
    }
}

controller:请求的处理,这里需要调用service获取数据并且显示到html中,

@Controller
public class HomeController {
    //日志
    private static final Logger logger= LoggerFactory.getLogger(HomeController.class);

    //引入Service层
    @Autowired
    UserService userService;
    @Autowired
    QuestionService questionService;

    //第一个主页
    @RequestMapping("/home")
    public String home(Model model){

        List<Question> qlist= questionService.getLatestQuestion(0,0,10);

        //直接用vo的数组;本身VO类是一个map
        ArrayList<ViewOfObject> vos =new ArrayList<>();
        for (Question question:qlist){
            ViewOfObject vo=new ViewOfObject();
            //在这里question是由questionService获取list然后遍历得到;
            //而对应的question的user由question.getUerID得到
            //得到userId之后根据UserService中的getUser可以得到user
            vo.set("question",question);
            vo.set("user",userService.getUser(question.getUserId()));
            vos.add(vo);
        }
        model.addAttribute("vos",vos);
        return "home";
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值