1. 程式人生 > 其它 >springmvc專案,註解方式配置(四)Demo範例

springmvc專案,註解方式配置(四)Demo範例

技術標籤:spring專案mybatisjavaspring

五、MVC架構Demo範例

springMVC 核心配置完成後,寫個demo範例進行測試。

1、實體類,建立一個簡單的User類,包含姓名和年齡兩個欄位,建立對應的資料庫表

User.java

public class User {
	private String name;
	private int age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
	@Override
	public String toString() {
		return "User [name=" + name + ", age=" + age + "]";
	}
}

建立資料庫對應表,並插入測試的資料,本範例使用oracle資料庫

CREATE TABLE TEST_USER(
  NAME    VARCHAR2(100),
  AGE     NUMBER
)

資料庫表中插入了兩條測試資料

2、DAO層,編寫dao介面類和xml對映檔案

UserDao.java

@Repository
public interface UserDao {
	public List<User> getUserList();
}

UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xxxyyyzzz.app.demo.dao.UserDao">
   
    <select id="getUserList" parameterType="string"
    	resultMap="resultUserList">
    	select * from test_user
    </select>
    
    <resultMap type="com.xxxyyyzzz.app.demo.model.User" id="resultUserList">
    	<result column="name" property="name"/>
    	<result column="age" property="age"/>
    </resultMap> 
</mapper>

3、Service層,編寫service介面類和實現類

UserServcie.java

public interface UserService {
	public List<User> getUserList();
}

UserServiceImpl.java

@Service
public class UserServiceImpl implements UserService {
	
	@Autowired
    private UserDao userDao;
	
	@Override
	public List<User> getUserList() {
		return this.userDao.getUserList();
	}
}

4、Controller層,編寫控制層類

HelloWorldController.java

@Controller
public class HelloWorldController {
	Logger logger = LogManager.getLogger(HelloWorldController.class);
	
	@Autowired
	UserService userServcie;
	
	@RequestMapping(value="/jsontest", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, String> jsontest() {
		logger.info("json 資料繫結測試");
		Map<String, String> results = new HashMap<String, String>();
		results.put("user", "iceher0");
		return results;
	}
	
	@RequestMapping(value="/userList", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, List<User>> listAllUserTest() {
		logger.info("----獲取使用者列表----");
		Map<String, List<User>> results = new HashMap<String, List<User>>();
		List<User> userList = userServcie.getUserList();
		results.put("userlist", userList);
		return results;
	}
}

寫了兩個 demo方法,其中 listAllUserTest 方法測試MVC整個架構各層是否正常執行,jsontest方法簡單測試傳到前臺的 json資料是否正常。