public class UserAction extends ActionSupport implements ModelDriven<User>{
private User user = null;
List<User> users = new ArrayList<User>();
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public String add() throws IOException{
System.out.println(user);
MysqlDAO dao = new MysqlDAO();
dao.insertUser(user);
return "add";
}
public String get() throws IOException{
MysqlDAO dao = new MysqlDAO();
users = dao.getUsers();
return "get";
}
public User getModel() {
if(user == null){
user = new User();
}
return user;
}
}
10 . MysqlDAO.java
package com.hjj.dao;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.hjj.model.User;
public class MysqlDAO {
private SqlSessionFactory sessionFactory = null;
private SqlSession session = null;
public MysqlDAO() throws IOException{
String resource = "conf.xml";
Reader reader = Resources.getResourceAsReader(resource);
sessionFactory = new SqlSessionFactoryBuilder().build(reader);
}
public List<User> getUsers(){
List<User> users = new ArrayList<User>();
session = sessionFactory.openSession();
String statement = "com.hjj.dao.userMapper.getUser";
users = session.selectList(statement);
session.commit();
return users;
}
public void insertUser(User user){
session = sessionFactory.openSession();
String statement = "com.hjj.dao.userMapper.insertUser";
int row = session.insert(statement, user);
session.commit();
System.out.println(row);
}
}
四.运行代码。
1.地址栏输入::8080/MybatisAndStruts/index.jsp。显示页面如下(页面简单丑陋)。
第一个文本输入框为用户名,第二个为密码。
2. 提交后页面显示
3.返回index.jsp。点击查询。显示列表。