gpt4 book ai didi

java - Spring MVC 转换方法

转载 作者:行者123 更新时间:2023-12-01 23:06:48 24 4
gpt4 key购买 nike

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

我得到的答案是尝试实现 spring 转换服务。我就是这么做的(我想),现在我需要帮助来摆脱困境。问题是 View 将服务中的部件实例与包含所有部件的 partsAttribute 形式的部件实例进行比较,并且从不使用转换器,因此它不起作用。我没有收到任何错误...只是在 View 中,未选择零件。下面您将找到转换器、WebMVCConfig、PartRepository、ServiceController 和 html w/thymeleaf,供您引用。我究竟做错了什么???

转换器:

部分到字符串:

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

View 正确显示服务,只是它没有预选部分。

编辑服务:

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

然后我删除了转换器,只制作了一个可以发挥魔力的格式化程序。不要被这个名字迷惑了,它是格式化程序:

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。无法让 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>

最后,在经历了很多我无法弄清楚的麻烦和转换错误之后,更改了我的 Controller 更新方法:

@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 返回Part 不起作用。以及为什么 thymeleaf 不起作用......如果有人可以将我带到正确的方向,我将不胜感激!

最佳答案

Thymeleaf 使用 Spring 框架 SelectedValueComparator.isSelected 比较值(用于在选项 html 中包含 selected="selected"标签),这本质上首先依赖于 java 相等性。如果失败,它将回退到两个值的字符串表示形式。以下是其文档的摘录

<小时/>

用于测试候选值是否与数据绑定(bind)值匹配的实用程序类。热切地尝试通过多种途径来证明比较,以处理实例不平等、逻辑(基于字符串表示)相等和基于 PropertyEditor 的比较等问题。
为比较数组、集合和映射提供全面支持。
平等契约
对于单值对象,首先使用标准 Java 相等性来测试相等性。因此,用户代码应努力实现 Object.equals 以加快比较过程。如果 Object.equals 返回 false,则尝试进行详尽的比较,目的是证明相等性而不是反驳它。
接下来,尝试比较候选值和绑定(bind)值的字符串表示形式。在许多情况下,这可能会导致 true,因为这两个值在显示给用户时都将表示为字符串。
接下来,如果候选值是字符串,则尝试将绑定(bind)值与将相应的 PropertyEditor 应用到候选值的结果进行比较。此比较可以执行两次,一次针对直接 String 实例,然后如果第一次比较结果为 false,则针对 String 表示形式。

<小时/>

对于您的具体情况,我会写下转换服务,以便将我的零件对象转换为字符串,如 http://www.thymeleaf.org/doc/html/Thymeleaf-Spring3.html#configuring-a-conversion-service 中的 VarietyFormatter 中所述。 。发布此内容时,我将使用 th:value="${part}"并让 SelectedValueComparator 完成比较对象的魔力,并在 html 中添加 selected="selected"部分。

此外,在我的设计中,我总是基于主键实现 equals 方法(通常我在所有其他实体继承的顶级抽象实体中执行此操作)。这进一步增强了我的系统中域对象的自然比较。你在设计中也在做类似的事情吗?

希望对你有帮助!!

关于java - Spring MVC 转换方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22606627/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com