Configure the simplest web with springmvc+mybatis+ transaction control +json

Source: Internet
Author: User
Tags aop

Note: This article was reprinted from: https://www.cnblogs.com/sdjnzqr/p/3816944.html, the copyright belongs to all of them.

Now organize the configuration files as follows:

The directory structure is as follows:

1.web.xml

<?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" xmlns:web= "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi: schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id= "Webapp_ ID "version=" 2.5 "> <display-name>standard</display-name> <context-param> <param-name&    Gt;webapprootkey</param-name> <param-value>standard.root</param-value> </context-param> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpa th:log4j.properties</param-value> </context-param> <context-param> <param-name>contex tconfiglocation</param-name> <param-value> Classpath*:applicationcontext.xml </par Am-value> </context-param> <filteR> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework .web.filter.characterencodingfilter</filter-class> <init-param> &LT;PARAM-NAME&GT;ENCODING&L    t;/param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/* </url-pattern> </filter-mapping> <servlet> <servlet-name>dispatcherservlet</servle T-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> < Init-param> <param-name>contextConfigLocation</param-name> <param-value>classpa        th:standard-context.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>dIspatcherservlet</servlet-name> <url-pattern>*.json</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> & Lt;/listener> <listener> <listener-class>org.springframework.web.context.contextloaderlistener&lt ;/listener-class> </listener> <welcome-file-list> <welcome-file>index.html</welcome-f Ile> </welcome-file-list></web-app>

2.applicationcontext.xml

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:tx= " Http://www.springframework.org/schema/tx "xmlns:context=" Http://www.springframework.org/schema/context "xmlns: Util= "Http://www.springframework.org/schema/util" xsi:schemalocation= "http://www.springframework.org/schema/ Beans Http://www.springframework.org/schema/beans/spring-beans-3.0.xsd Http://www.springframework.org/schema        /tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP        Http://www.springframework.org/schema/aop/spring-aop-2.5.xsd Http://www.springframework.org/schema/context Http://www.springframework.org/schema/context/spring-context-3.0.xsd Http://www.springframework.org/schema/util  Http://www.springframework.org/schema/util/spring-util.xsd ">  <!--added filtering configuration to make MyBatis transactions work--<context:component-scan base-package= "Cn.telchina.standard" > & Lt;context:exclude-filter type= "Annotation" expression= "Org.springframework.stereotype.Controller"/> </        context:component-scan> <context:property-placeholder location= "Classpath*:jdbc.properties" Ignore-resource-not-found= "true" system-properties-mode= "OVERRIDE" ignore-unresolvable= "true"/> <!-- Jdbc.propertis Directory--<!--define a database connection to the primary database--<bean id= "DataSource" class= "Com.mchange.v2.c3p0.Combo Pooleddatasource "destroy-method=" Close "> <property name=" Driverclass "> <value>${j dbc.driver}</value> </property> <property name= "Jdbcurl" > <value>${jdbc.u rl}</value> </property> <property name= "user" > <value>${jdbc.user}</va Lue> </property> &LT;property name= "Password" > <value>${jdbc.password}</value> </property> </bea  n> <bean id= "sqlsessionfactory" class= "Org.mybatis.spring.SqlSessionFactoryBean" > <property Name= "DataSource" ref= "DataSource"/> <property name= "typealiasespackage" value= "cn.telchina.standard.entity "/> <property name=" configlocation "value=" Classpath:mybatisConfig.xml "></property> &LT;PR Operty name= "mapperlocations" value= "Classpath*:sql-mappers/*.xml"/> </bean> <!--scan the directory in the scan mode In the Com/hoo/mapper directory, all mapper inherit the interface of the Sqlmapper interface so that a bean is available--<bean class= " Org.mybatis.spring.mapper.MapperScannerConfigurer "> <property name=" basepackage "value=" Cn.telchina.standard.mapper "/> </bean> <!--The transaction configuration of the primary database with the default policy--<bean id=" Transactionman Ager "class=" Org.springframework.jdbc.datasource.DataSourceTransactionManagEr "> <property name=" dataSource "ref=" DataSource "/> </bean> <tx:annotation-driven Transact Ion-manager= "TransactionManager"/></beans>

3.standard-context.xml

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:tx= " Http://www.springframework.org/schema/tx "xmlns:mvc=" Http://www.springframework.org/schema/mvc "xmlns:context= "Http://www.springframework.org/schema/context" xmlns:util= "Http://www.springframework.org/schema/util" XSI:SC hemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.0.xsd Http://www.springframework.org/schema/tx Http://www.springframework.org/schema/tx/sprin G-tx-3.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/spring-aop- 2.5.xsd Http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.x SD Http://www.springframework.org/schema/conText Http://www.springframework.org/schema/context/spring-context-3.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SC Hema/util http://www.springframework.org/schema/util/spring-util.xsd > <!--spring will scan all classes under the package path and will have annotations defined Bean for automatic assembly and implementation of automatic dependency injection between beans, Chengguan project personnel do not need to modify-<!--boot package scanning function, in order to register with @controller, @Service, @repository, @ The annotated classes such as component become spring beans--<!--filter configuration is added to make MyBatis transactions work--<context:component-scan BASE-PA Ckage= "Cn.telchina.standard" > <context:exclude-filter type= "annotation" expression= "Org.springframework.s Tereotype.  Service "/> </context:component-scan> <context:annotation-config/> <!-- Start the note-driven Spring MVC feature, register the request URL and annotate the Pojo class method mapping-<mvc:annotation-driven/> <!--if the block "/" is configured in Web. XML,         You need to configure the static file under/scripts <mvc:resources mapping= "/scripts/**" location= "/scripts/"/>-- <!--annotation default method mappingInjection adapter <bean id= "handlermapping" class= "Org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandl Ermapping "/> <bean id=" Handleradapter "class=" Org.springframework.web.servlet.mvc.annotation.AnnotationM Ethodhandleradapter "/>--></beans>

4.mybatisconfig.xml

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE configuration Public "-//mybatis.org//dtd Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-config.dtd" >&          Lt;configuration> <!--Configure MyBatis cache, lazy load and so on a series of properties-<settings> <!--Global Mapper enable Cache-- <setting name= "cacheenabled" value= "true"/> <!--query, close associated objects instant load to improve performance--<settin G Name= "lazyloadingenabled" value= "true"/> <!--sets the form of the associated object loading, where the field is loaded on demand (the Load field is specified by SQL) and all fields of the associated table are not loaded to improve performance--&G          T          <setting name= "aggressivelazyloading" value= "false"/> <!--for unknown SQL queries, allows different result sets to be returned to achieve a common effect--  <setting name= "multipleresultsetsenabled" value= "true"/> <!--allows column labels to be used instead of column names--<setting          Name= "Usecolumnlabel" value= "true"/> <!--allows the use of custom primary key values (such as the program-generated UUID 32-bit encoding as the key value), the data table's PK generation policy will be overwritten- <!--<setting name= "Usegeneratedkeys" value= "true"/>-<!--gives nested resultmap with field-property mapping support--<setting name= "Automappingbehavior" value= "full"/> <!-- Cache SQL for bulk update operations to improve performance-<setting name= "Defaultexecutortype" value= "batch"/> <!--database for more than 25,000 seconds  Timeout is still not responding--<setting name= "defaultstatementtimeout" value= "25000"/> </settings> <!--              Global alias settings, only write aliases in the mapping file, without having to write the entire classpath-<!--<typeAliases> <typealias alias= "Testbean" Type= "Com.wotao.taotao.persist.test.dataobject.TestBean"/> </typeAliases>-<!--non-annotated SQL mapping file Configuration, if you use the MyBatis annotation, the mapper does not need to be configured, but if the MyBatis annotation contains @resultmap annotations, then mapper must be configured to use Resultmap annotations-<!--&LT;MAPPERS&G          T <mapper resource= "Com/mybatis/mapper/usermapper.xml"/> </mappers>--></configuration>

5.*mapper.xml

<?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= "Cn.telchina.standard.mapper.UserMapper" >    <!--can only use "${variable}" in the way that "#{variable}" is not used, ${variable A direct display of incoming data is generated in SQL. -    <!--<![ Cdata[sql]]>  Try every SQL must write to prevent some special characters from damaging the SQL statement--    <select id= "GetUser" resulttype= "Sysusermodel" >        SELECT * from Sys_user where usercode= #{usercode}    </select>         <insert id= "Insertuser" Parametertype= "Sysusermodel" >        insert INTO Sys_user             (id,usercode,password)        values             (#{id},# {Usercode},#{password})      </insert></mapper>

6.javabean.java

Package Cn.telchina.standard.entity;import Java.util.date;public class Sysusermodel {    //number    private int id;    User code    private String usercode;    User Password    private String PassWord;        public int getId () {        return ID;    }    public void setId (int id) {        this.id = ID;    }    Public String Getusercode () {        return usercode;    }    public void Setusercode (String usercode) {        this.usercode = Usercode;    }    Public String GetPassword () {        return passWord;    }    public void SetPassword (String passWord) {        This.password = PassWord;    }}

7.mapper.java

Package Cn.telchina.standard.mapper;import Cn.telchina.standard.entity.sysusermodel;public Interface UserMapper { Public    Sysusermodel GetUser (String usercode);    public void Insertuser (Sysusermodel usermodel);

8.service.java

Package Cn.telchina.standard.model1.service;import Java.util.random;import Org.apache.log4j.logger;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.service;import Org.springframework.transaction.annotation.transactional;import Cn.telchina.standard.entity.sysusermodel;import Cn.telchina.standard.mapper.UserMapper; @Servicepublic class Testservice {    @Autowired    private Usermapper Usermapper;    Logger log = Logger.getlogger (This.getclass ());    @Transactional (rollbackfor=exception.class) public    void Dboperate ()  {        Sysusermodel Usermodel = Usermapper.getuser ("admin");        Log.info (Usermodel);        int i= (new Random ()). Nextint (+);        Usermodel.setid (i);        Usermodel.setusercode (Usermodel.getusercode () + i);        Usermapper.insertuser (Usermodel);//        if (true) {//            throw new RuntimeException ("Exception test"),//        }}}    

9.controller.java

Package Cn.telchina.standard.model1.controller;import Java.util.hashmap;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.controller;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.responsebody;import Cn.telchina.standard.model1.service.TestService; Import Com.alibaba.fastjson.JSON; @Controllerpublic class TestController {        @Autowired    private Testservice Testservice;    @ResponseBody    @RequestMapping ("/test") public    String getjsonstring (String para1,string para2)  {                Testservice.dboperate ();                hashmap<string,string> user = new hashmap<string,string> ();        User.put ("Para1", para1);        User.put ("Para2", para2);        return json.tojsonstring (user);}    }

10.html file

$ (function () {        $ (' #send '). Click (function () {            $.ajax ({                type: "GET",                URL: "Test.json",                data: { PARA1: "Para1", Para2: "Para2"},                DataType: "JSON",                success:function (data) {                    console.log (data);                }            );        });    });

Configure the simplest web with springmvc+mybatis+ transaction control +json

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.