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

网友投稿 221 2023-07-13


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

二、配置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的情况;

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

"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"

"http://struts.apache.org/dtds/struts-2.3.dtd">

json

text/html

.

.

四、配置Mybatis.xml和userMapper.xml,

 配置cacheEnabled为true, 开启二级缓存;

 配置datasource相关信息: type为POOLED-连接池形式,poolMaximumActiveConnections – 在任意时间存在的活动(也就是正在使用)连接的数量,默认值:10。

 配置实体类映射mappers             //

"http://mybatis.org/dtd/mybatis-3-config.dtd">

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

"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

insert into USER(

account,

name,

address

) values (

#{account},

#{name},

#{address}

)

select u.id,

u.account,

u.name,

u.address

from USER u

五、关键代码

 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(FHgdVxnew 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"%>

六、测试效果:

struts2运行正常;

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

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

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

@author   风一样的码农


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java利用Sping框架编写RPC远程过程调用服务的教程
下一篇:第十篇BootStrap轮播插件使用详解
相关文章

 发表评论

暂时没有评论,来抢沙发吧~