模型类可以实现模型用户界面吗?

huangapple go评论72阅读模式
英文:

Can model class implement Model UI?

问题

在我的Java代码中使用Spring Boot我以前使用模型或POJO对象来更好地控制我的对象等通常情况下我会创建实体存储库服务REST控制器就像文档和课程建议的那样
然而现在我正在使用Thymeleaf模板HTML还有一点Bootstrap和CSS来创建浏览器界面对于`@Controller`中的方法我将Spring Model UI中的Model作为参数传递像这样

```java
@GetMapping("/employees")
private String viewAllEmployees(Model employeeModel) {
    employeeModel.addAttribute("listEmployees", employeeService.getAllEmployees());
    return "employeeList";
}

我的问题是:我如何使用我的POJO对象来替代org.springframework.ui.Model

我第一个猜测是这样的:

public class EmployeeModel {
    
    private long employeeId;
    private String firstName;
    private String lastName;
    private String email;
    private String phone;
    private long companyId;
    //getter and setter methods
}

为了做到这一点,我必须@Override Model方法,这对我来说没问题。它看起来像是Java、Spring等在编译时不会出现问题,我可以在我的@Controller中像这样使用这个POJO对象:

@Controller
public class EmployeeController {
    @Autowired 
    private EmployeeService employeeService;    
    @GetMapping("/employees")
    private String viewAllEmployees(EmployeeModel employeeModel) {
        employeeModel.addAttribute("listEmployees", employeeService.getAllEmployees());
        return "employeeList";
    }
}

我运行代码,它启动了,显示了我的工作正常的/home端点,然而当我想要访问我的/employees端点,它应该显示我的员工列表时,它抛出了这个异常:

Method [private java.lang.String com.bojan.thyme.thymeApp.controller.EmployeeController.viewAllEmployees(com.bojan.thyme.thymeApp.model.EmployeeModel)] with argument values:[0] [type=org.springframework.validation.support.BindingAwareModelMap] [value={}] ] with root cause java.lang.IllegalArgumentException: argument type mismatch

请注意,REST控制器在浏览器和Postman中都正常工作。

是不是作为方法的String是问题所在?我的方法是否应该是其他类型,如List<EmployeeModel>或者可能是EmployeeModel本身?如果是这样的话,如何告诉方法我希望返回employeeList.html

我真诚地希望有人能够帮助我解决这个问题 模型类可以实现模型用户界面吗?


<details>
<summary>英文:</summary>

So far in my Java code with Spring Boot I was using models, or POJO objects to achieve better control of my objects, etc. Usually I am creating Entities, Repositories, Services, Rest controllers, just like documentation and courses are suggesting.
Now however I am working with Thymeleaf templates, HTML a bit of Bootstrap and CSS in order to create browser interface. For methods in `@Controller`, as parameter, I am passing Model from Spring Model UI like this:

    @GetMapping(&quot;/employees&quot;)
	private String viewAllEmployees(Model employeeModel) {
		employeeModel.addAttribute(&quot;listEmployees&quot;, employeeService.getAllEmployees());
		return &quot;employeeList&quot;;
	}

My question is: How can I use my POJO objects instead of org.springframework.ui.Model;?

My first guess was this:

    public class EmployeeModel implements Model{
	
	private long employeeId;
	private String firstName;
	private String lastName;
	private String email;
	private String phone;
	private long companyId;
	//getter and setter methods
    }

And in order to do that I have to `@Override` Model methods which is fine with me. And it looks like Java, Spring etc. does not complain in compile time, and I can use this POJO object in my `@Controller` like this:

    @Controller
    public class EmployeeController {
	@Autowired 
	private EmployeeService employeeService;	
	@GetMapping(&quot;/employees&quot;)
	private String viewAllEmployees(EmployeeModel employeeModel) {
		employeeModel.addAttribute(&quot;listEmployees&quot;, employeeService.getAllEmployees());
		return &quot;employeeList&quot;;
	}}

I run the code and it starts, shows my /home endpoint which works cool, however when I want to go to my /employees endpoing where it should show my eployees list it throws this: 

    Method [private java.lang.String com.bojan.thyme.thymeApp.controller.EmployeeController.viewAllEmployees(com.bojan.thyme.thymeApp.model.EmployeeModel)] with argument values:[0] [type=org.springframework.validation.support.BindingAwareModelMap] [value={}] ] with root cause java.lang.IllegalArgumentException: argument type mismatch

exception.

Please note that Rest controller is working perfectly in browser and Postman.

Is it possible that String as a method is the problem? Should my method be of some other type like `List&lt;EmployeeModel&gt;` or maybe `EmployeeModel ` itself? If it is so, how to tell the method that I want my employeeList.html to be returned?

I sincerely hope that someone can halp me with this one :)

</details>


# 答案1
**得分**: 1

&gt; 我怎样才能使用我的POJO对象替代org.springframework.ui.Model呢?

我认为当你使用Thymeleaf时,这不是最佳实践。根据他们的[文档][1],你应该将你的对象附加到你的Model中。所以在你的控制器中,你将操作包含你的POJO的模型。

示例:

```java
@RequestMapping(value = "message", method = RequestMethod.GET)
public ModelAndView messages() {
    ModelAndView mav = new ModelAndView("message/list");
    mav.addObject("messages", messageRepository.findAll());
    return mav;
}
英文:

> How can I use my POJO objects instead of org.springframework.ui.Model;?

I don't think that is the best practice when you are working with Thymeleaf. According to their documentation, you should attach your Objects to your Model. So in your controller you would be manipulating models that contain your Pojos.

Example:

 @RequestMapping(value = &quot;message&quot;, method = RequestMethod.GET)
    public ModelAndView messages() {
        ModelAndView mav = new ModelAndView(&quot;message/list&quot;);
        mav.addObject(&quot;messages&quot;, messageRepository.findAll());
        return mav;
    }

答案2

得分: 1

你应该始终将org.springframework.ui.Model用作参数。这个类基本上是一个带有键值对的Map,这些键值对可供Thymeleaf用于渲染。

你的第一个示例是正确的做法:

@GetMapping("/employees") //<1>
private String viewAllEmployees(Model model) {
    model.addAttribute("employees", employeeService.getAllEmployees()); //<2>
    return "employeeList"; //<3>
}
  • <1> 这是视图将要呈现在的URL
  • <2> 将任何你想要的Java对象作为属性添加到模型中
  • <3> 返回Thymeleaf模板的名称。在默认的Spring Boot与Thymeleaf应用程序中,这将引用位于src/main/resources/templates/employeeList.html的模板。在该模板中,你可以通过${employees}来访问模型的值。
英文:

You should always use org.springframework.ui.Model as argument. This class is basically a Map with key/value pairs that are made available to Thymeleaf for rendering.

Your first example is how you should do it:

@GetMapping(&quot;/employees&quot;) //&lt;1&gt;
private String viewAllEmployees(Model model) {
    model.addAttribute(&quot;employees&quot;, employeeService.getAllEmployees()); // &lt;2&gt;
    return &quot;employeeList&quot;; // &lt;3&gt;
}
  • <1> This is the URL that the view will be rendered on
  • <2> Add any Java object you want as attribute(s) to the model
  • <3> Return the name of the Thymeleaf template. In a default Spring Boot with Thymeleaf application, this will refer to the template at src/main/resources/templates/employeeList.html. In that template, you will be able to access your model value with ${employees}.

huangapple
  • 本文由 发表于 2020年9月15日 01:26:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/63889110.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定