1. Create a new web project and add a jar package in the lib directory
Main jar packages: struts2 related package, mybatis3.3 related package, mysql-connector-java-5.1.22-bin.jar, gson-2.1.jar
2. Configure web.xml, add a filter StrutsPrepareAndExecuteFilter, and handle all *.action requests;
<?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 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>
Check the doFilter source code of this filter and do the following:
1. Determine whether the url excluded by struts is set (struts.action.excludePattern, matched by regular expression). If there is and the current path meets the rules, the request will be forwarded to the next object in the filter chain and will not be handed over to struts2 for processing.
if (excludedPatterns != null && prepare.isUrlExcluded(request, excludedPatterns)) { chain.doFilter(request, response);}2. Find ActionMapping: Search through the findActionMapping method of PrepareOperations. If it is not found, the request will be forwarded to the next object in the filter chain and will not be handed over to struts2 for processing; if ActionMapping is found, the executeAction method of ExecuteOperations is called to start executing Action; the following figure is the case of finding ActionMapping based on the url;
3. Configure the struts.xml file. This demo mainly demonstrates the transmission of json format data to the front end, set the result type to json format, and of course it can also be set to other ones;
<?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" method="addUser"> <result>.</result> </action> <action name="queryAllUser" method="queryAllUser"> <result>.</result> </action> </package> <!-- Add packages here --></struts>
4. Configure Mybatis.xml and userMapper.xml,
Configure cacheEnabled to true and enable level 2 cache;
Configuring datasource related information: type is POOLED-connection pool form, poolMaximumActiveConnections has the number of active (that is, in use) connections at any time, the default value is: 10.
Configure entity class mapping 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> <!--Enable Level 2 Cache--> <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>
Configure userMapper.xml, configure cache as EHcache and related parameters, remember that the entity class needs to implement the 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 type="org.mybatis.caches.ehcache.LoggingEhcache" > <property name="timeToIdleSeconds" value="3600"/><!--1 hour The interval between the cache from the date of creation to the time of expiration--> <property name="timeToLiveSeconds" value="3600"/><!--1 hour After the cache is created, the time between the date of the last access to the cache to the time of expiration--> <property name="maxEntriesLocalHeap" value="1000"/> <property name="maxEntriesLocalDisk" value="10000000"/> <property name="memoryStoreEvictionPolicy" value="LRU"/> </cache> <!-- New --> <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. Key code
DAO layer:
First, create a class to obtain SqlSessionFactory and design it into a singleton 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; } } }Next is UserDao, which obtains SqlSession through openSession. Note that transaction control can be performed through SqlSession's commit and rollback. Of course, if there is only one SQL operation, there will be no transaction control (this example is just a 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 layer:
Model: no
Action layer:
Convert to json format data and return it 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 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(); } }}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"><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><label>Account: </label><input id="account" type="text"/></div> <div><label>Name: </label><input id="name" type="text"/></div> <div><label>Address: </label><input id="address" type="text"/></div> <div><button id="addUser" >Add</button></div><h3>User List: </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("added successfully"); } catch (e) { } }, error : function(e) { alert("sys error"); } }); }); }); });</script></body></html>6. Test effect:
struts2 runs normally;
Test whether the secondary cache is OK and query all Users;
First query: cache missed, access the database:
The second and next multiple queries, cache hits, no database access:
@author A wind-like coder
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.