1 package com.hjj.action; java.io.IOException; 4 import java.util.ArrayList; 5 import java.util.List; com.hjj.dao.MysqlDAO; 8 import com.hjj.model.*; 9 import com.opensymphony.xwork2.ActionSupport; 10 import com.opensymphony.xwork2.ModelDriven; UserAction extends ActionSupport implements ModelDriven<User>{ 13 private User user = null; 14 List<User> users = new ArrayList<User>(); List<User> getUsers() { 18 return users; 19 } setUsers(List<User> users) { 22 this.users = users; 23 } String add() throws IOException{ 26 System.out.println(user); 27 MysqlDAO dao = new MysqlDAO(); 28 dao.insertUser(user); 29 return "add"; 30 } String get() throws IOException{ 33 MysqlDAO dao = new MysqlDAO(); 34 users = dao.getUsers(); 35 return "get"; 36 } User getModel() { 40 if(user == null){ 41 user = new User(); 42 } 43 return user; 44 } 45 46 }
10 . MysqlDAO.java
1 package com.hjj.dao; java.io.IOException; 4 import java.io.Reader; 5 import java.util.ArrayList; 6 import java.util.List; org.apache.ibatis.io.Resources; 9 import org.apache.ibatis.session.SqlSession; 10 import org.apache.ibatis.session.SqlSessionFactory; 11 import org.apache.ibatis.session.SqlSessionFactoryBuilder; com.hjj.model.User; MysqlDAO { SqlSessionFactory sessionFactory = null; 18 private SqlSession session = null; MysqlDAO() throws IOException{ 21 String resource = "conf.xml"; 22 23 Reader reader = Resources.getResourceAsReader(resource); 24 25 sessionFactory = new SqlSessionFactoryBuilder().build(reader); 26 27 } 28 public List<User> getUsers(){ 29 30 List<User> users = new ArrayList<User>(); 31 32 session = sessionFactory.openSession(); 33 34 String statement = "com.hjj.dao.userMapper.getUser"; 35 36 users = session.selectList(statement); 37 38 session.commit(); users; 41 } insertUser(User user){ 44 45 session = sessionFactory.openSession(); 46 47 String statement = "com.hjj.dao.userMapper.insertUser"; row = session.insert(statement, user); 50 session.commit(); 51 System.out.println(row); 52 } 53 }
四.运行代码。
1.地址栏输入::8080/MybatisAndStruts/index.jsp。显示页面如下(页面简单丑陋)。
第一个文本输入框为用户名,第二个为密码。
2. 提交后页面显示
3.返回index.jsp。点击查询。显示列表。