The mybatis3.3+struts2.3.24+mysql5.1.22 development environment constructs the picture and text course _java

Source: Internet
Author: User
Tags commit flush getmessage rollback time interval tojson log4j

First, create a new Web project and add a jar pack to the Lib directory
Main jar Packs: Struts2 related packs, mybatis3.3 related packs, Mysql-connector-java-5.1.22-bin.jar, Gson-2.1.jar

Second, configure Web.xml, add a filter strutsprepareandexecutefilter, handle all *.action requests;

 <?xml version= "1.0" encoding= "UTF-8"?> <web-app "xmlns:xsi=" /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> 

View the filter Dofilter source code, mainly to do the following several things:
1, to determine whether the set Struts excluded URL (struts.action.excludePattern, matching through regular expressions), if there is and the current path conforms to the rules, then forward the request to the next object on the filter chain, do not give struts2 processing

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

2, find actionmapping: Through the Prepareoperations findactionmapping method to find, if not found, then forward the request to the next object on the filter chain, do not give struts2 processing If the actionmapping is found, the Executeoperations ExecuteAction method is invoked, the action is started, and the following figure is the actionmapping based on the URL;

Third, configure the Struts.xml file, the demo main demo to the front-end JSON format data, the result type set to JSON format, of course, can also be set to other;

 <?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" Default " extends= "Struts-default,json-default" > <global-results> <result type= "json" > <param name= "root" & gt;json</param> <param name= "ContentType" >text/html</param> </result> </global-results&

  Gt <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> 

Iv. configuring Mybatis.xml and Usermapper.xml,
Configure Cacheenabled to True to turn on level two caching;
Configuration DataSource Related information: type is pooled-connection pool form, poolmaximumactiveconnections– the number of activities (that is, in use) that exist at any time, default value: 10.
Configure entity class mappings 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> <!--turn on level two cache--> <setting name=" cacheenabled "value=" true "/> & lt;/settings> <environments default= "Development" > <environment id= "Development" > <transactionman Ager type= "JDBC"/> <datasource type= "Pooled" > <property name= "Driver" value= "Com.mysql.jdbc.Driver"/&gt
   ; <property name= "url" value= "Jdbc:mysql://localhost:3306/demo"/> <property "name=" username "root"/ > <property name= "password" value= "admin"/> <property name= "poolmaximumactiveconnections" value= "10"/&
   Gt <property name= "poolpingenabled" value= "true"/> <property name= "poolpingquery" value= "Select 1 as PoolPingQue Ry "/> </dataSource> </environment> </environments> <mappers>
  <mapper resource= "Ms/model/usermapper.xml"/> </mappers> </configuration>

 

Configuration usermapper.xml, configuration cache for Ehcache and related parameters, remember entity class to implement Serializable interface

<?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" > <!--default cache <cache/>--> <!--using Ehcache cache--> <cache "O Rg.mybatis.caches.ehcache.LoggingEhcache "> <property name=" timetoidleseconds "value=" 3600 "/><!--1 hour The interval between cache from date of creation to expiration--> <property name= "timetoliveseconds" value= "3600"/><!--1 hour cache was created, Time interval--> <property name= "Maxentrieslocalheap" value= "1000"/> <property "Name=" when last accessed cache date to expiration Maxentrieslocaldisk "value=" 10000000 "/> <property name=" Memorystoreevictionpolicy "value=" LRU "/> </ cache> <!--add--> <insert id= "Saveuser" parametertype= "Ms.model.User" > INSERT into User (account, NA Me, address) VALUES (#{account}, #{name}, #{address}) </insert> <select id= "Queryalluser" RESULTT Ype= "Ms.model.User" > SeleCT u.id, U.account, U.name, u.address from USER u </select> </mapper>

 

V. Key codes
DAO Layer:
First, a class is built to obtain the sqlsessionfactory, which is designed as a single case pattern.

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
 }}
 


The next step is Userdao, which obtains sqlsession through opensession, and note that this can be controlled through sqlsession commit and rollback, of course, if it was a SQL operation, There is no control over the matter (this example is only 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.getsqlsessio
 Nfactory (). 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.getsqlsessionfa
 Ctory (). 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 to users;

 }
}

Service layer: Slightly
Model: Slightly
Action Layer:
Turn the JSON format data back to the front end;

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 = 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 = 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 ();

 }
 }
}

Front-End Code:

<%@ 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" >  

Six, Test effect:

Struts2 operation is normal;


Test level Two cache OK, query all user;

First query: Cache misses, accessing database:

Second and next multiple queries, cache hits, no database access:


@author the wind of the farmer

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.