Tags: Tax Service System project


preface

Previously, we have completed the function of conditional query, which can query data according to the conditions given by users. However, there are still some minor glitches. Let’s take a look:

When we query data, we operate on the queried data. After the operation is complete, it returns not our query data, but our initialization data. This is obviously not appropriate, when the user is done, we should return the data from the conditional query **.

There is also a point: our page has not written…… Therefore, this paper mainly solves these two problems.

The echo data

First, let’s analyze why we get initialized data when we’re done. We follow the user’s actions to see what went wrong.

  1. Users can query data based on conditions and display the queried data
  2. The user clicks Edit/Delete on the query data operation, which is handed over to Action
  3. The Action returns to the display page JSP
  4. The JSP page submits the request to the Action, which handles it
  5. Finally, the Action redirects to listUI

So what problems do we encounter in this process??


Deal with 1.0

Use a variable in the Action to encapsulate the query condition

    /************ Obtain the value of the query condition *************************/
    private String selectCondition;
    public String getSelectCondition(a) {
        return selectCondition;
    }
    public void setSelectCondition(String selectCondition) {
        this.selectCondition = selectCondition;
    }

Copy the code

When an Action is requested, we extract the value of the query condition and send it to the corresponding JSP page

    public String editUI(a) {

        // Get all the information types
        ActionContext.getContext().getContextMap().put("infoTypeMap", Info.INFO_TYPE_MAP);
        // We need to find the corresponding Info
        if(info ! =null&& info.getInfoId() ! =null) {

            // Send the query criteria to the JSP page
            ActionContext.getContext().getContextMap().put("selectCondition", info.getTitle());

            // Get the information directly, JSP will be able to read the corresponding information according to the Info getter!
            info = infoServiceImpl.findObjectById(info.getInfoId());

        }
        return "editUI";
    }
Copy the code

The JSP page stores the sent value and sends it to the Action via a hidden field



    <%-- pass the query criteria to Action--%>
    <s:hidden name="selectCondition"/>
Copy the code

When the Action is rearrived, the query condition can be wrapped in the selectCondition variable, thanks to Struts2’s automatic wrapping. Finally, the operation is redirected to the listUI interface

Since it is a redirect, we need to bring our query criteria in the Struts configuration file:


    <result name="list" type="redirectAction">
        <param name="actionName">info_listUI</param>

        <! When redirecting back, add the query criteria with -->
        <param name="info.title">${selectCondition}</param>
    </result>
Copy the code

Of course, when deleting, just record the query conditions.


    / / delete
    public String delete(a) {
        selectCondition = info.getTitle();
        String id = info.getInfoId();
        infoServiceImpl.delete(id);
        return "list";
    }
Copy the code
  • Effect:

Deal with 2.0

Above we did solve the problem of data echo after query, but what if our query condition is Chinese?

Become a garbled….. Before solving it, let’s analyze why the garbled….

  • We know that Struts2 uses POST to submit the form’s data, and the internal code automatically converts it for us. In other words, our garbled code was definitely not messed up during the form transfer.

  • The Chinese parameter data was messed up during the redirect.

  • When passing parameters in the configuration file, we set the encoding:


        <! Encoding is required when transmitting data.
        <param name="encode">true</param>
Copy the code
  • When we read this data in the Action, we just decode it.

    if(info ! =null) {
        if (StringUtils.isNotBlank(info.getTitle())) {
            selectCondition =  URLDecoder.decode(info.getTitle(),"UTF-8");
            info.setTitle(selectCondition);

            queryHelper.addCondition(" i.title like ? "."%" + info.getTitle() + "%"); }}Copy the code

paging

Pagination is not new to us either, as I explained in a JDBC blog post about pagination: blog.csdn.net/hon_3y/arti…

Paging reuse code blog.csdn.net/hon_3y/arti…

This time we still use our paging reuse code, specific requirements, can be modified above.

