春季MVC转换如何[英] Spring MVC conversion HOW TO

问题描述

我有车辆服务,其中包括零件列表.添加新服务不是问题,而是查看服务不是问题,但是当我尝试实现编辑时,它不会预先选择零件列表.因此,我认为这是一个百里香问题,我发布了一个问题 there .

我得到的答案是尝试实现春季转换服务.我只是这样做(我想),现在我需要帮助才能使我摆脱困境.问题在于,视图比较了从服务中的零件与零件实例的实例形成包含所有零件的零件,并且从不使用转换器,因此它不起作用.我没有收到任何错误...仅根据视图,未选择零件. Bellow您会发现转换器,WebMvcconfig,Partrepository,ServiceController和HTML带有胸腺的HTML,供您参考.我究竟做错了什么???

转换器:

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");
        }
    }
}

StringTopart:

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

        @Resource
        private PartRepository partRepository;

        @Override
        public Part convert(final String idString) {
            if (idString.equals(NULL_REPRESENTATION)) {
                    return null;
            }
            try {
              Long id = Long.parseLong(idString);
              return this.partRepository.findByID(id);
            }
            catch (NumberFormatException e) {
                throw new RuntimeException("could not convert `" + id + "` to an valid id");
            }
        }
    }

WebMvcconfig的相关部分:

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
...
    @Bean(name="conversionService")
    public ConversionService getConversionService(){
        ConversionServiceFactoryBean bean = new ConversionServiceFactoryBean();
        bean.setConverters(getConverters());
        bean.afterPropertiesSet();
        ConversionService object = bean.getObject();
        return object;
    }
    private Set<Converter> getConverters() {
        Set<Converter> converters = new HashSet<Converter>();

        converters.add(new PartToStringConverter());
        converters.add(new StringToPartConverter());
        System.out.println("converters added");
        return converters;
    }
}

部分存储库看起来像这样:

@Repository
@Transactional(readOnly = true)
public class PartRepository {

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

    @PersistenceContext
    private EntityManager entityManager;

    @Transactional
    public Part update(Part part){
        try {
            entityManager.merge(part);
            return part;
        } catch (PersistenceException e) {
            return null;
        }
    }

    @SuppressWarnings("unchecked")
    public List<Part> getAllParts(){
        try {
            return entityManager.createQuery("from Part").getResultList();
        } catch (Exception e) {
            return new ArrayList<Part>();
        }
    }

    public Part findByID(Long id){
        try {
            return entityManager.find(Part.class, id);
        } catch (Exception e) {
            return new Part();
        }
    }
}

编辑ServiceController的部分:

    @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();
        }
}

视图正确显示服务,只是没有预选零件.

editservice:

<!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>

更新: 在Avnish的帮助下,我进行了几次更改,这就是我回到的:

添加转换服务不起作用,因此在研究和阅读文档后,返回并更改了我的webmvcconfig文件,因此代替@bean,我添加了此内容(我要做的就是查看WebMvcconfigurationsupport上的文档:

@Override
    protected void addFormatters(FormatterRegistry registry){
        registry.addFormatter(new PartTwoWayConverter());
    }

然后我删除了转换器,只制作了一个制作魔术的格式化器.不要对名称感到困惑,它是formater:

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");
        }
    }

}

然后我编辑了我的HTML.无法使胸腺锻炼,所以我这样做了:

<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();
    }

即使有效,我仍然不满意,因为此代码看起来更像是修补,而不是正确的编码.仍然感到困惑,为什么来自Partrepository的返回部分不起作用.以及为什么胸腺不起作用...如果有人可以将我送往正确的方向,我将非常感谢!

推荐答案

胸腺比较使用弹簧框架 selectedvaluecomparator.isselected ,比较 ,比较 .如果失败,它将返回到两个值的字符串表示.以下是从其文档中摘录


用于测试候选值是否匹配数据约束值的实用程序类.急切地试图通过许多途径来证明比较,以处理诸如实例不平等,逻辑(基于字符串代表)平等和基于属性的比较等问题.
提供了用于比较阵列,集合和地图的全部支持.
平等合同
对于单值对象,首先使用标准Java相等性测试平等.因此,用户代码应努力实现对象.等于加快比较过程.如果对象返回false,则在详尽的比较中进行尝试,目的是证明平等而不是反驳.
接下来,尝试比较候选人和绑定值的字符串表示形式.由于两个值将在向用户显示时,这可能会导致许多情况下的情况.
.
接下来,如果候选值是字符串,则试图将约束值与将相应的属性分配器应用于候选人的结果进行比较.该比较可以进行两次执行,一次与直接字符串实例相对,然后与字符串表示形式执行,如果第一个比较导致false.


对于您的具体情况,我会写下转换服务,以便将我的部分对象转换为 http://www.thymeleaf.org/doc/html/thymeleaf-spring3.html#configuring-a-convering-a-conversion-service .发布此信息,我将使用:value =" $ {part}",让SelectedValueComparator做到比较对象并在HTML中添加Selected =" Selected"部分的魔力.

在我的设计中,我始终基于主键实现等于方法(通常我在所有其他实体继承的顶级抽象实体上这样做).这进一步增强了整个系统中域对象的自然比较.您在设计中做类似的事情吗?

希望它有帮助!

其他推荐答案

我正在搜索另一件事,只是遇到了这篇文章,被认为可以分享一个实用,更简单的解决方案.

有时被淹没在技术中,不要让我们从开箱即用.

为此,浏览了转换器或格式化器的所有定义,我们可以简单地将对象设置(在这种情况下为零件)转换为字符串或动作方法中设置的启示,然后将其添加到模型中.

>

然后内部模板只需检查该集合是否包含任何选项值:

//In edit action:
Set<Long> selectedPartsLongSet = selectedParts.stream().map(Part::getId).collect(Collectors.toSet);
model.addAttribute("selectedPartsLongSet", selectedPartsLongSet);

在UI中:

<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>

本文地址:https://www.itbaoku.cn/post/978569.html