欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

mybatis3.3+struts2.3.24+mysql5.1.22开发环境搭建图文教程

程序员文章站 2024-03-12 15:28:50
一、新建web工程,并在lib目录下添加jar包  主要jar包:struts2相关包,mybatis3.3相关包,mysql-connector-java-5...

一、新建web工程,并在lib目录下添加jar包
 主要jar包:struts2相关包,mybatis3.3相关包,mysql-connector-java-5.1.22-bin.jar, gson-2.1.jar 

mybatis3.3+struts2.3.24+mysql5.1.22开发环境搭建图文教程

二、配置web.xml,添加一个过滤器strutsprepareandexecutefilter,处理所有*.action请求; 

<?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>ms</display-name>
 <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>*.action</url-pattern>
 </filter-mapping>

 <welcome-file-list>
 <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>

</web-app>

查看该过滤器dofilter源码,主要做以下几件事:
 1、判断是否设置了struts排除的url(struts.action.excludepattern,通过正则表达式匹配),如果有且当前路径符合规则,则将请求转发给过滤器链上下一个对象,不交给struts2处理 

if (excludedpatterns != null && prepare.isurlexcluded(request, excludedpatterns)) {
 chain.dofilter(request, response);
} 

2、查找actionmapping:通过prepareoperations的findactionmapping方法查找,如果没找到,则将请求转发给过滤器链上下一个对象,不交给struts2处理;如果找到actionmapping,则调用executeoperations的executeaction方法,开始执行action;下图是根据url找到actionmapping的情况; 

mybatis3.3+struts2.3.24+mysql5.1.22开发环境搭建图文教程

三、配置struts.xml文件,该demo主要演示向前端传json格式数据,result type设成json格式,当然也可以设成其它的;  

<?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="false" />

 <package name="default" extends="struts-default,json-default">
 
  <global-results>
  <result type="json">
  <param name="root">json</param>
  <param name="contenttype">text/html</param>
  </result>
  </global-results>

  <action name="adduser" class="ms.action.useraction" method="adduser">
   <result>.</result>
  </action>
  
  <action name="queryalluser" class="ms.action.useraction" method="queryalluser">
  <result>.</result>
 </action>
 
 </package>

 <!-- add packages here -->

</struts>

四、配置mybatis.xml和usermapper.xml,
 配置cacheenabled为true, 开启二级缓存;
 配置datasource相关信息: type为pooled-连接池形式,poolmaximumactiveconnections – 在任意时间存在的活动(也就是正在使用)连接的数量,默认值:10。
 配置实体类映射mappers             //<mapper resource="ms/model/usermapper.xml"/> 

<?xml version="1.0" encoding="utf-8"?>
<!doctype configuration public "-//mybatis.org//dtd sql map config 3.0//en" 
 "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>


 <settings>
 <!--开启二级缓存-->
 <setting name="cacheenabled" value="true"/>
 </settings>


 <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/demo" />
   <property name="username" value="root" />
   <property name="password" value="admin" />
   <property name="poolmaximumactiveconnections" value="10" />
   <property name="poolpingenabled" value="true"/>
   <property name="poolpingquery" value="select 1 as poolpingquery"/>
  </datasource>
 </environment>
 </environments>
 <mappers>
  <mapper resource="ms/model/usermapper.xml"/>
 </mappers>
</configuration>

配置usermapper.xml,配置缓存为ehcache及相关参数,记得实体类要实现serializable接口 

<?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="usermapper">
 
 <!-- 默认的cache <cache />-->
 <!-- 使用ehcache缓存 -->
 <cache type="org.mybatis.caches.ehcache.loggingehcache" >
 <property name="timetoidleseconds" value="3600"/><!--1 hour 缓存自创建日期起至失效时的间隔时间-->
 <property name="timetoliveseconds" value="3600"/><!--1 hour 缓存创建以后,最后一次访问缓存的日期至失效之时的时间间隔-->
 <property name="maxentrieslocalheap" value="1000"/>
 <property name="maxentrieslocaldisk" value="10000000"/>
 <property name="memorystoreevictionpolicy" value="lru"/> 
 </cache>

 <!-- 新增-->
 <insert id="saveuser" parametertype="ms.model.user">
 insert into user(
 account, 
 name, 
 address
 ) values (
 #{account}, 
 #{name}, 
 #{address}
 )
 </insert>
 
 <select id="queryalluser" resulttype="ms.model.user">
 select u.id,
  u.account,
  u.name,
  u.address
 from user u
 </select>

 
</mapper>

五、关键代码
 dao层:
 首先建一个类,用于获取sqlsessionfactory,设计成单例模式; 

package ms.dao.base;

import java.io.ioexception;

import org.apache.ibatis.io.resources;
import org.apache.ibatis.session.sqlsessionfactory;
import org.apache.ibatis.session.sqlsessionfactorybuilder;
import org.apache.log4j.logger;

public class mysessionfactory {

 private static sqlsessionfactory sessionfactory;
 private mysessionfactory(){
 
 }
 
 public static synchronized sqlsessionfactory getsqlsessionfactory(){
 if(sessionfactory == null){
  try {
  sessionfactory = new sqlsessionfactorybuilder().build(resources.getresourceasreader("mybatis-config.xml"));
  return sessionfactory;
  } catch (ioexception e) {
  logger.getlogger(mysessionfactory.class).error("getsqlsessionfactory error.");
  e.printstacktrace();
  return null;
  }
 }else{
  return sessionfactory;
 }
 }
 
}

