Java Spring MVC转换如何实现

Java Spring MVC转换如何实现,java,spring-mvc,type-conversion,converter,thymeleaf,Java,Spring Mvc,Type Conversion,Converter,Thymeleaf,我有车辆服务,其中包括零件清单。添加新服务不是问题,查看服务也不是问题,但当我尝试实现编辑时,它不会预选部件列表。所以,我认为这是一个胸腺问题,我发布了这个问题 我得到的答案是尝试实现spring转换服务。我就是这么做的(我想),现在我需要帮助才能摆脱困境。问题是视图将来自服务的部件实例与包含所有部件的部件表单部件属性的实例进行比较,并且从不使用转换器,所以它不起作用。我没有收到任何错误。。。仅在视图中,未选择零件。 在下面,您将找到转换器、WebMVCConfig、PartRepository

我有车辆服务,其中包括零件清单。添加新服务不是问题,查看服务也不是问题,但当我尝试实现编辑时,它不会预选部件列表。所以,我认为这是一个胸腺问题,我发布了这个问题

我得到的答案是尝试实现spring转换服务。我就是这么做的(我想),现在我需要帮助才能摆脱困境。问题是视图将来自服务的部件实例与包含所有部件的部件表单部件属性的实例进行比较,并且从不使用转换器,所以它不起作用。我没有收到任何错误。。。仅在视图中,未选择零件。 在下面,您将找到转换器、WebMVCConfig、PartRepository、ServiceController和html w/thymeleaf,供您参考。我做错了什么

转换器:

PartToString:

    public class PartToStringConverter implements  Converter<Part, String> {   
    /** The string that represents null. */
    private static final String NULL_REPRESENTATION = "null";

    @Resource
    private PartRepository partRepository;

    @Override
    public String convert(final Part part) {
        if (part.equals(NULL_REPRESENTATION)) {
                return null;
        }
        try {
          return part.getId().toString();
        }
        catch (NumberFormatException e) {
            throw new RuntimeException("could not convert `" + part + "` to an valid id");
        }
    }
}
然后我删除了我的转换器,只制作了一个格式化程序来实现这个神奇的效果。不要被名称弄糊涂,它是格式化程序:

public class PartTwoWayConverter implements Formatter<Part>{

    /** The string that represents null. */
    private static final String NULL_REPRESENTATION = "null";

    @Resource
    private PartRepository partRepository;

    public PartTwoWayConverter(){
        super();
    }

    public Part parse(final String text, final Locale locale) throws ParseException{
        if (text.equals(NULL_REPRESENTATION)) {
            return null;
        }
        try {
            Long id = Long.parseLong(text);
        // Part part = partRepository.findByID(id); // this does not work with controller
        Part part = new Part(); // this works
        part.setId(id);         // 
        return part;
        }
        catch (NumberFormatException e) {
            throw new RuntimeException("could not convert `" + text + "` to an valid id");
        }       
    }

    public String print(final Part part, final Locale locale){
        if (part.equals(NULL_REPRESENTATION)) {
            return null;
        }
        try {
            return part.getId().toString();
        }
        catch (NumberFormatException e) {
            throw new RuntimeException("could not convert `" + part + "` to an valid id");
        }
    }

}
公共类PartTwoWayConverter实现格式化程序{
/**表示null的字符串*/
私有静态最终字符串NULL_REPRESENTATION=“NULL”;
@资源
私人零件库零件库;
公共部分双向转换器(){
超级();
}
公共部分解析(最终字符串文本、最终区域设置)引发ParseException{
if(text.equals(NULL_表示)){
返回null;
}
试一试{
Long id=Long.parseLong(文本);
//Part Part=partRepository.findByID(id);//这不适用于控制器
Part Part=新的Part();//这很有效
第.setId部分(id);//
返回部分;
}
捕获(数字格式){
抛出新的RuntimeException(“无法将“`+text+“`转换为有效id”);
}       
}
公共字符串打印(最终部分,最终区域设置){
if(部分等于(零表示)){
返回null;
}
试一试{
返回part.getId().toString();
}
捕获(数字格式){
抛出新的RuntimeException(“无法将“`”+part+“`转换为有效id”);
}
}
}
然后我编辑了我的HTML。无法使thymeleaf工作,所以我这样做:

