Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the linkage between web and background

2025-03-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "how to achieve the linkage between web and the background". In the daily operation, I believe that many people have doubts about how to achieve the linkage between web and the background. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "how to achieve the linkage between web and the background". Next, please follow the editor to study!

one。 Project structure:

1.common: utility class

2.domain: body class

3.repository: persistent classes / interfaces

4.query: query class

5.service: service layer

6.web: front end

① controller: control layer

two。 Today's goal

1. Complete the extended extraction of SpringDataJpa, and then you can use it directly.

two。 Complete the process set up and run successfully

① background code building

② Front desk Home Page connection

③ perfect classes and presentation page

④ adds advanced query

⑤ function extension

three。 Code completion

[toc]

# I. SpringDataJpa extension

> the original function of SpringDataJpa has been added accordingly (the code is copying) # # 1.BaseRepository interface

> @ NoRepositoryBean: tell SpringdataJpa not to automatically generate subclasses for it

@ NoRepositoryBeanpublic interface BaseRepository extends JpaRepository, JpaSpecificationExecutor {/ / get paging object (paging) Page findPageByQuery (BaseQuery baseQuery) according to Query; / / get all corresponding data (non-paging) List findByQuery (BaseQuery baseQuery) according to Query; / / get data List findByJpql (String jpql,Object...) based on jpql and corresponding parameters Values);}

# # implementing BaseRepository with 2.BaseRepositoryImpl

Public class BaseRepositoryImpl extends SimpleJpaRepository implements BaseRepository {private final EntityManager entityManager; / / must implement this constructor of the parent class public BaseRepositoryImpl (Class domainClass, EntityManager em) {super (domainClass, em); this.entityManager = em;} @ Override public Page findPageByQuery (BaseQuery baseQuery) {/ / first step: get all the advanced query conditions Specification spec = baseQuery.createSpec () / / step 2: get the sorted value Sort sort = baseQuery.createSort (); / / step 3: query paged data according to conditions and return Pageable pageable = new PageRequest (baseQuery.getJpaPage (), baseQuery.getPageSize (), sort); Page page = super.findAll (spec, pageable); return page } @ Override public List findByQuery (BaseQuery baseQuery) {/ / first step: get all the advanced query criteria Specification spec = baseQuery.createSpec (); / / step 2: get the sorted value Sort sort = baseQuery.createSort (); / / step 3: get the data and return return findAll (spec, sort);} @ Override public List findByJpql (String jpql, Object...) Values) {/ / first step: create a Query object Query query = entityManager.createQuery (jpql); / / second step: set the value to the Query object to if (valuesvalues are null) {for (int I = 0; I)

< values.length; i++) { query.setParameter(i + 1, values[i]); } } //第三步:返回数据 return query.getResultList(); }} ## 3.让SpringDataJpa使用我们自己的实现 >

Originally, it was implemented by default using SimpleJpaRepository, which was modified to BaseRepositoryImpl### 3.1BaseRepositoryFactoryBean.

/ * if you want to extend SpringDataJpa, you must write it * / public class BaseRepositoryFactoryBean extends JpaRepositoryFactoryBean {@ Override protected RepositoryFactorySupport createRepositoryFactory (EntityManager entityManager) {return new MyRepositoryFactory (entityManager); / / Note: here is our custom class} / / after inheriting JpaRepositoryFactory, modify the returned object to our own implementation private static class MyRepositoryFactory extends JpaRepositoryFactory {private final EntityManager entityManager / * * Creates a new {@ link JpaRepositoryFactory}. * * @ param entityManager must not be {@ literal null} * / public MyRepositoryFactory (EntityManager entityManager) {super (entityManager); this.entityManager = entityManager;} / / the last function object @ Override protected Object getTargetRepository (RepositoryInformation information) {return new BaseRepositoryImpl ((Class) information.getDomainType (), entityManager) is returned here. } / / determine the type of function object @ Override protected Class getRepositoryBaseClass (RepositoryMetadata metadata) {return BaseRepositoryImpl.class;}

# 3.2 applicationContext.xml configuration

> the key is factory-class configuration

# 3.3 inherit BaseRepository when you use it

Public interface EmployeeRepository extends BaseRepository {...}

# II. Invocation of Service layer

Implementing IBaseService with BaseServiceImpl

IEmployeeService inherits IBaseService

Pay attention to generic injection

@ Autowiredprivate BaseRepository baseRepository

# III. Integration of SpringMVC and EasyUI

# # 3.1 noSession issues

Before we shut down EntityManager, we were still using it to manipulate the database (appears during lazy loading)

> > solution: add OpenEntityManagerInViewFilter to web.xml

OpenEntityManager org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter openEntityManager / *

# # 3.2 no serializer issues

> reason: the lazy loading object of jpa adds some attributes ("hibernateLazyInitializer", "handler", "fieldHandler") that will affect the return of Json by SpringMVC (because there is an introspection mechanism when returning)

# solution 1: add comments

`@ JsonIgnoreProperties (value= {"hibernateLazyInitializer", "handler", "fieldHandler"})`

# solution 2: once and for all-rewrite: ObjectMapper

Import com.fasterxml.jackson.annotation.JsonInclude;import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.SerializationFeature;// rewrites the native mapping relationship public class CustomMapper extends ObjectMapper {public CustomMapper () {this.setSerializationInclusion (JsonInclude.Include.NON_NULL); / / sets SerializationFeature.FAIL_ON_EMPTY_BEANS to false this.configure (SerializationFeature.FAIL_ON_EMPTY_BEANS, false);}}

-configure this mapping in applicationContext-mvc.xml

Application/json; charset=UTF-8 application/x-www-form-urlencoded; charset=UTF-8

# # 3.3 get data by paging

> the Page object {content:..,totalElements:..} is returned in the background

> > the code for the receptionist is {rows:..,total:...}.

> their results don't match.-got a UIPage.

Public class UIPage {private List rows; private Long total; public UIPage (Page page) {this.rows = page.getContent (); this.total = page.getTotalElements ();} / / omit getter and setter}

-the return code is as follows:

RequestMapping ("/ page") @ ResponseBodypublic UIPage page (EmployeeQuery query) {return new UIPage (employeeService.findPageByQuery (query));}

# # 3.4 transmit data by page

> page and rows are uploaded, but our previous query names do not match.

-BaseQuery plus compatibility

/ / for compatibility with foreground easyui, add additional setter

Public void setPage (int page) {this.currentPage = page;} public void setRows (int rows) {this.pageSize = rows;}

# # 3.5 Advanced query

-get the corresponding form value when you query an advanced query

# introduce [jquery.jdirk.js]

It extends the functions of jQuery

``

# get the function of form

Search () {/ / directly get all the values in the form var params = $("# searchForm") .serializeObject (); / / query $("# employeeGrid") .datagrid ("load", params);}

# # 3.6 extension

one。 Sorting function

BaseQuery background support

/ * Common conditions and specifications * / public abstract class BaseQuery {... / compatible Easyui sorting public void setSort (String sort) {this.orderByName = sort;} public void setOrder (String order) {this.orderByType = order;}}

2.employee.js support: add the sortable= "true" attribute to the fields that need to be supported

Profile picture, user name, password, email age department

3. Hidden field

You can find this effect in the http://www.easyui-extlib.com/-> grid section

And get the support and source code you need

What is needed:

Just add the enableHeaderClickMenu= "true" attribute to the table tag

At this point, the study on "how to achieve the linkage between web and the background" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report