选择了Thymeleaf选项

时间:2017-08-25 13:45:05

标签: spring-mvc spring-data thymeleaf

请你能帮帮我吗?我编写了一个cron监控应用程序,我使用Spring-mvc,Spring-data和thymeleaf。在html页面中,当我选择应用程序名称并单击“bRechercher”(搜索)按钮时,应用程序重新加载页面并且应用程序名称未保持选中状态,而是选择“Sélectionner”。请,我希望在页面重新加载后应用程序名称保持选中状态。有我的html页面,我的控制器和我的事件实体:

<!DOCTYPE html>
   
<html lang="fr"
      xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorator ="layouts/layout">



<head>
    <!-- jQuery -->
    <script src="/resources/components/jquery/jquery.min.js"></script>
    <!-- Bootstrap Core JavaScript -->
    <script src="/resources/components/bootstrap/js/bootstrap.min.js"></script>
    <script src="/resources/js/appSuiviCrons.js"></script>
    <script>
        $(document).ready(function(){
            var date_input=$('input[name="startDateEvent"]'); //our date input has the name "date"
            var container=$('.bootstrap-iso form').length>0 ? $('.bootstrap-iso form').parent() : "body";
            date_input.datepicker({
                format: 'mm/dd/yyyy',
                container: container,
                todayHighlight: true,
                autoclose: true,
            })
        })
    </script>

    <script>
        $(document).ready(function(){
            var date_input=$('input[name="endDateEvent"]'); //our date input has the name "date"
            var container=$('.bootstrap-iso form').length>0 ? $('.bootstrap-iso form').parent() : "body";
            date_input.datepicker({
                format: 'mm/dd/yyyy',
                container: container,
                todayHighlight: true,
                autoclose: true,
            })
        })
    </script>


    <title th:text="#{sider.suivi.cron}"></title>
</head>

