你的位置:首页 > Java教程

[Java教程]Mybatis+Struts2的结合:实现用户插入和查找


  总结一下今天一个成功的小实验:Mybatis+Struts2的结合:实现用户插入和查找。删除和修改如果以后写了,会继续更新。

  一 准备工作。

   1.新建一个java web项目。

   2.在webContent\lib目录下导入所需要的jar包。

     a.struts2需要的jar包。

struts2     xwork-core.jar     strut2-core.jar     ognl.jar     commoms-lang.jar     freemarker.jar     commons-fileupload.jar

      包的位置:

struts-2.3.24.1-all\struts-2.3.24.1\apps\WEB-INF\lib

      我下载的struts2的版本这个目录下有13个jar包,每个jar包的作用网上都可以查到。正常使用加入这六个就可以了。

    b.mybatis需要的的jar包。

      

asm.jarcglib.jarcommons-logging-.jarlog4j.jarmybatis.jarslf4j-api.jarslf4j-log4j12.jar

    c.mysql需要的jar包。

mysql-connector-java-5.1.7-bin.jar

    到此准备工作就做好了。

  二.工程目录    

    在这里我贴出我的工程目录,便于我后面进行描述。

    

    三.写代码。

      对于Java web 工程的搭建,服务器的搭建我就不多说了,因为网上资料很多。(虽然我写的也有很多,但是只是想给自己做一个简单的总结,顺便分享给需要的人) 

      1.webContent\lib\web.

 1 <? 2 <web-app  3  <display-name>MybatisAndStruts2</display-name> 4  <welcome-file-list> 5   <welcome-file>index.jsp</welcome-file> 6  </welcome-file-list> 7  <filter> 8     <filter-name>struts2</filter-name> 9     <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>10  </filter>11 <filter-mapping>12     <filter-name>struts2</filter-name>13     <url-pattern>/*</url-pattern>14  </filter-mapping>15 </web-app>

    2.index.jsp

      

 1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2   pageEncoding="UTF-8"%> 3 <% 4  5 String path = request.getContextPath(); 6 String BasePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 7  8 %> 9  10 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">11 <html>12 <head>13 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">14 <base href="<%=BasePath %>"></base>15 <title>首页</title>16 </head>17 <body>18   <h3 align="center">添加用户</h3>19   <form action="user/user!add">20     <table align="center">21       <tr>22         <td><input type="text" name="username"></td>23       </tr>24       <tr>25         <td><input type="password" name="password"></td>26       </tr>27       <tr>28         <td><input type="submit" value="提交"></td>29       </tr>30     </table>31   </form>32   33   <h3 align="center">查询所有用户</h3>34   <p align="center"><a href="user/user!get">查询</a></p>35 </body>36 </html>

    3. user_add_success.jsp

    

 1 <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 2   pageEncoding="ISO-8859-1"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 7 <title>Insert title here</title> 8 </head> 9 <body bgcolor="#33CC99">10 <h3 align="center">user add success</h3></body>11 </html>

    

    4. user_get.jsp

 

<%@ page language="java" contentType="text/html; charset=UTF-8"  pageEncoding="UTF-8"%>  <%@taglib prefix="s" uri="/struts-tags"%>  <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body bgcolor="#33CC99"><h3 align="center">用户列表</h3></body>  <table align="center">    <tr>      <td>ID</td>      <td>用户名</td>      <td>密码</td>    </tr>        <s:iterator value="users" >        <tr>        <td> <s:property value="id" />    </td>        <td> <s:property value="username" /> </td>         <td> <s:property value="password" /> </td>       </tr>    </s:iterator>   </table></html>

    

 

    5. struts.

 

 

 1 <??> 2 <!DOCTYPE struts PUBLIC 3   "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" 4   "http://struts.apache.org/dtds/struts-2.3.dtd"> 5  6 <struts>   7   <constant name="struts.devMode" value="true" /> 8   <constant name="struts.enable.DynamicMethodInvocation" value="true" /> 9   10   <package name="default" namespace="/user" extends="struts-default">11     <action name="user" class="com.hjj.action.UserAction" >12       <result name="add">13       /user_add_success.jsp14       </result>15       16       <result name="get">17       /user_get.jsp?users=${users}18       </result>19     </action>20   </package>21 </struts>

     

    6. conf.

 

 1 <??> 2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> 3 <configuration> 4   <environments default="development"> 5     <environment id="development"> 6       <transactionManager type="JDBC" /> 7         <dataSource type="POOLED"> 8           <property name="driver" value="com.mysql.jdbc.Driver" /> 9           <property name="url" value="jdbc:mysql://localhost:3306/mybatis" />10           <property name="username" value="root" />11           <property name="password" value="000000" />12         </dataSource>13     </environment>14   </environments>15   <mappers>16       <mapper resource="com/hjj/dao/userMapper./>17   </mappers>18 </configuration>

    7. userMapper.

  

 1 <??>  2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  3 <mapper namespace="com.hjj.dao.userMapper">  4     <select id="getUser" resultType="com.hjj.model.User">  5         select * from user; 6     </select>  7      8     <insert id="insertUser" parameterType="com.hjj.model.User">  9         insert into user (username,password) values (#{username},#{password});10     </insert> 11 </mapper>

    

    8 .User.java

 1 package com.hjj.model; 2  3 public class User { 4    5   private int id; 6   private String username; 7   private String password; 8    9   public User(int id, String username, String password) {10     super();11     this.id = id;12     this.username = username;13     this.password = password;14   }15   public User() {16     super();17     // TODO Auto-generated constructor stub18   }19   20   public int getId() {21     return id;22   }23   public void setId(int id) {24     this.id = id;25   }26   public String getUsername() {27     return username;28   }29   public void setUsername(String username) {30     this.username = username;31   }32   public String getPassword() {33     return password;34   }35   public void setPassword(String password) {36     this.password = password;37   }38   39   @Override40   public String toString() {41     return "User [id=" + id + ", username=" + username + ", password=" + password + "]";42   }43 }

    9. UserAction.java

  

 1 package com.hjj.action; 2  3 import java.io.IOException; 4 import java.util.ArrayList; 5 import java.util.List; 6  7 import com.hjj.dao.MysqlDAO; 8 import com.hjj.model.*; 9 import com.opensymphony.xwork2.ActionSupport;10 import com.opensymphony.xwork2.ModelDriven;11 12 public class UserAction extends ActionSupport implements ModelDriven<User>{13   private User user = null; 14   List<User> users = new ArrayList<User>();15   16   17   public List<User> getUsers() {18     return users;19   }20   21   public void setUsers(List<User> users) {22     this.users = users;23   }24   25   public String add() throws IOException{26     System.out.println(user);27     MysqlDAO dao = new MysqlDAO();28     dao.insertUser(user);    29     return "add";30   }31   32   public String get() throws IOException{33     MysqlDAO dao = new MysqlDAO();34     users = dao.getUsers();35     return "get";36   }37   38   39   public 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; 2  3 import java.io.IOException; 4 import java.io.Reader; 5 import java.util.ArrayList; 6 import java.util.List; 7  8 import 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;12 13 import com.hjj.model.User;14 15 public class MysqlDAO {16   17   private SqlSessionFactory sessionFactory = null;18   private SqlSession session = null;19   20   public MysqlDAO() throws IOException{21     String resource = "conf.; 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();39     40     return users;41   }42   43   public void insertUser(User user){44       45     session = sessionFactory.openSession();46   47     String statement = "com.hjj.dao.userMapper.insertUser";48   49     int row = session.insert(statement, user);50     session.commit();51     System.out.println(row);52   }53 }

  四.运行代码。

  1.地址栏输入:http://localhost:8080/MybatisAndStruts/index.jsp。显示页面如下(页面简单丑陋)。

第一个文本输入框为用户名,第二个为密码。

    2. 提交后页面显示

    

 

        3.返回index.jsp。点击查询。显示列表。

    

    至此,所有的代码和测试已经写完了。这应该算是很简单的一个mybatis和struts的整合了,就当做入门练习了。至于里面的一些东西,例如ModelDriven,和user/user!add这些东西,学过struts2的人应该都知道。不过为了自己能够更深刻的理解,在明天我也会做出总结。