Back end SSH, some methods that may be used in development projects

Posted by EvanAgee on Sat, 01 Jan 2022 13:28:31 +0100

catalogue

Login to different pages with different accounts

Chinese garbled code method

Search fuzzy query

The permission login function is grayed out

Tab child parent page display

Child parent page data display

Login query function

Display according to year data

Change Password

Give multiple permissions

Database connection

Front end data crud is stored in the back end

CRUD of multiple encapsulated parameters

Front end "pages"

Submit Form

Login to different pages with different accounts

if (rs.next()) {
            String role = rs.getString("usertype");
            if("administrators".equals(role)){
                url = "/pages/user/user_homepage.jsp?user_id="+user_id;
            }else if("instructor".equals(role)){
                url = "/pages/instructor/inst_homepage.jsp?user_id="+user_id;
            }else if("student".equals(role)){
                url = "/pages/leave/leave_homepage.jsp?user_id="+user_id;
            }else{
                url = "/pages/user/error.jsp?user_id="+user_id;
            }

Chinese garbled code method

public String toUtf8(String content) throws UnsupportedEncodingException {
        if (Objects.isNull(content)) {
            return "";
        }
        return new String(content.getBytes("ISO-8859-1"), "UTF-8");
    }

Search fuzzy query

Dao's implementation class

if (!Objects.isNull(equipName) && !equipName.isEmpty()) {// Fuzzy query data by name
                            hql += " and equipName like :equipName";
                            query = session.createQuery(hql);
                            try {
                                query.setString("equipName", "%" + new String(equipName.getBytes("ISO-8859-1"),"UTF-8") + "%");
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                        }else {
                            query = session.createQuery(hql);
                        }
                        List<EquipmentEntity> list = query.list();
                        return list;
                    }

The permission login function is grayed out

Description: in The jsp front-end page is completed. Different login users have different function buttons in the page displayed after logging in

Idea: → write in the code section onload method

<script type="text/javascript">
        window.onload = function(){
            var userType = '<s:property value="#session.user.userType"/>';
            if (userType == '2'){// Project Leader
                $("#develop").hide();
                $("#leader").hide();
                $("#system").hide();
            }else if (userType == '3'){// Development and Reform Bureau
                $("#leader").hide();
                $("#manager").hide();
                $("#system").hide();
            }else if (userType == '4'){// leader
                $("#develop").hide();
                $("#manager").hide();
                $("#system").hide();
            }
        };
    </script>

→ different users introduce usertype through session

var userType = '<s:property value="#session.user.userType"/>';

→ give an id to the function button

            <li id="develop" class="layui-nav-item"><a href="javascript:;" data-id="8" data-title="Development and Reform Bureau" onclick="removeHome()" data-url="account.jsp"
                                          class="site-demo-active" data-type="tabAdd" class="AccountAction" lay-event="develop">Development and Reform Bureau</a></li>
            <li id="leader" class="layui-nav-item"><a href="javascript:;" data-id="9" data-title="Leading Secretary" onclick="removeHome()" data-url="account.jsp"
                                          class="site-demo-active" data-type="tabAdd"class="AccountAction" lay-event="leader">Leading Secretary</a></li>
            <li id="manager" class="layui-nav-item"><a href="javascript:;" data-id="10" data-title="Project Leader" onclick="removeHome()" data-url="account.jsp"
                                          class="site-demo-active" data-type="tabAdd"class="AccountAction" lay-event="manager">Project Leader</a></li>
            <li id="system" class="layui-nav-item"><a href="javascript:;" data-id="11" data-title="project manager" onclick="removeHome()" data-url="account.jsp"
                                          class="site-demo-active" data-type="tabAdd"class="AccountAction" lay-event="system">project manager</a></li>

Tab child parent page display

Description: in The jsp front-end page is completed, and the parent page is displayed on the home page. Click the tab to display the sub option content, and the parent page content is hidden

Idea: → write a method to remove the parent page

<script>
function removeHome() {
            // Remove tbody
            $("#yearHome").remove();
        }
</script>

Click the button to give the method to onclick

Data type = "tabAdd" the child frame appears under the large parent page

Jump address of sub page after clicking data URL

<li id="system" class="layui-nav-item"><a href="javascript:;" data-id="11" data-title="project manager" onclick="removeHome()" data-url="account.jsp"
                                          class="site-demo-active" data-type="tabAdd"class="AccountAction" lay-event="system">project manager</a></li>

Child parent page data display

Description: if the large frame does not move, click different tab pages to display different data

Idea: → in dao's method, SystemDao

List<ProjectEntity> projectNames(String proName);

→ dao's method implementation class SystenDaoImpl(* the implementation class should inherit SystemDao)

@Repository
public class SystemDaoImpl extends HibernateDaoSupport implements SystemDao {
@Override
//  Query project table
  public List<ProjectEntity> projectNames(String proName) {
    return getHibernateTemplate().execute(new HibernateCallback<List<ProjectEntity>>() {
      @Override
      public List<ProjectEntity> doInHibernate(Session session) throws HibernateException {
        String hql = "from ProjectEntity where proName = ?";
        Query query = session.createQuery(hql);
        query.setParameter(0, proName);
        List<ProjectEntity> list = query.list();
        return list;
      }
    });
  }
}

→ in SystemAction: put the data queried from the database in "projects", which is queried according to the project name (one click get set)

  private String projectName;
  private Map<String,Object> request;
  private List<SystemStatisticEntity> datas;
  private List<ProjectEntity> data;

public String names() throws UnsupportedEncodingException {
    // Chinese garbled code problem
    String name = new String(projectName.getBytes("ISO-8859-1"), "UTF-8");
    // Query database by projectName
    List<ProjectEntity> datas = systemService.projectNames(name);
    // Put it in request
    request.put("projects", datas);
    return "projects";
  }

→ in systemService

List<ProjectEntity> projectNames(String proName);

→ SystemServiceImpl implementation class (description return object) inherits the SystemService interface.

@Service
public class SystemServiceImpl implements SystemService {

  @Resource
  private SystemDao systemDao;
  @Override
  public List<ProjectEntity> projectNames(String proName) {
    return systemDao.projectNames(proName);
  }
}

→ the sub page of the write tab displays data url = "project_names. Action? ProjectName = residential square", execute the action, and put forward a series of data according to the query name

<dl class="layui-nav-child">
                        <dd><a href="javascript:;" data-id="3" data-title="Residential square" onclick="removeHome()" data-url="project_names.action?projectName=Residential square"
                               class="site-demo-active" data-type="tabAdd">Residential square</a></dd>
                    </dl>

→ configuring

<!--Project statistics-->
		<action name="project_*" class="com.xmgc.models.action.SystemAction" method="{1}">
			<result name="success" type="json">
				<param name="root">datas</param>
			</result>
			<result name="projects">/system.jsp</result>
		</action>

Login query function

Description: when logging in, the password is also queried according to the account. After entering the password, the account password is the same and the login is successful

Idea:

→ front end The jsp page needs to execute the action action, and the name = "username" and name = "password" correspond to the data

<form action="user_login.action" method="post">
       user name: <input type="text" name="username" onFocus="this.value = '';" onBlur="if (this.value == '') {this.value = 'user name';}"
               required="">
        password:<input type="password" name="password" onFocus="this.value = '';" onBlur="if (this.value == '') {this.value = 'password';}"
               required="">
        <input type="submit" value="Sign in">
    </form>

→ in AccountDao

public interface AccountDao {
  AccountEntity validateAccount(String userName, String userPwd);
  AccountEntity findByUserName(String userName);
}

→ in AccountService

public interface AccountService {
  AccountEntity validateAccount(String userName, String userPwd);
  AccountEntity findByUserName(String userName);
}

→ write two methods in AccountDaoImpl (inherit AccountDao interface)

Query the account password and check the consistency between the login password and the password in the database

@Repository
public class AccountDaoImpl extends HibernateDaoSupport implements AccountDao {

  @Autowired
  public void setMySessionFactory(SessionFactory sessionFactory) {
    super.setSessionFactory(sessionFactory);
  }
//Query two consistency
  @Override
  public AccountEntity validateAccount(String userName, String userPwd) {
    AccountEntity entity = findByUserName(userName);
    if(entity == null || !entity.getUserPwd().equals(userPwd)){
      return null;
    }
    return entity;
  }
//Query the account and password in the database
  @Override
  public AccountEntity findByUserName(String userName) {
    return getHibernateTemplate().execute(new HibernateCallback<AccountEntity>() {
      @Override
      public AccountEntity doInHibernate(Session session) throws HibernateException {
        String hql = "from AccountEntity where userName = ?";
        Query query = session.createQuery(hql);
        query.setParameter(0, userName);
        AccountEntity user = (AccountEntity) query.uniqueResult();
        return user;
      }
    });
  }

→ in AccountAction

//The log method corresponds to struts action configuration in XML
  public String login() {
    boolean validated = false;//Verification success identification
    AccountEntity user = userService.validateAccount(getUsername(), getPassword());

    if (user != null) {
      validated = true;
    }
    if (validated) {
      //The string "success" is returned after successful verification
      session.put("user", user);
      //If the login is successful, record the user in the session

→ in the corresponding struts Configure in the XML file and return the json type, so only the data will not jump to the page

Actions should be configured to set whether the return type is data or page

<!-- land -->
		<action name="user_*" class="com.xmgc.models.action.AccountAction" method="{1}">
			<result name="success">/begin.jsp</result>
			<result name="error">/error.jsp</result>
			<result name="account">/account.jsp</result>
			<result name="updateSuccess" type="json">
			<param name="root">msg</param>
			</result>
		</action>

Display according to year data

Description: transfer data from the database to the foreground display, and display according to the year

thinking

→ in SystemAction (inheritance interface requestaware), click get set to create

Put the queried data into the data

public class SystemAction extends ActionSupport implements RequestAware {
  //Get information for year
  private String year;
  private Map<String,Object> request;
  private Map<String,Object> session;
  //Injection bean
  @Resource
  private SystemService systemService;

  public String types() throws Exception{
    if(StringUtils.isBlank(year)){
      datas = new ArrayList<>();
    }else {
      datas = systemService.projectTypeNums(Integer.parseInt(year));
      if(datas == null){
        datas = new ArrayList<>();
      }
    }
    return SUCCESS;
  }

→ create interface SystemService

public interface SystemService {
  /**
   * Project type statistics
   * @param year year
   * @return
   */
  List<SystemStatisticEntity> projectTypeNums(int year);
}

→ in SystemDao

public interface SystemDao {
  /**
   * Project type statistics
   * @param year year
   * @return
   */
  List<SystemStatisticEntity> projectTypeNums(int year);

→ query the table in the SystemDaoImpl implementation class and return data according to the query of the year

@Repository
public class SystemDaoImpl extends HibernateDaoSupport implements SystemDao {

  @Autowired
  public void setMySessionFactory(SessionFactory sessionFactory) {
    super.setSessionFactory(sessionFactory);
  }

  @Override
//  Query system table
  public List<SystemStatisticEntity> projectTypeNums(int year) {
    return getHibernateTemplate().execute(new HibernateCallback<List<SystemStatisticEntity>>() {
      @Override
      public List<SystemStatisticEntity> doInHibernate(Session session) throws HibernateException {
        String hql = "from SystemStatisticEntity where year = ?";
        Query query = session.createQuery(hql);
        query.setParameter(0, year);
        List<SystemStatisticEntity> list = query.list();
        return list;
      }
    });
  }
}

→ put the queried data into projects

//The log method corresponds to struts action configuration in XML
 public class AccountAction extends ActionSupport implements RequestAware,SessionAware {
 public String login() {
      // Item type statistics (default query current year)
      List<SystemStatisticEntity> datas = systemService.projectTypeNums(LocalDateTime.now().getYear());
      if (datas != null && !datas.isEmpty()) {
        request.put("projects", datas);
      }else{
        request.put("projects", new ArrayList<>());
      }
      return SUCCESS;
    } else {
      //Validation failed, return string "error"
      return ERROR;
    }
  }
}

→ at The jsp page sets which row of data corresponds to who is displayed, and uses projects to get the value

<%@ taglib prefix="s" uri="/struts-tags" %>
//Use the label < s: iterator > < / s: iterator > to reference the header
<thead>
                <th>Project type</th>
                <th>Total quantity</th>
                <th>Total project investment</th>
                <th>Annual planned investment</th>
                <th>Actually completed investment</th>
                <th>Annual commencement/day</th>
                <th>Actual commencement/day</th>
                <th>Planned completion/day</th>
                <th>practical completion /day</th>
                </tr>
                </thead>
                <tbody id="datas">
                <s:iterator value="#request.projects" status="project">
                    <tr>
                        <td><s:property value="proType"/></td>
                        <td><s:property value="totalNum"/></td>
                        <td><s:property value="totalMoney"/></td>
                        <td><s:property value="finishedMoney"/></td>
                        <td><s:property value="planMoney"/></td>
                        <td><s:property value="finishedWorkDay"/></td>
                        <td><s:property value="planWorkDay"/></td>
                        <td><s:property value="finishedCompletedDay"/></td>
                        <td><s:property value="planCompletedDay"/></td>
                    </tr>
                </s:iterator>

→ in the corresponding struts Configure in the XML file and return the json type, so only the data will not jump to the page

Actions should be configured to set whether the return type is data or page

<!--Project statistics-->
<action name="project_*" class="com.xmgc.models.action.SystemAction" method="{1}">
			<result name="success" type="json">
				<param name="root">datas</param>
			</result>
			<result name="projects">/system.jsp</result>
</action>

Change Password

Description: query the account according to the login account, input the password at the front end, and directly put the new password under the account to generate a new password

Idea:

→ write in AccountAction and put the data in username

setUserPwd put the modified data into the database

public class AccountAction extends ActionSupport implements RequestAware,SessionAware {
  private String msg = "Modification failed!";
  private Map<String,Object> request;
  private Map<String,Object> session;
  //Injection bean
  @Resource
  private AccountService userService;
  @Resource
  private SystemService systemService;

  public String toUpdatePwdPage(){
    request.put("username", username);
    return "account";
  }

  public String updatePwd(){
    AccountEntity entity = userService.findByUserName(username);
    if(entity == null){
      msg = "User does not exist, modification failed!";
    }else{
      entity.setUserPwd(password);
      userService.updatePwd(entity);
      msg = "Modification succeeded!";
    }
    return "updateSuccess";
  }

→ create method in AccountService

public interface AccountService {
  void updatePwd(AccountEntity entity);
}

→ at the front of the password modification page, take the value from username

<div class="layui-input-block">
            <s:hidden id="username" value="%{#request.username}" name="username"></s:hidden>
            <input id="password" type="text" name="password" lay-verify="title" <%--autocomplete="off"--%> placeholder="Enter the new password again, submit it immediately, refresh the page and log in again" class="layui-input">
        </div>

→ at the front of the password change page jsp page

  • Finally, submit the button to the onclick method
<div class="layui-input-block">
            <button type="submit" class="layui-btn" lay-submit="" lay-filter="demo1" onclick="check()">Submit now</button>
        </div>
        • The onclick method is written on the front end
<script>

    function check() {
        var data = $("#form").serializeArray();
        $.ajax({
            type: "POST",
            url: "user_updatePwd.action",
            data: data,
            dataType: "text",
            async: false,
            success: function (message) {
                $("#message").html(eval(message));
            }
        });
        return false;
    }
    });
</script>

→ get the entered value in AccountDaoImpl

@Repository
public class AccountDaoImpl extends HibernateDaoSupport implements AccountDao {
@Override
  public void updatePwd(AccountEntity entity) {
    if(entity == null || entity.getId() <= 0){
      return;
    }
    getHibernateTemplate().update(entity);
  }
}

→ in the corresponding struts Configure in the XML file and return the json type, so only the data will not jump to the page

Actions should be configured to set whether the return type is data or page

<!-- land -->
		<action name="user_*" class="com.xmgc.models.action.AccountAction" method="{1}">
			<result name="success">/begin.jsp</result>
			<result name="error">/error.jsp</result>
			<result name="account">/account.jsp</result>
			<result name="updateSuccess" type="json">
			<param name="root">msg</param>
			</result>
		</action>

Give multiple permissions

<s:if test="#session.user.userType == 2 || #session.user.userType == 1">
</s:if>

Database connection

In resources properties, directly enter the database name and password (framework connection)

hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.validationQuery=SELECT 1 FROM DUAL
jdbc.url=jdbc:mysql://47.100.92.76:3306/xmgc?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true

jdbc.username=root
jdbc.password=123456

hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.autoReconnect=true

Front end data crud is stored in the back end

→ create a ManagerService interface and wait for the implementation class to write specific methods.

public interface ManagerService {
  //Define insertion method
  String add(ProjectEntity projectEntity);

  //Define traversal query method
  List findall();

  ProjectEntity findid(int id);

  //Definition deletion
  int del(int id);

  //Definition modification
  void edit(ProjectEntity projectEntity);
}

→ define methods in the ManagerDao interface and wait for specific implementation in the implementation class

public interface ManagerDao {
    //Define insertion method
    String add(ProjectEntity projectEntity);
    //Define query method
    List findall();
    ProjectEntity findid(int id);
    //Define deletion method
    int del(int id);
    //Define modification method
    void edit(ProjectEntity projectEntity);

→ ManagerDaoImpl implements the class inheritance interface, rewrites HibernateDaoSupport and writes specific methods

@Repository
public class ManagerDaoImpl extends HibernateDaoSupport implements ManagerDao {

    @Autowired
    public void setSessionFactoryOverride(SessionFactory sessionFactory) {
        super.setSessionFactory(sessionFactory);
    }

    @Override
    //Insert operation
    public String add(ProjectEntity projectEntity) {
        return getHibernateTemplate().save(projectEntity).toString();
    }

    //Find operation
    public List<ProjectEntity> findall() {
        String sql = "from ProjectEntity";
        ArrayList<ProjectEntity> list = (ArrayList<ProjectEntity>) this.getHibernateTemplate().find(sql);
        return list;
    }

    //Query by item id
    public ProjectEntity findid(int id) {
        ProjectEntity dd = this.getHibernateTemplate().get(ProjectEntity.class, id);
        return dd;
    }

    //Delete operation
    public int del(int id) {
        //Instantiate object
        ProjectEntity dd = new ProjectEntity();
        dd.setId(id);
        this.getHibernateTemplate().delete(dd);
        int tt = 1;
        return tt;
    }

    //Modify operation
    public void edit(ProjectEntity projectEntity) {
        this.getHibernateTemplate().update(projectEntity);
    }
}

→ write specific methods for ManagerServiceImpl implementation class

@Service
public class ManagerServiceImpl implements ManagerService {

    @Resource
    private ManagerDao managerDao;

    //Injection transaction management
    @Transactional(rollbackFor = {Exception.class,RuntimeException.class})

     //Insert operation
    public String add(ProjectEntity projectEntity) {

        return managerDao.add(projectEntity);
    }

    //Query operation
    public List<ProjectEntity> findall(){
        return  managerDao.findall();

    }
    public ProjectEntity findid(int id){
        return managerDao.findid(id);
    }

    //Delete operation
    public int del(int id){

        return managerDao.del(id);
    }

    //Modify operation
    public void edit(ProjectEntity projectEntity){

        managerDao.edit(projectEntity);
    }

}

ManageAction

public class ManagerAction extends ActionSupport implements SessionAware {
  @Resource
  private ManagerService managerService;
  private int id;
  private Long proMoney;
  private String proName;
  private String proType;
  private String proManager;
  private int managerNum;
  private String chargeDepart;
  private String leaderName;
  private String leaderNum;
  private String proYear;
  private String proBegin;
  private String proFinish;
  private String proAddress;

  private Map<String, Object> session;

  public String add() {

    //Format conversion
    try {

      ProjectEntity projectEntity = new ProjectEntity();
      projectEntity.setProMoney(getProMoney());
      projectEntity.setProName(getProName());
      projectEntity.setProType(getProType());
      projectEntity.setProManager(getProManager());
      projectEntity.setManagerNum(getManagerNum());
      projectEntity.setChargeDepart(getChargeDepart());
      projectEntity.setLeaderName(getLeaderName());
      projectEntity.setLeaderNum(getLeaderNum());
      projectEntity.setProYear(csrq1);
      projectEntity.setProBegin(csrq2);
      projectEntity.setProFinish(csrq3);
      projectEntity.setProAddress(getProAddress());

      managerService.add(projectEntity);

    } catch (Exception e) {

      e.printStackTrace();
    }
    return SUCCESS;
  }
}

CRUD of multiple encapsulated parameters

→ ProcessDaoImpl is the implementation of specific methods

@Repository
@Transactional
public class ProcessDaoImpl extends HibernateDaoSupport implements ProcessDao {
    //Create DetachedCriteria object
    private DetachedCriteria criteria;
    // Inject SessionFactory into the parent class
    @Autowired
    public void setMySessionFactory(SessionFactory sessionFactory){
        //Call the SessionFactory of the parent class and pass it to the parent class to ensure that the SessionFactory is unique
        super.setSessionFactory(sessionFactory);
    }

    public String save(ProcessEntity processEntity) {
        //Save processEntity
        this.getHibernateTemplate().save(processEntity);
        if(this.getHibernateTemplate()!=null){
            return "save";
        }
        return null;
    }

    @Override
    public int findProcessCount(boolean isAdmin, String managerNum) {
        //Query all records of the corresponding responsible person
        return this.findCount(isAdmin, managerNum);

    }

//Query project progress report by page
    @Override
    public List<ProcessEntity> findProcess(boolean isAdmin, ProcessEntity processEntity, int begin, int pageSize) {
        criteria = DetachedCriteria.forClass(ProcessEntity.class);
        if(!isAdmin) {// Non supertube
            //Query by responsible labor number
            if (processEntity.getManagerNum() != null && !processEntity.getManagerNum().isEmpty()) {
                criteria.add(Restrictions.like("managerNum", processEntity.getManagerNum()));
            }
        }
        List<ProcessEntity> processEntityList = (List<ProcessEntity>) this.getHibernateTemplate().findByCriteria(criteria,begin,pageSize);
        return processEntityList;
    }
    //Query the number of records of the project corresponding to the person in charge
    @Override
    public int findProjectCount(boolean isAdmin, Integer managerNum) {
        String hql = "SELECT COUNT(*) from com.xmgc.models.pojo.ProjectEntity ";
        Query query = null;
        if (isAdmin) {
            query = currentSession().createQuery(hql);
        }else{
            if(managerNum == null){
                return 0;
            }
            hql += " where ManagerNum=? ";
            query = currentSession().createQuery(hql);
            query.setInteger(0, managerNum);
        }

        List<Long> list =  query.list();
        if(list.size()>0){
            return list.get(0).intValue();
        }
        return 0;
    }

→ write a method in the ProcessDao interface

//ProcessDao interface
public interface ProcessDao {
    //Save processEntity
    String save(ProcessEntity processEntity);

    int findProcessCount(boolean isAdmin, String managerNum);

    List<ProcessEntity> findProcess(boolean isAdmin, ProcessEntity processEntity, int begin, int pageSize);

    int findProjectCount(boolean isAdmin, Integer managerNum);
}

→ProcessService

public interface ProcessService {

    String save(ProcessEntity processEntity);//preservation

    PageBeanEntity<ProcessEntity> findProcess(boolean isAdmin, ProcessEntity processEntity, int currPage);

    PageBeanEntity<ProjectEntity> findProject(boolean isAdmin,ProjectEntity projectEntity, int currPage);
}

→ ProcessServiceImpl write the specific save, check the project progress and check the project name

@Service
public class ProcessServiceImpl implements ProcessService {

    private ProcessDao processDao;
    @Autowired
    public void setProcessDao(ProcessDao processDao) {
        this.processDao = processDao;
    }

    public String save(ProcessEntity processEntity) {
       return processDao.save(processEntity);
    }
@Override
    public PageBeanEntity<ProcessEntity> findProcess(boolean isAdmin, ProcessEntity processEntity, int currPage) {
        PageBeanEntity<ProcessEntity> pageBean = new PageBeanEntity<ProcessEntity>();
        //Encapsulates the current number of pages
        pageBean.setCurrPage(currPage);
        //Number of records displayed per page
        int pageSize = 10;
        pageBean.setPageSize(pageSize);
        //Total records encapsulated
        int totalCount = processDao.findProcessCount(isAdmin, processEntity.getManagerNum());
        pageBean.setTotalCount(totalCount);
        //Total encapsulated pages
        double tc = totalCount;
        Double sum = Math.ceil(tc/pageSize);
        pageBean.setTotalPage(sum.intValue());
        if(totalCount == 0){// If the total number is 0, there is no need to query paging data
            return pageBean;
        }
        //Encapsulates the data displayed on each page
        int begin = (currPage-1)*pageSize;
        List<ProcessEntity> list = processDao.findProcess(isAdmin, processEntity, begin, pageSize);
        pageBean.setList(list);
        return pageBean;
    }
    //query
    @Override
    public PageBeanEntity<ProjectEntity> findProject(boolean isAdmin,ProjectEntity projectEntity, int currPage) {
        PageBeanEntity<ProjectEntity> pageBean = new PageBeanEntity<ProjectEntity>();
        //Encapsulates the current number of pages
        pageBean.setCurrPage(currPage);
        //Number of records displayed per page
        int pageSize = 12;
        pageBean.setPageSize(pageSize);
        //Total records encapsulated
        int totalCount = processDao.findProjectCount(isAdmin, projectEntity.getManagerNum());
        pageBean.setTotalCount(totalCount);
        //Total encapsulated pages
        double tc = totalCount;
        Double sum = Math.ceil(tc/pageSize);
        pageBean.setTotalPage(sum.intValue());
        if(totalCount == 0){// If the total number is 0, there is no need to query paging data
            return pageBean;
        }
        //Encapsulates the data displayed on each page
        int begin = (currPage-1)*pageSize;
        List<ProjectEntity> list = processDao.findProject(isAdmin, projectEntity, begin, pageSize);
        pageBean.setList(list);
        return pageBean;
    }
}

→ ProcessAction saves the Action method of the project report

public String save() {
        //Call the save method of the business layer
        HttpServletRequest request = ServletActionContext.getRequest();
        //Convert JSON string to entity class object
        ProcessEntity processEntity = JSON.parseObject(request.getParameter("save"),ProcessEntity.class);
        String bool =  processService.save(processEntity);
        processService.save(processEntity);
        if(bool!=null){
            msg = "Project progress uploaded successfully";
        } else
        msg = "Project progress upload failed!! Please try again";
        return SUCCESS;
    }

Front end "pages"

Description: the queried project progress data has many pieces of data, which should be displayed in pages

→ PageBeanEntity create entity class

public class PageBeanEntity<T> {
    private int currPage;//Current number of pages
    private int pageSize;//Number of records displayed per page
    private int totalCount;//Total records
    private int totalPage;//PageCount 
    private List<T> list;//Data displayed per page
}

→ in ProcessService interface

public interface ProcessService {
PageBeanEntity<ProcessEntity> findProcess(boolean isAdmin, ProcessEntity processEntity, int currPage);
}

→ ProcessServiceImpl implements the class inheritance interface to write specific operations

@Override
public class ProcessServiceImpl implements ProcessService {
    public PageBeanEntity<ProcessEntity> findProcess(boolean isAdmin, ProcessEntity processEntity, int currPage) {
        PageBeanEntity<ProcessEntity> pageBean = new PageBeanEntity<ProcessEntity>();
        //Encapsulates the current number of pages
        pageBean.setCurrPage(currPage);
        //Number of records displayed per page
        int pageSize = 10;
        pageBean.setPageSize(pageSize);
        //Total records encapsulated
        int totalCount = processDao.findProcessCount(isAdmin, processEntity.getManagerNum());
        pageBean.setTotalCount(totalCount);
        //Total encapsulated pages
        double tc = totalCount;
        Double sum = Math.ceil(tc/pageSize);
        pageBean.setTotalPage(sum.intValue());
        if(totalCount == 0){// If the total number is 0, there is no need to query paging data
            return pageBean;
        }
        //Encapsulates the data displayed on each page
        int begin = (currPage-1)*pageSize;
        List<ProcessEntity> list = processDao.findProcess(isAdmin, processEntity, begin, pageSize);
        pageBean.setList(list);
        return pageBean;
    }
}
→

Submit Form

→ configure action in struts configuration file

<action name="processAction_*" class="com.xmgc.models.action.ProcessAction" method="{1}">

→ the front-end jsp page calls saveform to submit the form (the name should correspond to the js code)

<body>
<form class="layui-form layui-form-pane" action="" method="POST" id="saveForm" style="width: 70% ">
 Content in the page, various div label

    </form>
</body>

→ call the action in the js code part of the front-end Jsp page (the layui framework is used here without multi management)

$.each($("#saveForm").serializeArray(), function (i, field) {
                        $.post("<%=basePath%>biz/processAction_save.action", 

Topics: Front-end ssh Back-end