<body>
<div layout:fragment="content" id="page-wrapper">

    <div class="container-fluid">
        <div class="row">
            <div class="col-lg-12">
                <h1 class="page-header" th:text="#{sider.suivi.cron}"></h1>
            </div>
        </div>
        <div class="row">
            <div class="col-lg-12">

                <form name="crons" action="#" th:action="@{/suiviCrons}" method="get">
                    <table>
                        <tbody>
                            <tr>
                                <td>Rechercher par :</td><td></td><td></td><td></td>
                            </tr>
                            <tr>
                                <td>Nom de l'application : </td>
                                <td>
                                    <select class = "btn dropdown-toggle" th:value="${applicationName}" name="applicationName"  th:field="*{lApplication}">
                                        <option value="" selected="selected">Sélectionner</option>
                                        <option th:each="event : ${lApplication}" th:value="${event}" th:text="${event}"></option>
                                    </select>
                                </td>
                                <td>Nom du cron : </td>
                                <td>
                                    <select th:value="${cronName}" class = "btn dropdown-toggle" name="cronName">
                                        <option th:value="${cronName}"><p th:text="${cronName}"></p></option>
                                        <option th:value="Sélectionner"><p th:text="Sélectionner"></p></option>
                                        <option th:each="event : ${lCrons}" th:value="${event}"><p th:text="${event}"></p></option>
                                    </select>
                                </td>
                            </tr>
                            <tr>
                                <td>Nom du serveur : </td>
                                <td>
                                    <select th:value="${serverName}" class = "btn dropdown-toggle" name="serverName">
                                        <option th:value="${serverName}"><p th:text="${serverName}"></p></option>
                                        <option th:value="Sélectionner"><p th:text="Sélectionner"></p></option>
                                        <option th:each="event : ${lServerNames}" th:value="${event}"><p th:text="${event}"></p></option>
                                    </select>
                                </td>
                                <td>Adresse IP du serveur : </td>
                                <td>
                                    <select th:value="${serverIP}" class = "btn dropdown-toggle" name="serverIP">
                                        <option th:value="${serverIP}"><p th:text="${serverIP}"></p></option>
                                        <option th:value="Sélectionner"><p th:text="Sélectionner"></p></option>
                                        <option th:each="event : ${lServerIPs}" th:value="${event}"><p th:text="${event}"></p></option>
                                    </select>
                                </td>
                            </tr>
                            <tr>
                                <td>Date de début : </td><td></td><td></td><td></td>
                            </tr>
                            <tr>
                                <td>De : </td>
                                <td>
                                    <input class="form-control" name="startDateEvent" th:value="${startDateEvent}" type="text"/>
                                </td>
                                <td>A : </td>
                                <td>
                                    <input class="form-control" name="endDateEvent" th:value="${endDateEvent}" type="text"/>
                                </td>
                            </tr>
                            <tr>
                                <td>Statut : </td>
                                <td>
                                    <select th:value="${status}" class = "btn dropdown-toggle" name="status">
                                        <option th:value="${status}"><p th:text="${status}"></p></option>
                                        <option th:value="Sélectionner"><p th:text="Sélectionner"></p></option>
                                        <option th:each="statut : ${lStatut}" th:value="${statut.label}"><p th:text="${statut.label}"></p></option>
                                    </select>
                                </td>
                                <td></td>
                                <td></td>
                            </tr>
                        </tbody>
                    </table>
                    <br/><button class = "fa fa-search btn btn-success" th:value="Rechercher" name="bRechercher"> Rechercher</button></br></br></br>

                    <table class="table table-bordered" border="1">
                        <tbody>
                        <tr>
                            <th>Nom du cron</th>
                            <th>Serveur/Adresse IP</th>
                            <th>Application</th>
                            <th>Date de début</th>
                            <th>Date de fin</th>
                            <th>Statut</th>
                        </tr>
                        <tr th:each="event : ${lEvents}">
                            <td><p th:text="${event.cron.nom}"></p></td>
                            <td><p th:text="${event.cron.application.serveur.nom}"></p>/<p th:text="${event.cron.application.serveur.adresseIP}"></p></td>
                            <td><p th:text="${event.cron.application.nom}"></p></td>
                            <td th:text="${event.dateDebut}"></td>
                            <td th:text="${event.dateFin}"></td>
                            <td th:if="${event.statut == null}"><p th:text="${event.statut}"></p></td>
                            <td th:if="${event.statut != null}"><p th:text="${event.statut.label}"></p></td>
                        </tr>
                        </tbody>
                    </table><br/></br>
                    <center>
                        <div th:if="${lEvents.totalPages != 1}" class="form-group col-md-11 pagination-centered" style="cen">

                            <ul class="pagination">
                                <li th:class="${lEvents.number == 0} ? disabled">
                                    <a class="pageLink" th:href="@{/suiviCrons(pageSize=${selectedPageSize}, page=1, bRechercher='Rechercher', applicationName=${applicationName}, cronName=${cronName}, serverName=${serverName}, serverIP=${serverIP}, startDateEvent=${startDateEvent}, endDateEvent=${endDateEvent}, status=${status})}">&laquo;</a>
                                </li>
                                <li th:class="${lEvents.number == 0} ? disabled">
                                    <a class="pageLink" th:href="@{/suiviCrons(pageSize=${selectedPageSize}, page=${lEvents.number}, bRechercher='Rechercher', applicationName=${applicationName}, cronName=${cronName}, serverName=${serverName}, serverIP=${serverIP}, startDateEvent=${startDateEvent}, endDateEvent=${endDateEvent}, status=${status})}">&larr;</a>
                                </li>
                                <li th:class="${lEvents.number == (page - 1)} ? 'active pointer-disabled'"
                                    th:each="page : ${#numbers.sequence(pager.startPage, pager.endPage)}">
                                    <a class="pageLink" th:href="@{/suiviCrons(pageSize=${selectedPageSize}, page=${page}, bRechercher='Rechercher', applicationName=${applicationName}, cronName=${cronName}, serverName=${serverName}, serverIP=${serverIP}, startDateEvent=${startDateEvent}, endDateEvent=${endDateEvent}, status=${status})}" th:text="${page}"></a>
                                </li>
                                <li th:class="${lEvents.number + 1 == lEvents.totalPages} ? disabled">
                                    <a class="pageLink" th:href="@{/suiviCrons(pageSize=${selectedPageSize}, page=${lEvents.number + 2}, bRechercher='Rechercher', applicationName=${applicationName}, cronName=${cronName}, serverName=${serverName}, serverIP=${serverIP}, startDateEvent=${startDateEvent}, endDateEvent=${endDateEvent}, status=${status})}">&rarr;</a>
                                </li>
                                <li th:class="${lEvents.number + 1 == lEvents.totalPages} ? disabled">
                                    <a class="pageLink" th:href="@{/suiviCrons(pageSize=${selectedPageSize}, page=${lEvents.totalPages}, bRechercher='Rechercher', applicationName=${applicationName}, cronName=${cronName}, serverName=${serverName}, serverIP=${serverIP}, startDateEvent=${startDateEvent}, endDateEvent=${endDateEvent}, status=${status})}">&raquo;</a>
                                </li>
                                <li style="padding-left: 18px">
                                    <select class = "btn dropdown-toggle" id="pageSizeSelect">
                                        <option th:each="pageSize : ${pageSizes}" th:text="${pageSize}" th:value="${pageSize}" th:selected="${pageSize} == ${selectedPageSize}"></option>
                                    </select>
                                </li>
                            </ul>
                        </div>
                    </center>
                </form>
            </div>
        </div>
    </div>

</div>

</body>
</html>

控制器:

package com.leyton.cacron.frontend.controller;

import com.leyton.cacron.backend.bo.Application;
import com.leyton.cacron.backend.bo.Cron;
import com.leyton.cacron.backend.bo.Event;
import com.leyton.cacron.backend.repository.jpa.ApplicationRepo;
import com.leyton.cacron.backend.repository.jpa.CronRepo;
import com.leyton.cacron.backend.repository.jpa.CronRepoCustom;
import com.leyton.cacron.backend.repository.jpa.EventRepoCustom;
import com.leyton.cacron.backend.service.CronService;
import com.leyton.cacron.backend.service.EventService;
import com.leyton.cacron.backend.util.Pager;
import com.leyton.cacron.backend.util.Statut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import static com.leyton.cacron.frontend.util.WebPaths.SUIVCRONS;

@Controller
@RequestMapping(SUIVCRONS)
public class SuiviCronController {
    private static final int BUTTONS_TO_SHOW = 5;
    private static final int INITIAL_PAGE = 0;
    private static final int INITIAL_PAGE_SIZE = 5;
    private static final int[] PAGE_SIZES = { 5, 10, 20 };

    @Autowired
    private CronService cronService;

    @Autowired
    private EventService eventService;

    @Autowired
    private ApplicationRepo applicationRepo;

    @Autowired
    private EventRepoCustom eventRepoCustom;


    @Autowired
    private CronRepo cronRepo;

    public SuiviCronController(CronService cronService) {
        this.cronService = cronService;
    }

    @RequestMapping(method = RequestMethod.GET)
    public String findAllUsers(ModelMap model, HttpServletRequest request, HttpSession session, @RequestParam("pageSize") Optional<Integer> pageSize,
                               @RequestParam("page") Optional<Integer> page) {
        try {
            String bRechercher = request.getParameter("bRechercher");
            if(bRechercher == null) {
                String applicationName = request.getParameter("applicationName") == null? "":request.getParameter("applicationName");
                String cronName = request.getParameter("cronName") == null? "":request.getParameter("cronName");
                String serverName = request.getParameter("serverName") == null? "":request.getParameter("serverName");
                String serverIP = request.getParameter("serverIP") == null? "":request.getParameter("serverIP");
                String startDateCron = request.getParameter("startDateCron") == null? "":request.getParameter("startDateCron");
                String endDateCron = request.getParameter("endDateCron") == null? "":request.getParameter("endDateCron");
                String status = request.getParameter("status") == null? "":request.getParameter("status");
                // Evaluate page size. If requested parameter is null, return initial
                // page size
                int evalPageSize = pageSize.orElse(INITIAL_PAGE_SIZE);
                //int evalPageSize = Integer.parseInt(request.getParameter("listPageSizes"));
                // Evaluate page. If requested parameter is null or less than 0 (to
                // prevent exception), return initial size. Otherwise, return value of
                // param. decreased by 1.
                int evalPage = (page.orElse(0) < 1) ? INITIAL_PAGE : page.get() - 1;

                Page<Event> lEvents = eventService.findAllPageable(new PageRequest(evalPage, evalPageSize, new Sort(new Sort.Order(Sort.Direction.DESC, "dateDebut"))));
                List<Event> lEventsAll = eventService.findAll();
                //List<Cron> lCronAccueil = crons.getContent();
//                Date d1 = null;
//                for(Cron c4 : crons){
//                    d1 = c4.getHeure();
//                    d1.setHours(d1.getHours()-1);
//                    c4.setHeure(d1);
//                }

                Pager pager = new Pager(lEvents.getTotalPages(), lEvents.getNumber(), BUTTONS_TO_SHOW);
                List<Statut> lStatut = new ArrayList<>();
                lStatut.add(Statut.SANS_ERREUR);
                lStatut.add(Statut.AVEC_ERREUR);
                lStatut.add(Statut.DELAI_DEPASSE);
                lStatut.add(Statut.EXECUTION_INCOMPLETE);
                lStatut.add(Statut.NON_EXECUTE);

                List<Event> lApplication = eventRepoCustom.findEventByApplicationDistinct();
                List<Event> lCrons = eventRepoCustom.findEventByCronNameDistinct();
                List<Event> lServerNames  = eventRepoCustom.findEventByServerNameDistinct();
                List<Event> lServerIPs = eventRepoCustom.findEventByServerIPDistinct();

                model.addAttribute("lastSelected", applicationName);
                model.addAttribute("lApplication", lApplication);
                model.addAttribute("lCrons", lCrons);
                model.addAttribute("lServerNames", lServerNames);
                model.addAttribute("lServerIPs", lServerIPs);
                //model.addAttribute("applicationName", "Sélectionner");
                model.addAttribute("cronName", "Sélectionner");
                model.addAttribute("serverName", "Sélectionner");
                model.addAttribute("serverIP", "Sélectionner");
                model.addAttribute("status", "Sélectionner");
                model.addAttribute("lEvents", lEvents);
                model.addAttribute("lEventsAll", lEventsAll);
                model.addAttribute("lStatut", lStatut);
                model.addAttribute("selectedPageSize", evalPageSize);
                model.addAttribute("pageSizes", PAGE_SIZES);
                model.addAttribute("pager", pager);

            }
            else{

                String applicationName = request.getParameter("applicationName") == null? "":request.getParameter("applicationName");
                String cronName = request.getParameter("cronName") == null? "":request.getParameter("cronName");
                String serverName = request.getParameter("serverName") == null? "":request.getParameter("serverName");
                String serverIP = request.getParameter("serverIP") == null? "":request.getParameter("serverIP");
                String startDateEvent = request.getParameter("startDateEvent") == null? "":request.getParameter("startDateEvent");
                String endDateEvent = request.getParameter("endDateEvent") == null? "":request.getParameter("endDateEvent");
                String status = request.getParameter("status") == null? "":request.getParameter("status");

                Statut statut = null;
                if(Statut.AVEC_ERREUR.getLabel().equals(status))
                    statut = Statut.AVEC_ERREUR;
                else if(Statut.DELAI_DEPASSE.getLabel().equals(status))
                    statut = Statut.DELAI_DEPASSE;
                else if(Statut.NON_EXECUTE.getLabel().equals(status))
                    statut = Statut.NON_EXECUTE;
                else if(Statut.EXECUTION_INCOMPLETE.getLabel().equals(status))
                    statut = Statut.EXECUTION_INCOMPLETE;
                else if(Statut.SANS_ERREUR.getLabel().equals(status))
                    statut = Statut.SANS_ERREUR;

                int evalPageSize = pageSize.orElse(INITIAL_PAGE_SIZE);
                int evalPage = (page.orElse(0) < 1) ? INITIAL_PAGE : page.get() - 1;

                Page<Event> lEvents = eventRepoCustom.findCronBySrchFilterCriteria(applicationName, cronName, serverName, serverIP, startDateEvent, endDateEvent, statut, new PageRequest(evalPage, evalPageSize));

                Pager pager = new Pager(lEvents.getTotalPages(), lEvents.getNumber(), BUTTONS_TO_SHOW);

                List<Statut> lStatut = new ArrayList<>();
                lStatut.add(Statut.SANS_ERREUR);
                lStatut.add(Statut.AVEC_ERREUR);
                lStatut.add(Statut.DELAI_DEPASSE);
                lStatut.add(Statut.EXECUTION_INCOMPLETE);
                lStatut.add(Statut.NON_EXECUTE);

                List<Event> lEventsAll = eventService.findAll();

                List<Event> lApplication = eventRepoCustom.findEventByApplicationDistinct();
                List<Event> lCrons = eventRepoCustom.findEventByCronNameDistinct();
                List<Event> lServerNames  = eventRepoCustom.findEventByServerNameDistinct();
                List<Event> lServerIPs = eventRepoCustom.findEventByServerIPDistinct();

                model.addAttribute("lastSelected", applicationName);
                model.addAttribute("lApplication", lApplication);
                model.addAttribute("lCrons", lCrons);
                model.addAttribute("lServerNames", lServerNames);
                model.addAttribute("lServerIPs", lServerIPs);
                model.addAttribute("applicationName", applicationName);
                model.addAttribute("cronName", cronName);
                model.addAttribute("serverName", serverName);
                model.addAttribute("serverIP", serverIP);
                model.addAttribute("status", status);
                model.addAttribute("lEvents", lEvents);
                model.addAttribute("lEventsAll", lEventsAll);
                model.addAttribute("lStatut", lStatut);
                model.addAttribute("startDateEvent", startDateEvent);
                model.addAttribute("endDateEvent", endDateEvent);
                model.addAttribute("selectedPageSize", evalPageSize);
                model.addAttribute("pageSizes", PAGE_SIZES);
                model.addAttribute("pager", pager);
            }

        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return "suiviCrons";
    }
}

事件实体:

