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

一、新建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开发环境搭建图文教程_第1张图片

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



 MS
 
 struts2
 org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
 

 
 struts2
 *.action
 

 
 index.jsp
 



查看该过滤器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开发环境搭建图文教程_第2张图片

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






 

 
 
  
  
  json
  text/html
  
  

  
   .
  
  
  
  .
 
 
 

 



四、配置Mybatis.xml和userMapper.xml,
 配置cacheEnabled为true, 开启二级缓存;
 配置datasource相关信息: type为POOLED-连接池形式,poolMaximumActiveConnections �C 在任意时间存在的活动(也就是正在使用)连接的数量,默认值:10。
 配置实体类映射mappers             // 






 
 
 
 


 
 
  
  
   
   
   
   
   
   
   
  
 
 
 
  
 


配置userMapper.xml,配置缓存为EHcache及相关参数,记得实体类要实现Serializable接口 




 
 
 
 
 
 
 
 
  
 

 
 
 insert into USER(
 account, 
 name, 
 address
 ) values (
 #{account}, 
 #{name}, 
 #{address}
 )
 
 
 

 


五、关键代码
 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 queryAllUser() throws Exception{
 SqlSession session = MySessionFactory.getSqlSessionFactory().openSession();
 List users = new ArrayList();
 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 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"%>




Insert title here




用户列表:

六、测试效果:

struts2运行正常;

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

测试二级缓存是否OK,查询所有User;

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

mybatis3.3+struts2.3.24+mysql5.1.22开发环境搭建图文教程_第4张图片

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

mybatis3.3+struts2.3.24+mysql5.1.22开发环境搭建图文教程_第5张图片

@author   风一样的码农

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

你可能感兴趣的:(mybatis3.3+struts2.3.24+mysql5.1.22开发环境搭建图文教程)