程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> mybatis3.3+struts2.3.24+mysql5.1.22開辟情況搭建圖文教程

mybatis3.3+struts2.3.24+mysql5.1.22開辟情況搭建圖文教程

編輯:關於JAVA

mybatis3.3+struts2.3.24+mysql5.1.22開辟情況搭建圖文教程。本站提示廣大學習愛好者:(mybatis3.3+struts2.3.24+mysql5.1.22開辟情況搭建圖文教程)文章只能為提供參考,不一定能成為您想要的結果。以下是mybatis3.3+struts2.3.24+mysql5.1.22開辟情況搭建圖文教程正文


1、新建Web工程,並在lib目次下添加jar包
 重要jar包:struts2相干包,mybatis3.3相干包,mysql-connector-java-5.1.22-bin.jar, gson-2.1.jar 

2、設置裝備擺設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的情形; 

3、設置裝備擺設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>

4、設置裝備擺設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>

5、症結代碼
 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.谷歌.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 >
 <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>

6、測試後果:

struts2運轉正常;


測試二級緩存能否OK,查詢一切User;

第一次查詢:cache未射中,拜訪數據庫:

第二次和接上去的屢次查詢,cache射中,沒有拜訪數據庫:


@author   風一樣的碼農

以上就是本文的全體內容,願望對年夜家的進修有所贊助,也願望年夜家多多支撐。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved