Spring MVC转换如何
问题内容:
我的车辆服务包括零件清单。添加新服务不是问题,查看服务也不是问题,但是当我尝试实现编辑时,它不会预先选择零件列表。因此,考虑到这是Thymeleaf的问题,我在此处发布问题。
我得到的答案是尝试实现spring转换服务。我只是这样做了(我认为),现在我需要帮助才能摆脱困境。问题在于,视图将服务中的零件实例与包含所有零件的partsAttribute零件形式的实例进行比较,并且从不使用转换器,因此它不起作用。我没有收到任何错误…在视图中,未选择零件。在下面,您可以找到转换器,WebMVCConfig,PartRepository,ServiceController和带有百里香叶的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());
}
然后,我删除了转换器,只制作了一个能发挥作用的格式化程序。请勿混淆名称,它是格式化程序:
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返回Part无效。以及为什么百里香无法工作…如果有人可以将我送往正确的方向,我将不胜感激!
问题答案:
Thymeleaf使用Spring框架 SelectedValueComparator.isSelected
比较值(用于在选项html中包含selected =“
selected”标记),该框架固有地首先依赖于Java相等性。如果失败,则返回两个值的字符串表示形式。以下是其文档摘录
用于测试候选值是否与数据绑定值匹配的实用程序类。急于尝试通过多种途径来证明比较,以解决实例不平等,逻辑(基于字符串表示)的相等性和基于PropertyEditor的比较等问题。
提供了全面的比较数组,集合和映射的支持。
平等合同
对于单值对象,平等首先使用标准Java平等进行测试。因此,用户代码应努力实现Object.equals以加快比较过程。如果Object.equals返回false,则尝试进行详尽的比较,目的是证明平等而不是证明平等。
接下来,尝试比较候选值和绑定值的字符串表示形式。由于在显示给用户时两个值都将表示为字符串,因此在许多情况下这可能会导致结果为true。
接下来,如果候选值为字符串,则尝试将绑定值与将对应的PropertyEditor应用于候选的结果进行比较。该比较可以执行两次,一次是针对直接的String实例,然后是第一次的比较结果为false时,针对字符串表示形式。
对于您的特定情况,我会记下转换服务,以便将我的part对象转换为字符串,如http://www.thymeleaf.org/doc/html/Thymeleaf-
Spring3.html#configuring-a-中针对VarietyFormatter所述。
conversion-service。发布此内容后,我将使用th:value =“ $
{part}”并让SelectedValueComparator做比较对象的魔术,并在html中添加selected =“ selected”部分。
同样在我的设计中,我总是基于主键实现equals方法(通常是在所有其他实体都从其继承的顶级抽象实体上执行)。这进一步增强了整个系统中域对象的自然比较。您是否在设计中做了类似的事情?
希望能帮助到你!!