<div class="form-group" th:class="${#fields.hasErrors('parts')} ? 'form-group has-error' : 'form-group'">
      <label for="parts" class="col-lg-2 control-label">Parts</label>
        <div class="col-lg-10">
            <select class="form-control" id="parts" name="parts" multiple="multiple" >
            <option th:each="part : ${partsAtribute}" 
                    th:selected="${servisAttribute.parts.contains(part)}"
                    th:value="${part.id}"
                    th:text="${part.name}">Part name and serial No.</option>
            </select>
          <p th:if="${#fields.hasErrors('parts')}" class="label label-danger" th:errors="*{parts}">Incorrect part ID</p>
        </div>
      </div>

部分
零件名称和序列号。

零件ID不正确

最后,在经历了许多我无法理解的麻烦和转换错误后,我改变了控制器更新方法:

@RequestMapping(value="/admin/servisi/editServis", method = RequestMethod.POST)
    public String saveEditServis(@ModelAttribute("servisAttribute") @Valid Servis servis, BindingResult result){
        logger.debug("Received request to save edit page");
        if (result.hasErrors()) 
        {
            logger.debug(result);
            String ret = "/admin/servis/editServis";
            return ret;
        }
        List<Part> list = new ArrayList<Part>();
        for (Part part : servis.getParts()) {
            list.add(partRepo.findByID(part.getId()));
        }
        Servis updating = servisRepository.getById(servis.getId());

        updating.setCompleted(servis.getCompleted());
        updating.setParts(list); // If just setting servis.getParts() it does not work
        updating.setServiceDate(servis.getServiceDate());
        updating.setServiceType(servis.getServiceType());

        servisRepository.update(updating);

        return "redirect:/admin/servisi/listServis?id="+servis.getVehicle().getVin();
    }
