第一步:Spring整合MyBatis

请参考:http://www.moonlightgate.com/archives/88

第二步:将SpringMVC整合进入Spring和MyBatis

  1. 修改UserServiceImpl.java
package com.royotech.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.royotech.dao.PersonDAO;
import com.royotech.entity.Person;
import com.royotech.service.UserService;

@Service
public class UserServiceImpl implements UserService{
    @Autowired
    private PersonDAO personDAO;

    @Override
    public List<Person> select() {
        return personDAO.selectAll();
    }
}
  1. applicationContext.xml头部增加scanner语句。
<context:component-scan base-package="com.royotech.service"></context:component-scan>
  1. web.xml增加filter
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
  1. 撰写controller
package com.royotech.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.royotech.entity.Person;
import com.royotech.service.UserService;

@Controller //作用:将当前类的对象交给Spring工厂创建
@RequestMapping("user")   //请求路径
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("select") //请求路径
    public String select(Model model) {
        List<Person> listPerson = userService.select();
        model.addAttribute("listPerson",listPerson);
        return "forward:/list.jsp";
    }
}
  1. 撰写list.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Welcome!</title>
</head>
<body>
    <c:forEach var="person" items="${listPerson}">
        ${person.id},${person.name},${person.birthday},${person.telephone},${person.address}<br/>
    </c:forEach>
</body>
</html>
  1. 大功告成,测试结果如下:
    file

发表评论

邮箱地址不会被公开。 必填项已用*标注