總結一下今天一個成功的小實驗: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.jar
cglib.jar
commons-logging-.jar
log4j.jar
mybatis.jar
slf4j-api.jar
slf4j-log4j12.jar
c.mysql需要的jar包。
mysql-connector-java-5.1.7-bin.jar
到此准備工作就做好了。
二、工程目錄
在這裡我貼出我的工程目錄,便於我後面進行描述。
三.寫代碼。
對於Java web 工程的搭建,服務器的搭建我就不多說了,因為網上資料很多。(雖然我寫的也有很多,但是只是想給自己做一個簡單的總結,順便分享給需要的人)
1.webContent\lib\web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>MybatisAndStruts2</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
2.index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String BasePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!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">
<base href="<%=BasePath %>"></base>
<title>首頁</title>
</head>
<body>
<h3 align="center">添加用戶</h3>
<form action="user/user!add">
<table align="center">
<tr>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td><input type="submit" value="提交"></td>
</tr>
</table>
</form>
<h3 align="center">查詢所有用戶</h3>
<p align="center"><a href="user/user!get">查詢</a></p>
</body>
</html>
3. user_add_success.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body bgcolor="#33CC99">
<h3 align="center">user add success</h3></body>
</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.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<constant name="struts.enable.DynamicMethodInvocation" value="true" />
<package name="default" namespace="/user" extends="struts-default">
<action name="user" class="com.hjj.action.UserAction" >
<result name="add">
/user_add_success.jsp
</result>
<result name="get">
/user_get.jsp?users=${users}
</result>
</action>
</package>
</struts>
6. conf.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
<property name="username" value="root" />
<property name="password" value="000000" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/hjj/dao/userMapper.xml"/>
</mappers>
</configuration>
7. 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.hjj.dao.userMapper">
<select id="getUser" resultType="com.hjj.model.User">
select * from user;
</select>
<insert id="insertUser" parameterType="com.hjj.model.User">
insert into user (username,password) values (#{username},#{password});
</insert>
</mapper>
8 .User.java
package com.hjj.model;
public class User {
private int id;
private String username;
private String password;
public User(int id, String username, String password) {
super();
this.id = id;
this.username = username;
this.password = password;
}
public User() {
super();
// TODO Auto-generated constructor stub
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
}
}
9. UserAction.java
package com.hjj.action;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.hjj.dao.MysqlDAO;
import com.hjj.model.*;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
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.地址欄輸入:http://localhost:8080/MybatisAndStruts/index.jsp。顯示頁面如下(頁面簡單丑陋)。
第一個文本輸入框為用戶名,第二個為密碼。
2. 提交後頁面顯示
3.返回index.jsp。點擊查詢。顯示列表。
至此,所有的代碼和測試已經寫完了。這應該算是很簡單的一個mybatis和struts的整合了,就當做入門練習了。至於裡面的一些東西,例如ModelDriven,和user/user!add這些東西,學過struts2的人應該都知道。不過為了自己能夠更深刻的理解,在明天我也會做出總結。
Struts2學習筆記-Value Stack(值棧)和OGNL表達式 http://www.linuxidc.com/Linux/2015-07/120529.htm
struts2文件上傳(保存為BLOB格式) http://www.linuxidc.com/Linux/2014-06/102905.htm
Struts2的入門實例 http://www.linuxidc.com/Linux/2013-05/84618.htm
Struts2實現ModelDriven接口 http://www.linuxidc.com/Linux/2014-04/99466.htm
遇到的Struts2文件下載亂碼問題 http://www.linuxidc.com/Linux/2014-03/98990.htm
Struts2整合Spring方法及原理 http://www.linuxidc.com/Linux/2013-12/93692.htm
Struts2 注解模式的幾個知識點 http://www.linuxidc.com/Linux/2013-06/85830.htm
Struts 的詳細介紹:請點這裡
Struts 的下載地址:請點這裡