@RequestMapping(value=“/admin/servisi/editServis”,method=RequestMethod.POST)
公共字符串saveEditServis(@ModelAttribute(“servisAttribute”)@有效的Servis Servis,BindingResult){
debug(“收到保存编辑页的请求”);
if(result.hasErrors())
{
调试(结果);
字符串ret=“/admin/servis/editServis”;
返回ret;
}
列表=新的ArrayList();
for(部分:servis.getParts()){
add(partRepo.findByID(part.getId());
}
Servis updating=servisRepository.getById(Servis.getId());
更新.setCompleted(servis.getCompleted());
更新.setParts(list);//如果只是设置servis.getParts(),它就不起作用
更新.setServiceDate(servis.getServiceDate());
更新.setServiceType(servis.getServiceType());
服务存储更新(更新);
return“redirect:/admin/servisi/listServis?id=“+servis.getVehicle().getVin()”;
}
即使这样做有效,我仍然不高兴,因为这段代码看起来更像是修补而不是正确的编码。仍然不明白为什么从partRepository返回的部件不起作用。为什么百里香不起作用。。。如果有人能把我送到正确的方向,我将不胜感激

Thymeleaf使用spring frameworksSelectedValueComparator.isSelected比较值(用于在选项html中包含selected=“selected”标记),它首先本质上取决于java相等性。如果失败,则返回两个值的字符串表示。以下是它的文档摘录


用于测试候选值是否与数据绑定值匹配的实用程序类。热切地尝试通过多种途径来证明比较,以解决实例不平等、逻辑(基于字符串表示)平等和基于属性编辑器的比较等问题。
完全支持比较阵列、集合和地图。
平等合同
对于单值对象,首先使用标准Java相等性测试相等性。因此,用户代码应该努力实现Object.equals以加快比较过程。如果Object.equals返回false,则尝试进行详尽的比较,目的是证明相等,而不是反驳相等。
接下来,尝试比较候选值和绑定值的字符串表示形式。这可能导致在许多情况下为真,因为当向用户显示时,两个值都将表示为字符串。
接下来,如果候选值是字符串,则尝试将绑定值与对候选值应用相应PropertyEditor的结果进行比较。此比较可以执行两次,一次针对直接字符串实例,如果第一次比较结果为false,则执行一次针对字符串表示


对于您的特定情况,我将写下转换服务,以便将我的part对象转换为字符串,如中的VarietyFormatter所述。发布本文时,我会使用th:value=“${part}”,让SelectedValueComparator执行比较对象的神奇操作,并在html中添加selected=“selected”部分

艾尔
    @Controller
    @RequestMapping("/")
    public class ServisController {

        protected static Logger logger = Logger.getLogger("controller");

        @Autowired
        private ServisRepository servisRepository;
        @Autowired
        private ServisTypeRepository servisTypeRepo;
        @Autowired
        private PartRepository partRepo;
        @Autowired
        private VehicleRepository2 vehicleRepository;   

        /*-- **************************************************************** -*/
    /*--  Editing servis methods                                          -*/
    /*--                                                                  -*/
    /*-- **************************************************************** -*/

        @RequestMapping(value="/admin/servisi/editServis", method = RequestMethod.GET)
        public String getEditServis(@RequestParam(value="id", required=true) Long id, Model model){
            logger.debug("Received request to show edit page");

            List<ServisType> servisTypeList = servisTypeRepo.getAllST();
            List<Part> partList = partRepo.getAllParts();
            List<Part> selectedParts = new ArrayList<Part>();
            Servis s = servisRepository.getById(id);
            for (Part part : partList) {
                for (Part parts : s.getParts()) {
                    if(part.getId()==parts.getId()){
                        selectedParts.add(part);
                        System.out.println(part);
                    }
                }
            }
            s.setParts(selectedParts);

            logger.debug("radjeni dijelovi " + s.getParts().toString());
            logger.debug("radjeni dijelovi " + s.getParts().size());
            s.setVehicle(vehicleRepository.findByVin(s.getVehicle().getVin()));
            model.addAttribute("partsAtribute", partList);
            model.addAttribute("servisTypesAtribute", servisTypeList);
            model.addAttribute("servisAttribute", s);

            return "/admin/servis/editServis";
        }

        @RequestMapping(value="/admin/servisi/editServis", method = RequestMethod.POST)
        public String saveEditServis(@ModelAttribute("servisAttribute") @Valid Servis servis, BindingResult result){
            logger.debug("Received request to save edit page");
            if (result.hasErrors()) 
            {
                String ret = "/admin/servis/editServis";
                return ret;
            }

            servisRepository.update(servis);

            return "redirect:/admin/servisi/listServis?id="+servis.getVehicle().getVin();
        }
}
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring3-3.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:th="http://www.thymeleaf.org">
<head th:include="fragments/common :: headFragment">
<title>Edit Vehicle Service</title>
</head>
<body>

<div th:include="fragments/common :: adminHeaderFragment"></div>

<div class="container">

<section id="object">
  <div class="page-header">
    <h1>Edit service</h1>
  </div>

<div class="row">

    <form action="#" th:object="${servisAttribute}"
        th:action="@{/admin/servisi/editServis}" method="post" class="form-horizontal well">

        <input type="hidden" th:field="*{vehicle.vin}" class="form-control input-xlarge" />
          <div class="form-group" th:class="${#fields.hasErrors('vehicle.vin')} ? 'form-group has-error' : 'form-group'">
          <label for="vehicle.licensePlate" class="col-lg-2 control-label">License Plate</label>
            <div class="col-lg-10">
                <input type="text" th:field="*{vehicle.licensePlate}" class="form-control input-xlarge" placeholder="License Plate" readonly="readonly"/>
              <p th:if="${#fields.hasErrors('vehicle.licensePlate')}" class="label label-danger" th:errors="*{vehicle.licensePlate}">Incorrect LP</p>
            </div>
          </div>    
          <div class="form-group" th:class="${#fields.hasErrors('serviceDate')} ? 'form-group has-error' : 'form-group'">
          <label for="serviceDate" class="col-lg-2 control-label">Servis Date: </label>
            <div class="col-lg-10">
              <input type="date" th:field="*{serviceDate}" class="form-control input-xlarge" placeholder="Servis Date" />
              <p th:if="${#fields.hasErrors('serviceDate')}" class="label label-danger" th:errors="*{serviceDate}">Incorrect Date</p>
            </div>
          </div>
          <div class="form-group" th:class="${#fields.hasErrors('serviceType.id')} ? 'form-group has-error' : 'form-group'">
          <label for="serviceType.id" class="col-lg-2 control-label">Vrsta Servisa</label>
            <div class="col-lg-10">
                <select th:field="*{serviceType.id}" class="form-control">
                <option th:each="servisType : ${servisTypesAtribute}" 
                        th:value="${servisType.id}" th:selected="${servisType.id==servisAttribute.serviceType.id}"
                        th:text="${servisType.name}">Vrsta Servisa</option>
                </select>
              <p th:if="${#fields.hasErrors('serviceType.id')}" class="label label-danger" th:errors="${serviceType.id}">Incorrect VIN</p>
            </div>
          </div>
          <div class="form-group" th:class="${#fields.hasErrors('parts')} ? 'form-group has-error' : 'form-group'">
          <label for="parts" class="col-lg-2 control-label">Parts</label>
            <div class="col-lg-10">
                <select class="form-control" th:field="*{parts}" multiple="multiple" >
                <option th:each="part : ${partsAtribute}" 
                        th:field="*{parts}"
                        th:value="${part.id}"
                        th:text="${part.Name}">Part name and serial No.</option>
                </select>
              <p th:if="${#fields.hasErrors('parts')}" class="label label-danger" th:errors="*{parts}">Incorrect part ID</p>
            </div>
          </div>
          <div class="form-group" th:class="${#fields.hasErrors('completed')} ? 'form-group has-error' : 'form-group'">
          <label for="completed" class="col-lg-2 control-label">Is service completed?</label>
            <div class="col-lg-10">
              <select th:field="*{completed}" class="form-control">
                <option value="true">Yes</option>
                <option value="false">No</option>
              </select>
              <p th:if="${#fields.hasErrors('completed')}" class="label label-danger" th:errors="*{completed}">Incorrect checkbox</p>
            </div>
          </div>
        <hr/>
          <div class="form-actions">
            <button type="submit" class="btn btn-primary">Edit Service</button>
            <a class="btn btn-default" th:href="@{/admin/servisi/listServis(id=${servisAttribute.vehicle.vin})}">Cancel</a>
          </div>
    </form>

</div>
</section>

<div class="row right">
  <a class="btn btn-primary btn-large" th:href="@{/admin/part/listPart}">Back to list</a>
</div> 

<div th:include="fragments/common :: footerFragment"></div>
</div>
<!-- /.container -->
<div th:include="fragments/common :: jsFragment"></div>

</body>
</html>
@Override
    protected void addFormatters(FormatterRegistry registry){
        registry.addFormatter(new PartTwoWayConverter());
    }
public class PartTwoWayConverter implements Formatter<Part>{

    /** The string that represents null. */
    private static final String NULL_REPRESENTATION = "null";

    @Resource
    private PartRepository partRepository;

    public PartTwoWayConverter(){
        super();
    }

    public Part parse(final String text, final Locale locale) throws ParseException{
        if (text.equals(NULL_REPRESENTATION)) {
            return null;
        }
        try {
            Long id = Long.parseLong(text);
        // Part part = partRepository.findByID(id); // this does not work with controller
        Part part = new Part(); // this works
        part.setId(id);         // 
        return part;
        }
        catch (NumberFormatException e) {
            throw new RuntimeException("could not convert `" + text + "` to an valid id");
        }       
    }

    public String print(final Part part, final Locale locale){
        if (part.equals(NULL_REPRESENTATION)) {
            return null;
        }
        try {
            return part.getId().toString();
        }
        catch (NumberFormatException e) {
            throw new RuntimeException("could not convert `" + part + "` to an valid id");
        }
    }

}
<div class="form-group" th:class="${#fields.hasErrors('parts')} ? 'form-group has-error' : 'form-group'">
      <label for="parts" class="col-lg-2 control-label">Parts</label>
        <div class="col-lg-10">
            <select class="form-control" id="parts" name="parts" multiple="multiple" >
            <option th:each="part : ${partsAtribute}" 
                    th:selected="${servisAttribute.parts.contains(part)}"
                    th:value="${part.id}"
                    th:text="${part.name}">Part name and serial No.</option>
            </select>
          <p th:if="${#fields.hasErrors('parts')}" class="label label-danger" th:errors="*{parts}">Incorrect part ID</p>
        </div>
      </div>
@RequestMapping(value="/admin/servisi/editServis", method = RequestMethod.POST)
    public String saveEditServis(@ModelAttribute("servisAttribute") @Valid Servis servis, BindingResult result){
        logger.debug("Received request to save edit page");
        if (result.hasErrors()) 
        {
            logger.debug(result);
            String ret = "/admin/servis/editServis";
            return ret;
        }
        List<Part> list = new ArrayList<Part>();
        for (Part part : servis.getParts()) {
            list.add(partRepo.findByID(part.getId()));
        }
        Servis updating = servisRepository.getById(servis.getId());

        updating.setCompleted(servis.getCompleted());
        updating.setParts(list); // If just setting servis.getParts() it does not work
        updating.setServiceDate(servis.getServiceDate());
        updating.setServiceType(servis.getServiceType());

        servisRepository.update(updating);

        return "redirect:/admin/servisi/listServis?id="+servis.getVehicle().getVin();
    }
//In edit action:
Set<Long> selectedPartsLongSet = selectedParts.stream().map(Part::getId).collect(Collectors.toSet);
model.addAttribute("selectedPartsLongSet", selectedPartsLongSet);
<select class="form-control" id="parts" name="parts" multiple="multiple" >
            <option th:each="part : ${partsAtribute}" 
                    th:selected="${selectedPartsLongSet.contains(part.id)}"
                    th:value="${part.id}"
                    th:text="${part.name}">Part name and serial No.</option>
            </select>