    @Entity
public class Event implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private Date dateDebut;
    private Date dateFin;
    private long dureeExecution;

    @Enumerated
    private Statut statut;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "cron_id")
    private Cron cron;

    public Event() {
    }

    public Event(Cron cron) {
        this.cron = cron;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Date getDateDebut() {
        return dateDebut;
    }

    public void setDateDebut(Date dateDebut) {
        this.dateDebut = dateDebut;
    }

    public Date getDateFin() {
        return dateFin;
    }

    public void setDateFin(Date dateFin) {
        this.dateFin = dateFin;
    }

    public long getDureeExecution() {
        return dureeExecution;
    }

    public void setDureeExecution(long dureeExecution) {
        this.dureeExecution = dureeExecution;
    }

    public Cron getCron() {
        return cron;
    }

    public void setCron(Cron cron) {
        this.cron = cron;
    }

    public Statut getStatut() {
        return statut;
    }

    public void setStatut(Statut statut) {
        this.statut = statut;
    }

}

1 个答案:

答案 0 :(得分:1)

尝试用以下内容替换您的选择:

<select class = "btn dropdown-toggle" th:value="${applicationName}" name="applicationName"  th:field="*{lApplication}">
  <option value="" selected="selected">Sélectionner</option>
  <option th:each="event : ${lApplication}" th:value="${event}" th:text="${event}" th:selected="${event} == ${lastSelected}"></option>
</select>

另外,您可以查看此thymeleaf forum