Build Springmvc+mybatis project based on MAVEN (3)

Source: Internet
Author: User
Tags tld knowledge base

| From the college entrance examination to the programmer csdn daily 20170620--"Find a good job, talk about a good salary" June Newsletter | The most popular SQL starter book heavyweight upgrade

    start from scratch based on MAVEN build Springmvc+mybatis project (3)Tags: javamavenspring mvcmybatis2016-07-26 10:06 42087 People read Comments (2) favorite report This article has been included in: Java Knowledge Base     
Classification:JAVA () Author of similar articles X

    Copyright NOTICE: Welcome Reprint, Reproduced please keep the original link.

    Following the above, this section describes the MyBatis-based query and paging features, and presents a customized paging label that can be reused to simplify the development of JSP pages.

    Read the portal from the beginning

    In the previous section, we've built the project's infrastructure using MAVEN, including a parent project petstore-parent and the database Persistence module petstore-persist and the Web site Petstore-web, Now let's add some features to Petstore-web. For starters, the more complex problem that might come up first is paging, so start by solving it.

    Take a look at the finished effect:

    The above is the four optional query criteria that the user can combine to set the query criteria.

    In the middle is a qualifying data presentation table that can be modified and deleted for query results, but is not implemented at this stage.

    At the bottom is a pager bar, which is implemented with custom tag technology that can be reused on multiple JSP pages.

    Here are the key steps and code. The first is the Petstore-persist module, the directory structure is as follows:

    Product.java is an ordinary Java Bean, which is skipped here. There are two methods defined in Productmapper.java:

    Package Com.example.petstore.persist.model;import Java.util.list;import Org.apache.ibatis.annotations.Param; Public interface Productmapper {/** * Query the total number of records that meet the criteria * @param ID * @param name * @param fromprice * @param toprice * @return */int Matches (@Param (value= "id") int ID, @Param (value= "name") String name, @Param (value= "Fromprice") float Fromprice, @  Param (value= "Toprice") float toprice)/** * Query records by query criteria and pagination criteria * @param ID * @param name * @param fromprice * @param toprice * @param fetchindex * @param fetchcount * @return */list<product> findproducts (@Param (value= "id") int ID, @Param (VA Lue= "name") String name, @Param (value= "Fromprice") float Fromprice, @Param (value= "Toprice") float Toprice, @Param (value = "Fetchindex") int fetchindex, @Param (value= "fetchcount") int fetchcount);}
    When used, first call the matches method to get the total number of records that match the criteria, then calculate the limit offset and number of records for the read data based on the number of records displayed per page and the current page count, and then call the Findproducts method to read the data. The parameters of the two methods use @param annotations, such as the @param (value= "id") int ID, which can be used in the mapping file in the format of the #{id}.

    Add SQL mappings for two methods in Product.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= "Com.example.petstore.persist.model.ProductMapper" ><resultmap type= " Com.example.petstore.persist.model.Product "id=" Productmap "><id column=" p_id "property=" id "/><result Column= "P_name" property= "name"/><result column= "P_price" property= "Price"/></resultmap><select Id= "matches" resulttype= "int" >select count (*) from t_product<where><if test= "id>0" >p_id=#{id}< /if><if test= "Name!=null and name!=" ">and Locate (#{name},p_name) >0</if><if test=" FromPrice >-1 ">and p_price>=#{fromprice}</if><if test=" toprice>-1 ">and p_price<=#{toPrice}</ If></where></select><select id= "findproducts" resultmap= "Productmap" >select * from T_product <where><if test= "Id>0" >p_id=#{id}</if><ifTest= "Name!=null and name!=" ">and Locate (#{name},p_name) >0</if><if test=" Fromprice>-1 ">and p_ Price>=#{fromprice}</if><if test= "Toprice>-1" >and p_price<=#{toprice}</if></where >limit #{fetchindex},#{fetchcount}</select></mapper>

    You can see the above two methods, that is, the <where><if> and other elements to assemble the query SQL. One of the advantages of MyBatis is the straightforward use of SQL syntax, which is very easy to get started with the SQL Foundation.

    Enter the Petstore-web module below, first look at the overall structure:

    Where Com.example.petstore.web.tag.PagingTag.java is the paging label class, the key code:

    private int pageIndex = 1;  Current page private int pageSize = 20;  Default number of rows per page private int pagecount = 0;  Total pages recorded private int itemCount = 0;  Record total number of bars private int numcount = 10; Number of page bar numbers navigation links @overridepublic void Dotag () throws Jspexception, IOException {jspwriter out = This.getjspcontext (). getout (); Out.write ("<script type=\" text/javascript\ ">function navigatorpage (pageIndex) {document.getElementById (' PageIndex '). Value = Pageindex;document.forms[0].submit ();} </script> ") out.write (" per page "); Out.write (" <select id= ' pageSize ' name= ' pageSize ' onchange= " + PageIndex + ") ' >") out.write ("<option value= ' 5 '" + (pageSize = = 5?) "Selected= ' true '": "") + ">5</option>") out.write ("<option value= '" + (pageSize = = ten? "Selected= ' true ') ":" ") +" >10</option> "), Out.write (" <option value= ' "+ (pageSize = =)" Selected= ' true ' ":" ") +" >2 0</option> "); Out.write (" <option value= ' "+ (pageSize = = 50?) "Selected= ' true '": "") + ">50&Lt;/option> "); Out.write (" <option value= ' "+ (pageSize = = 100?) "Selected= ' true '": "") + ">100</option>") out.write ("<option value=" + (pageSize = =) "Selected= ' t Rue ' ":") + ">500</option>"); Out.write ("</select>"); Out.write ("Bar     "); o Ut.write (PageIndex + "/" + PageCount + "page     ") out.write ("Total" + itemCount + "record    & nbsp; "); O Ut.write ("<input type= ' button ' value= ' first page ' onclick= ' javascript:navigatorpage (1); '" + (PageIndex > 1?) "": "Disabled= ' true '") + "/>  "); Out.write ("<input type= ' button ' value= ' prev ' onclick= ' javascript: Navigatorpage ("+ (pageIndex-1) +"); ' "+ (PageIndex > 1?" ":" Disabled= ' true ' ") +"/>   ");//digital navigation bar in  T Istartindex = 1;int Iendindex = pagecount;if (PageCount <= numcount) {} else if ((PageIndex + (Numcount + 1)/2) >        PageCount) {Istartindex = PageCount-(numCount-1); iendindex = PageCount; } else if (pageiNdex <= (numcount + 1)/2) {iendindex = Numcount;            } else {if (numcount% = = 2 = 0) {istartindex = PAGEINDEX-NUMCOUNT/2;            Iendindex = PageIndex + (numCount-1)/2;            } else {istartindex = PAGEINDEX-NUMCOUNT/2;            Iendindex = PageIndex + numcount/2; }}for (int i = istartindex; I <= iendindex; i++) {if (i = = PageIndex) {out.write ("<strong>" + i + "</str ong>   ");} else {out.write ("<a href= ' javascript:navigatorpage (" + i + "); ' > "+ i +" </a>   ");}}  Out.write ("<input type= ' button ' value= ' Next ' onclick= ' Javascript:navigatorpage (" + (PageIndex + 1) + "); '" + (PageIndex < PageCount? "": "Disabled= ' true '") + "/>  "); Out.write ("<input type= ' button ' value= ' last page ' onclick= ' javascript: Navigatorpage ("+ PageCount +"); ' "+ (PageIndex < PageCount?" ":" Disabled= ' true ' ") +"/> "); Out.write (" <inpu T type= ' hidden ' id= 'PageIndex ' name= ' pageIndex ' value= ' + pageIndex + '/> ');} 
    Next you need a label profile to declare how this tag is used.

    Create a directory TLD under Web-inf, and then add Pagingtag.tld, as follows:

    <?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE taglib Public "-//sun Microsystems, Inc.//dtd JSP Tag Library 1.2//en" "Http://java.sun.com/dtd/web-jsptaglibrar Y_1_2.dtd "><taglib><tlib-version>2.0</tlib-version><jsp-version>1.2</jsp-version ><short-name>Paging</short-name><uri>http://blog.csdn.net/autfish/tag/</uri>< Display-name>paging tag</display-name><description>paging Tag Library</description><tag ><name>pagingtag</name><tag-class>com.example.petstore.web.tag.pagingtag</tag-class ><body-content>empty</body-content><description>create Navigation for Paging</description ><attribute><name>pageindex</name><rtexprvalue>true</rtexprvalue></ attribute><attribute><name>pagesize</name><rtexprvalue>true</rtexprvalue>< /attribute><attribute><name>pagecount</name><rtexprvalue>true</rtexprvalue></attribute><attribute><name>itemcount</name> <rtexprvalue>true</rtexprvalue></attribute></tag></taglib>
    Note that the URI element here does not need to configure a real-presence URL, but the URI should remain unique in your classpath and cannot be used by other components.

    Enable this tag in Web. xml:

    <jsp-config><taglib><taglib-uri>http://blog.csdn.net/autfish/tag/</taglib-uri>< Taglib-location>/web-inf/tld/pagingtag.tld</taglib-location></taglib></jsp-config>
    Use in JSP:

    <%@ taglib prefix= "My" uri= "http://blog.csdn.net/autfish/tag/"%>
    <my:pagingtag pageindex= "${contentmodel.pageindex}" pagesize= "${contentmodel.pagesize}" pageCount= "${ Contentmodel.pagecount} "itemcount=" ${contentmodel.itemcount} "/>
    For the assignment of four attributes, Contentmodel is an instance of the Paginglist.java class that is used to assist paging, which consists of a paging property and a data table, populates the controller with data, and passes it to the view JSP. The properties are as follows:

    private int pageIndex = 1;private int pageSize = 20;private int pagecount = 0;private int itemCount = 0;private list<t& Gt Items
    Controller code:

     @Controller @requestmapping ("/product") public class Productcontroller {@ Autowiredprivate Productservice Productservice; @RequestMapping (value= "/list") public String listproduct (model model, @ModelAttribute ("Searchmodel") Searchmodel Formmodel, @RequestParam (Value=paginglist.page_index_name, DefaultValue = "1") int pageIndex, @RequestParam (Value=paginglist.page_size_name, defaultvalue= ") int pageSize) {int id = 0; String name = ""; float Fromprice = -1;float Toprice = -1;if (Formmodel! = NULL) {id = numberutils.toint (Formmodel.getid (), 0); name = Formmodel.getname (); fromprice = Numberutils.tofloat (Formmodel.getfromprice (),-1); Toprice = Numberutils.tofloat (Formmodel.gettoprice (),-1);} Model.addattribute ("Searchmodel", Formmodel); paginglist<product> Contentmodel = this.productService.findProducts (ID, name, Fromprice, Toprice, PageIndex, pageSize) Model.addattribute ("Contentmodel", Contentmodel); return "Product/list";}} 
    The controller injects an instance of Productservice to manage the invocation of the persistence layer, the main code is as follows:

    @Servicepublic class Productservicestdimpl implements Productservice {@Autowiredprivate Productmapper productmapper;@ Overridepublic paginglist<product> findproducts (int id, String name,float fromprice, float toprice, int pageIndex, int pageSize) {int total = this.productMapper.matches (ID, name, fromprice, toprice); int pagecount = total% PageSize = = 0 ?  Total/pagesize:total/pagesize + 1;if (PageIndex > PageCount) pageIndex = Pagecount;int Fetchindex = (pageIndex-1) * Pagesize;int Fetchcount = fetchindex + pageSize > total? (Total-fetchindex): pageSize; list<product> list = this.productMapper.findProducts (ID, name, Fromprice, Toprice, Fetchindex, Fetchcount); paginglist<product> paging = new paginglist<product> ();p aging.setitemcount (total);p Aging.setpagecount ( PageCount);p Aging.setpageindex (pageIndex);p aging.setpagesize (pageSize);p aging.setitems (list); return paging;}}

    Limited to space, can not be all the source code one by one paste, interested in downloading the source code.

    Run the Petstore-web module in a Web container, such as Tomcat, with http://localhost:8080/petstore-web/product/list access, and then see the beginning of the picture. If there is an error, compare the code to check the differences.

    Summarize

    The use of paging query function frequently, and the development is more complex, on-demand customization of a reusable set of paging components to improve the development efficiency of a great help. In the next section we continue to improve the Web module, adding additions and deletions and permissions control functions.

    Download the source code in this section

    Start from scratch based on MAVEN build Springmvc+mybatis project (1) Build Springmvc+mybatis project from scratch based on MAVEN (2) Build Springmvc+mybatis project from scratch based on MAVEN (3) Start from scratch based on MAVEN build Springmvc+mybatis project (4)

    Build Springmvc+mybatis project based on MAVEN (3)

    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.