130 |
131 |
132 |
133 | Show entries
134 |
135 |
136 |
137 | Show entries
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Thymeleaf Spring Data Dialect
2 | Data pagination made easy with thymeleaf and spring data.
3 |
4 | This is a dialect for Thymeleaf that provides some attributes to create pagination and sorting elements, bootstrap style, based on Spring Data.
5 |
6 | Usage
7 | -----
8 |
9 | Maven dependency:
10 | ```xml
11 |
12 | io.github.jpenren
13 | thymeleaf-spring-data-dialect
14 | 3.6.0
15 |
16 | ```
17 |
18 | Add the Spring Data dialect to your existing Thymeleaf template engine:
19 |
20 | ```java
21 | templateEngine.addDialect(new SpringDataDialect()); // This line adds the dialect to Thymeleaf
22 | ```
23 |
24 | If using Spring Boot you can add the following line and the ThymeleafAutoConfiguration class will add the dialect to the template engine.
25 | ```java
26 | @Bean
27 | public SpringDataDialect springDataDialect() {
28 | return new SpringDataDialect();
29 | }
30 | ```
31 |
32 | This will introduce the `sd` namespace, and the new attribute processors that
33 | you to use in your pages: `pagination`, `pagination-sort`, `pagination-summary`,
34 | `pagination-url`, `page-object`, `pagination-qualifier` and `page-size-selector`.
35 |
36 | Examples
37 | --------
38 | In your @Controller
39 | ```java
40 | @RequestMapping("/users")
41 | public String list(ModelMap model, @SortDefault("username") Pageable pageable){
42 | model.addAttribute("page", userService.find(pageable));
43 |
44 | return "users/list";
45 | }
46 | ```
47 |
48 | Your html page looks like:
49 | ```html
50 |
218 | ```
219 |
220 | 
221 |
222 | By default SpringDataDialect search in the request for the attribute "page" or if one attribute of type org.springframework.data.domain.Page> exists. To use another model attribute, use sd:page-object="${attrName}"
223 |
224 | To specify the pagination url use `sd:pagination-url` tag:
225 | ```html
226 |
233 | ```
234 |
235 | Sort Icons
236 | ----------
237 | The generated HTML has the CSS classes `sorted`, `sorted-asc` and `sorted-desc`. This allows you to quite easily add some custom CSS to have sort icons in the table headers.
238 |
239 | Example with FontAwesome:
240 | ```
241 | table.table thead .sorted:after{
242 | display: inline-block;
243 | font-family: 'FontAwesome';
244 | opacity: 0.8;
245 | margin-left: 1em;
246 | }
247 | table.table thead .sorted.sorted-desc:after{
248 | content: "\f15e";
249 | }
250 | table.table thead .sorted.sorted-asc:after{
251 | content: "\f15d";
252 | }
253 | ```
254 |
255 | Example with Unicode characters:
256 |
257 | ```
258 | .sorted-desc::after, .sorted-asc::after {
259 | float: right;
260 | }
261 |
262 | .sorted-desc::after{
263 | content:"\25BC";
264 | }
265 |
266 | .sorted-asc::after{
267 | content: "\25B2";
268 | }
269 | ```
270 |
271 |
--------------------------------------------------------------------------------
/src/main/java/org/thymeleaf/dialect/springdata/util/PageUtils.java:
--------------------------------------------------------------------------------
1 | package org.thymeleaf.dialect.springdata.util;
2 |
3 | import static org.thymeleaf.dialect.springdata.util.Strings.AND;
4 | import static org.thymeleaf.dialect.springdata.util.Strings.COMMA;
5 | import static org.thymeleaf.dialect.springdata.util.Strings.EMPTY;
6 | import static org.thymeleaf.dialect.springdata.util.Strings.EQ;
7 | import static org.thymeleaf.dialect.springdata.util.Strings.PAGE;
8 | import static org.thymeleaf.dialect.springdata.util.Strings.Q_MARK;
9 | import static org.thymeleaf.dialect.springdata.util.Strings.SIZE;
10 | import static org.thymeleaf.dialect.springdata.util.Strings.SORT;
11 |
12 | import java.util.Arrays;
13 | import java.util.Collection;
14 | import java.util.Iterator;
15 | import java.util.Map;
16 | import java.util.Map.Entry;
17 | import java.util.Set;
18 |
19 | import org.springframework.data.domain.Page;
20 | import org.springframework.data.domain.Sort;
21 | import org.springframework.data.domain.Sort.Direction;
22 | import org.springframework.data.domain.Sort.Order;
23 | import org.thymeleaf.IEngineConfiguration;
24 | import org.thymeleaf.context.ITemplateContext;
25 | import org.thymeleaf.context.IWebContext;
26 | import org.thymeleaf.dialect.springdata.Keys;
27 | import org.thymeleaf.dialect.springdata.exception.InvalidObjectParameterException;
28 | import org.thymeleaf.standard.expression.IStandardExpression;
29 | import org.thymeleaf.standard.expression.IStandardExpressionParser;
30 | import org.thymeleaf.standard.expression.StandardExpressions;
31 | import org.thymeleaf.web.IWebExchange;
32 | import org.thymeleaf.web.IWebRequest;
33 | import org.thymeleaf.web.servlet.IServletWebRequest;
34 | import org.unbescape.html.HtmlEscape;
35 |
36 | @SuppressWarnings("unchecked")
37 | public final class PageUtils {
38 |
39 | private PageUtils() {
40 | }
41 |
42 | public static Page> findPage(final ITemplateContext context) {
43 | // 1. Get Page object from local variables (defined with sd:page-object)
44 | // 2. Search Page using ${page} expression
45 | // 3. Search Page object as request attribute
46 |
47 | final Object pageFromLocalVariable = context.getVariable(Keys.PAGE_VARIABLE_KEY);
48 | if (isPageInstance(pageFromLocalVariable)) {
49 | return (Page>) pageFromLocalVariable;
50 | }
51 |
52 | // Check if not null and Page instance available with ${page} expression
53 | final IEngineConfiguration configuration = context.getConfiguration();
54 | final IStandardExpressionParser parser = StandardExpressions.getExpressionParser(configuration);
55 | final IStandardExpression expression = parser.parseExpression(context, Keys.PAGE_EXPRESSION);
56 | final Object page = expression.execute(context);
57 | if (isPageInstance(page)) {
58 | return (Page>) page;
59 | }
60 |
61 | // Search for Page object, and only one instance, as request attribute
62 | if (context instanceof IWebContext) {
63 | IWebExchange webExchange = ((IWebContext) context).getExchange();
64 | Set attrNames = webExchange.getAllAttributeNames();
65 | Page> pageOnRequest = null;
66 |
67 | for (String attrName : attrNames) {
68 | Object attr = webExchange.getAttributeValue(attrName);
69 | if (isPageInstance(attr)) {
70 | if (pageOnRequest != null) {
71 | throw new InvalidObjectParameterException("More than one Page object found on request!");
72 | }
73 |
74 | pageOnRequest = (Page>) attr;
75 | }
76 | }
77 |
78 | if (pageOnRequest != null) {
79 | return pageOnRequest;
80 | }
81 | }
82 |
83 | throw new InvalidObjectParameterException("Invalid or not present Page object found on request!");
84 | }
85 |
86 | public static String createPageUrl(final ITemplateContext context, int pageNumber) {
87 | final String prefix = getParamPrefix(context);
88 | final Collection excludedParams = Arrays.asList(new String[] { prefix.concat(PAGE) });
89 | final String baseUrl = buildBaseUrl(context, excludedParams);
90 |
91 | return buildUrl(baseUrl, context).append(PAGE).append(EQ).append(pageNumber).toString();
92 | }
93 |
94 | /**
95 | * Creates an url to sort data by fieldName
96 | *
97 | * @param context execution context
98 | * @param fieldName field name to sort
99 | * @param forcedDir optional, if specified then only this sort direction will be allowed
100 | * @return sort URL
101 | */
102 | public static String createSortUrl(final ITemplateContext context, final String fieldName, final Direction forcedDir) {
103 | // Params can be prefixed to manage multiple pagination on the same page
104 | final String prefix = getParamPrefix(context);
105 | final Collection excludedParams = Arrays
106 | .asList(new String[] { prefix.concat(SORT), prefix.concat(PAGE) });
107 | final String baseUrl = buildBaseUrl(context, excludedParams);
108 |
109 | final StringBuilder sortParam = new StringBuilder();
110 | final Page> page = findPage(context);
111 | final Sort sort = page.getSort();
112 | final boolean hasPreviousOrder = sort != null && sort.getOrderFor(fieldName) != null;
113 | if (forcedDir != null) {
114 | sortParam.append(fieldName).append(COMMA).append(forcedDir.toString().toLowerCase());
115 | } else if (hasPreviousOrder) {
116 | // Sort parameters exists for this field, modify direction
117 | Order previousOrder = sort.getOrderFor(fieldName);
118 | Direction dir = previousOrder.isAscending() ? Direction.DESC : Direction.ASC;
119 | sortParam.append(fieldName).append(COMMA).append(dir.toString().toLowerCase());
120 | } else {
121 | sortParam.append(fieldName);
122 | }
123 |
124 | return buildUrl(baseUrl, context).append(SORT).append(EQ).append(sortParam).toString();
125 | }
126 |
127 | public static String createPageSizeUrl(final ITemplateContext context, int pageSize) {
128 | final String prefix = getParamPrefix(context);
129 | // Reset page number to avoid empty lists
130 | final Collection excludedParams = Arrays
131 | .asList(new String[] { prefix.concat(SIZE), prefix.concat(PAGE) });
132 | final String baseUrl = buildBaseUrl(context, excludedParams);
133 |
134 | return buildUrl(baseUrl, context).append(SIZE).append(EQ).append(pageSize).toString();
135 | }
136 |
137 | public static int getFirstItemInPage(final Page> page) {
138 | return page.getSize() * page.getNumber() + 1;
139 | }
140 |
141 | public static int getLatestItemInPage(final Page> page) {
142 | return page.getSize() * page.getNumber() + page.getNumberOfElements();
143 | }
144 |
145 | public static boolean isFirstPage(Page> page) {
146 | if( page.getTotalPages()==0 ) {
147 | return true;
148 | }
149 |
150 | return page.isFirst();
151 | }
152 |
153 | public static boolean hasPrevious(Page> page) {
154 | return page.getTotalPages()>0 && page.hasPrevious();
155 | }
156 |
157 | private static String buildBaseUrl(final ITemplateContext context, Collection excludeParams) {
158 | // URL defined with pagination-url tag
159 | final String url = (String) context.getVariable(Keys.PAGINATION_URL_KEY);
160 |
161 | if (url == null && context instanceof IWebContext) {
162 | // Creates url from actual request URI and parameters
163 | final StringBuilder builder = new StringBuilder();
164 | final IWebContext webContext = (IWebContext) context;
165 | final IWebExchange webExchange = webContext.getExchange();
166 | final IWebRequest request = webExchange.getRequest();
167 |
168 | // URL base path from request
169 | builder.append(getRequestURI(request));
170 |
171 | Map params = request.getParameterMap();
172 | Set> entries = params.entrySet();
173 | boolean firstParam = true;
174 | for (Entry param : entries) {
175 | // Append params not excluded to basePath
176 | String name = param.getKey();
177 | if (!excludeParams.contains(name)) {
178 | if (firstParam) {
179 | builder.append(Q_MARK);
180 | firstParam = false;
181 | } else {
182 | builder.append(AND);
183 | }
184 |
185 | // Iterate over all values to create multiple values per
186 | // parameter
187 | String[] values = param.getValue();
188 | Collection paramValues = Arrays.asList(values);
189 | Iterator it = paramValues.iterator();
190 | while (it.hasNext()) {
191 | String value = it.next();
192 | builder.append(name).append(EQ).append(value);
193 | if (it.hasNext()) {
194 | builder.append(AND);
195 | }
196 | }
197 | }
198 | }
199 |
200 | // Escape to HTML content
201 | return HtmlEscape.escapeHtml4Xml(builder.toString());
202 | }
203 |
204 | return url == null ? EMPTY : url;
205 | }
206 |
207 | private static String getRequestURI(IWebRequest webRequest) {
208 | if (webRequest instanceof IServletWebRequest servletWebRequest) {
209 | return servletWebRequest.getRequestURI();
210 | } else {
211 | // from org.thymeleaf.web.IWebRequest.getRequestURL
212 | String scheme = webRequest.getScheme();
213 | String serverName = webRequest.getServerName();
214 | Integer serverPort = webRequest.getServerPort();
215 | String requestPath = webRequest.getRequestPath();
216 | if (scheme != null && serverName != null && serverPort != null) {
217 | StringBuilder urlBuilder = new StringBuilder();
218 | urlBuilder.append(scheme).append("://").append(serverName);
219 | if ((!scheme.equals("http") || serverPort != 80) && (!scheme.equals("https") || serverPort != 443)) {
220 | urlBuilder.append(':').append(serverPort);
221 | }
222 |
223 | urlBuilder.append(requestPath);
224 |
225 | return urlBuilder.toString();
226 | } else {
227 | throw new UnsupportedOperationException("Request scheme, server name or port are null in this environment. Cannot compute request URL");
228 | }
229 | }
230 | }
231 |
232 | private static boolean isPageInstance(Object page) {
233 | return page != null && (page instanceof Page>);
234 | }
235 |
236 | private static StringBuilder buildUrl(String baseUrl, final ITemplateContext context) {
237 | final String paramAppender = String.valueOf(baseUrl).contains(Q_MARK) ? AND : Q_MARK;
238 | final String prefix = getParamPrefix(context);
239 |
240 | return new StringBuilder(baseUrl).append(paramAppender).append(prefix);
241 | }
242 |
243 | private static String getParamPrefix(final ITemplateContext context) {
244 | final String prefix = (String) context.getVariable(Keys.PAGINATION_QUALIFIER_PREFIX);
245 |
246 | return prefix == null ? EMPTY : prefix.concat("_");
247 | }
248 |
249 | }
250 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------