接下来是userdao,通过opensession获取sqlsession,注意这里是可以通过sqlsession的commit和rollback进行事务控制的,当然如果本来就一条sql操作,也就没什么事务控制可言了(本例子只是demo); 

package ms.dao;

import java.util.arraylist;
import java.util.list;

import org.apache.ibatis.session.sqlsession;

import ms.dao.base.mysessionfactory;
import ms.model.user;

public class userdao {
 
 public void add(user user) throws exception{
 sqlsession session = mysessionfactory.getsqlsessionfactory().opensession();
 try {
  
  string statement = "usermapper.saveuser";
  session.insert(statement, user);
  session.commit(true);
  
 } catch (exception e) {
  session.rollback(true);
  e.printstacktrace();
  
  throw new exception("error in add method");
 } finally {
  session.close();
 }
  
 }
 
 public list<user> queryalluser() throws exception{
 sqlsession session = mysessionfactory.getsqlsessionfactory().opensession();
 list<user> users = new arraylist<user>();
 try{
  string statement = "usermapper.queryalluser";
  users = session.selectlist(statement,1);
  session.commit(true);
  
 } catch (exception e) {
  session.rollback(true);
  e.printstacktrace();
  throw new exception("error in queryalluser method");
 } finally {
  session.close();
 }
 
 return users;
 }
}

service层:略
 model:略
 action层:
 转成json格式数据返回给前端; 

package ms.action;

import java.io.printwriter;
import java.util.list;

import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;

import ms.model.user;
import ms.service.userservice;

import org.apache.log4j.logger;
import org.apache.struts2.servletactioncontext;

import com.google.gson.gson;

public class useraction {
 logger logger = logger.getlogger(useraction.class);
 private userservice userservice = new userservice();
 public void adduser(){
 printwriter out = null;
 try{
  httpservletrequest request = servletactioncontext.getrequest();
  httpservletresponse response = servletactioncontext.getresponse();
  response.setcontenttype("text/html;charset=utf-8");
  string account = request.getparameter("account");
  string name = request.getparameter("name");
  string address = request.getparameter("address"); 
  user user = new user();
  user.setaccount(account);
  user.setaddress(address);
  user.setname(name);
  userservice.add(user);
  out = response.getwriter();
  out.write(new gson().tojson("success"));
 }catch(exception e){
  e.printstacktrace();
  logger.error(e.getmessage());
  if(out != null)
  out.write(new gson().tojson("fail"));
 }finally{
  out.flush();
  out.close();
 }
 
 }
 
 
 public void queryalluser(){
 printwriter out = null;
 try {
  httpservletresponse response = servletactioncontext.getresponse();
  response.setcontenttype("text/html;charset=utf-8");
 
  gson gson = new gson();
  list<user> userlist= userservice.queryalluser();
  string gsonstr = gson.tojson(userlist);
  
  out = response.getwriter();
  out.write(gsonstr);
 } catch (exception e) {
  e.printstacktrace();
  logger.error(e.getmessage());
  if(out != null)
  out.write(new gson().tojson("fail"));
 }finally{
  out.flush();
  out.close();
 }
 }
}

前端代码: 

<%@ page language="java" contenttype="text/html; charset=utf-8"
 pageencoding="utf-8"%>
<!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>
<style>
.mt20{
 margin-top: 20px;
}
</style>
</head>
<body>

<div style="text-align: center;">
 <div class="mt20"><label>账号:</label><input id="account" type="text"/></div>
 <div class="mt20"><label>姓名:</label><input id="name" type="text"/></div>
 <div class="mt20"><label>地址:</label><input id="address" type="text"/></div>
 <div class="mt20"><button id="adduser" >添加</button></div>
</div>

<h3>用户列表:</h3>
<ul id="userlist">
</ul>

<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>

<script>
 $(function() {
 $.ajax({
  url : 'queryalluser.action',
  type : 'post',
  datatype : 'json',
  success : function(data) {
  try {
  for(var i = 0; i < data.length; i++){
   $("#userlist").append("<li><span style='color:red'>id="+data[i].id+"</span>,account="+data[i].account+",name="+data[i].name+",address="+data[i].address+"</li>");
  }
  } catch (e) {};
  
  }
  ,
  error : function(e) {
  alert("sys error");
  }
 });
 
 $("#adduser").on("click", function() {
 var account = $("#account").val();
 var name = $("#name").val();
 var address = $("#address").val();
 $.ajax({
 url : 'adduser.action',
 type : 'post',
 datatype : 'json',
 data : {
  account : account,
  name : name,
  address : address
 },
 success : function(data) {
  try {
  
  $("#userlist").append("<li>account="+account+",name="+name+",address="+address+"</li>");
  alert("添加成功");
  } catch (e) {

  }
 },
 error : function(e) {
  alert("sys error");
 }
 });

 });
 });
</script>
</body>
</html>

六、测试效果:

struts2运行正常;

mybatis3.3+struts2.3.24+mysql5.1.22开发环境搭建图文教程

测试二级缓存是否ok,查询所有user;

第一次查询:cache未命中,访问数据库:

mybatis3.3+struts2.3.24+mysql5.1.22开发环境搭建图文教程

第二次以及接下来的多次查询,cache命中,没有访问数据库:

mybatis3.3+struts2.3.24+mysql5.1.22开发环境搭建图文教程

@author   风一样的码农

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。