0
我對myBatis和JSP相當陌生。我處於學習階段,想要知道一件簡單的事情。我在mySQL中有一個表格書,並且能夠使用myBatis對它進行基本操作。但我想要將數據顯示在JSP頁面中。使用myBatis在JSP中顯示數據庫數據
下面是代碼:
Book.java
package ibatis;
public class Book {
private int id;
private String author;
private String title;
private String year;
private String remark;
//Getters and Setters
}
是book.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMap
PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap namespace="Book">
<typeAlias alias="Book" type="ibatis.Book"/>
<select id="selectAllBooks" resultClass="ibatis.Book">
select * from books
</select>
</sqlMap>
sqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
<sqlMapConfig>
<transactionManager type="JDBC" commitRequired="false">
<dataSource type="SIMPLE">
<property name="JDBC.Driver" value="com.mysql.jdbc.Driver"/>
<property name="JDBC.ConnectionURL"
value="jdbc:mysql://localhost:3306/books"/>
<property name="JDBC.Username" value="root"/>
<property name="JDBC.Password" value=""/>
</dataSource>
</transactionManager>
<sqlMap resource="ibatis/Book.xml"/>
</sqlMapConfig>
Main.java
package ibatis;
import java.io.IOException;
import java.io.Reader;
import java.sql.SQLException;
import java.util.List;
import org.apache.ibatis.io.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
public class Main {
public static void main(String[] args)
throws IOException, SQLException {
Reader reader = Resources.getResourceAsReader("sqlMapConfig.xml");
SqlMapClient sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
System.out.println("List of all Books");
@SuppressWarnings("unchecked")
List<Book> books = (List<Book>)sqlMap.queryForList("selectAllBooks");
for (Book a : books) {
System.out.println(a.getAuthor() + " : " + a.getTitle());
}
}
}
這是一個基本的MyBatis的Java程序。任何建設jsp頁面的步驟將不勝感激。
我打算使用Spring MVC框架。你能指導我如何完成它? – user2339071
看看這個github項目對你有幫助https://github.com/lorcanluo/spring-mvc-mybatis-tpl –