Add methods in DAO and daoImpl

  • Dao methods
    / * * * *@paramQueryHelper, queryHelper, queryHelper, queryHelper@paramCurrentPage Number of current pages *@return* /
    PageResult getPageResult(QueryHelper queryHelper, int currentPage);

Copy the code
  • Add an SQL statement to query the total number of records in queryHelper

    / * * * *@returnReturn SQL statement */ to query total number of records
    public String getTotalRecordSql(a) {
        return "SELECT COUNT(*) " + fromClause + whereClause;
    }

Copy the code
  • DaoImpl implementation:

  • Query the total number of records first

  • Initialize the Page object

  • Query paging data to set paging data to a Page object

  • Return Page object


	public PageResult getPageResult(QueryHelper queryHelper, int currentPage) {

		// Query the total number of records
		Query queryCount = getSession().createQuery(queryHelper.getTotalRecordSql());
		if(queryHelper.getObjectList() ! =null) {
			int i =0;
			for (Object o : queryHelper.getObjectList()) {
				queryCount.setParameter(i, o);
				i++;
			}
		}
		Long totalRecord = (Long) queryCount.uniqueResult();

		// Initialize the PageResult object
		PageResult pageResult = new PageResult(currentPage, totalRecord);

		// Query the data of specific modules.
		Query query = getSession().createQuery(queryHelper.returnHQL());
		if(queryHelper.getObjectList() ! =null) {
			int i =0;
			for(Object o : queryHelper.getObjectList()) { query.setParameter(i, o); i++; }}// Set the start and end of pages
		query.setFirstResult(pageResult.getStartIndex());
		query.setMaxResults(pageResult.getLineSize());
		List dataList = query.list();
		
		// Set the query data to the Page object
		pageResult.setList(dataList);
		return pageResult;
	}
Copy the code

Add methods in service and serviceImpl

  • baseService

    PageResult getPageResult(QueryHelper queryHelper, int currentPage);
Copy the code
  • baseServiceImpl

    public PageResult getPageResult(QueryHelper queryHelper, int currentPage) {
        return baseDao.getPageResult(queryHelper, currentPage);
    }

Copy the code

Call the service method in the Action

Set the paging properties we need to use.


    private int currentPageCount;
    private PageResult pageResult;
    public int getCurrentPageCount(a) {
        return currentPageCount;
    }
    public void setCurrentPageCount(int currentPageCount) {
        this.currentPageCount = currentPageCount;
    }
    public PageResult getPageResult(a) {
        return pageResult;
    }
    public void setPageResult(PageResult pageResult) {
        this.pageResult = pageResult;
    }
Copy the code

Determine if our current page is 0 (if 0, indicating a newly initialized value, we set it to 1) and call the service method to get the paging object


    // The current page number has no value, then the value is 1
    if (currentPageCount == 0) {
        currentPageCount = 1;
    }
    pageResult = infoServiceImpl.getPageResult(queryHelper,currentPageCount);
Copy the code

In a JSP page, we iterate through the collection of paging objects to get the paging data.


   <s:iterator value="pageResult.list" status="st">
Copy the code

Effect:


Extract the attributes

Our paging properties and query criteria data are not unique to the Info module, so we extract the paging data into BaseAction


    /************ paging properties *************************/
    protected int currentPageCount;
    protected PageResult pageResult;
    public int getCurrentPageCount(a) {
        return currentPageCount;
    }
    public void setCurrentPageCount(int currentPageCount) {
        this.currentPageCount = currentPageCount;
    }
    public PageResult getPageResult(a) {
        return pageResult;
    }
    public void setPageResult(PageResult pageResult) {
        this.pageResult = pageResult;
    }

    /************ Obtain the value of the query condition *************************/
    protected String selectCondition;
    public String getSelectCondition(a) {
        return selectCondition;
    }
    public void setSelectCondition(String selectCondition) {
        this.selectCondition = selectCondition;
    }
Copy the code

Modify other modules, can also have conditional query and paging query these two functions: take the user module as an example.

  • Set the query object to User and perform conditional query according to the name of the User.

    // Throw an Action exception
    public String listUI(a) throws ServiceException, UnsupportedEncodingException {
        QueryHelper queryHelper = new QueryHelper(User.class, "u");
        // Check whether the query is conditional based on whether info is null. If info is empty, all are queried.
        if(user ! =null) {
            if (org.apache.commons.lang.StringUtils.isNotBlank(user.getName())) {
                selectCondition =  URLDecoder.decode(user.getName(),"UTF-8");
                user.setName(selectCondition);
                queryHelper.addCondition(" u.name like ? "."%" + user.getName() + "%"); }}// The current page number has no value, then the value is 1
        if (currentPageCount == 0) {
            currentPageCount = 1;
        }
        pageResult = userServiceImpl.getPageResult(queryHelper,currentPageCount);
        return "listUI";
    }
Copy the code
  • The JSP page is traversed by paging objects, importing our paging subscript table JSP
        <s:iterator value="pageResult.list">
  		<jsp:include page="/common/pageNavigator.jsp"/>

Copy the code

Handling the problem of data output after query:

  • Note down the query criteria before jumping to the edit page. Otherwise it would have been covered.

    public String editUI(a) {

        // Query all the roles and bring them to the JSP page to display
        ActionContext.getContext().getContextMap().put("roleList", roleServiceImpl.findObjects());

        // We need to find the User that corresponds to the id
        if(user ! =null&&user.getId() ! =null  ) {

            // get the query condition
            selectCondition = user.getName();

            // The User has a getter to read the corresponding information!
            user = userServiceImpl.findObjectById(user.getId());

            // Get the owning UserRole from the user id
            List<UserRole> roles = userServiceImpl.findRoleById(user.getId());
            // Fill the array with the user's role iD, which is displayed in the JSP page
            int i=0;
            userRoleIds =  new String[roles.size()];
            for(UserRole role : roles) { userRoleIds[i++] = role.getUserRoleId().getRole().getRoleId(); }}return "editUI";
    }
Copy the code
  • On the JSP that displays the edit page, pass the query criteria to the Action

    <%-- bring the query criteria through the hidden field to Action--%>
    <s:hidden name="selectCondition"></s:hidden>
Copy the code
  • Finally, when editing and redirecting, you should also bring the query criteria with you. To prevent problems with Chinese, we coded it

        <action name="user_*" class="zhongfucheng.user.action.UserAction" method="{1}">
            <result name="{1}" >/WEB-INF/jsp/user/{1}.jsp</result>

            <! Return to the list display page, redirect to list display
            <result name="list" type="redirectAction">
                <param name="actionName">user_listUI</param>
                <param name="user.name">${selectCondition}</param>
                <param name="encode">true</param>
            </result>
        </action>
Copy the code
  • When deleting, you should also record the query conditions.

    / / delete
    public String delete(a) {
        if(user ! =null&& user.getId() ! =null) {

            // Record the query condition
            selectCondition = user.getName();

            userServiceImpl.delete(user.getId());
        }
        return "list";
    }
Copy the code

conclusion

  • In the process of conditional query, if we do not keep the query condition. So this condition is going to be lost. When we’re done, it returns a list page with no query criteria.
  • For example, our editing operation goes through several steps: the request goes to editUI() if we don’t record the query criteria. It gets overwritten by the original properties.
  • Then jump to the edit page, and if we don’t pass the query criteria to the Action via the hidden field, the query criteria are lost on the page.
  • Finally, when we redirect to the list page, we either redirect the condition to the list() method by adding parameters to the URL, or we use Struts2 parameter passing. Among them, if the Chinese, remember to code ah!
  • We’ve done a lot with paging data. Finally, encapsulate the data passed in our Action into a BaseAction.

If you find this article helpful, give the author a little encouragement