Spring为什么返回String而不是HTML视图

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

Why is Spring returning a String instead of HTML view

问题

  1. 我只会翻译代码部分,不包括代码注释和文件名。
  2. Actor.java
  3. ```java
  4. package com.dbtest.dbTest;
  5. import jakarta.persistence.Entity;
  6. import jakarta.persistence.Id;
  7. @Entity
  8. public class Actor {
  9. @Id
  10. private Integer actor_id;
  11. private String first_name;
  12. private String last_name;
  13. private String last_update;
  14. public Actor(Integer actor_id, String first_name, String last_name, String last_update) {
  15. this.actor_id = actor_id;
  16. this.first_name = first_name;
  17. this.last_name = last_name;
  18. this.last_update = last_update;
  19. }
  20. public Actor() {}
  21. public Integer getActor_id() {
  22. return actor_id;
  23. }
  24. public void setActor_id(Integer actor_id) {
  25. this.actor_id = actor_id;
  26. }
  27. public String getFirst_name() {
  28. return first_name;
  29. }
  30. public void setFirst_name(String first_name) {
  31. this.first_name = first_name;
  32. }
  33. public String getLast_name() {
  34. return last_name;
  35. }
  36. public void setLast_name(String last_name) {
  37. this.last_name = last_name;
  38. }
  39. public String getLast_update() {
  40. return last_update;
  41. }
  42. public void setLast_update(String last_update) {
  43. this.last_update = last_update;
  44. }
  45. }

ActorRepository.java:

  1. package com.dbtest.dbTest;
  2. import org.springframework.data.repository.CrudRepository;
  3. public interface ActorRepository extends CrudRepository<Actor, Integer> {
  4. }

MainController.java:

  1. package com.dbtest.dbTest;
  2. import java.util.Date;
  3. import java.text.SimpleDateFormat;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.ui.Model;
  6. import org.springframework.web.bind.annotation.*;
  7. @RestController
  8. @RequestMapping(path="/actor")
  9. public class MainController {
  10. @Autowired
  11. private ActorRepository actorRepository;
  12. @PostMapping(path="/add")
  13. public @ResponseBody String addNewActor(@RequestParam String first_name, @RequestParam String last_name) {
  14. Actor a = new Actor();
  15. a.setActor_id(this.getMaxId()+1);
  16. a.setFirst_name(first_name);
  17. a.setLast_name(last_name);
  18. Date date = new Date(System.currentTimeMillis());
  19. SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
  20. String formattedDate = sdf.format(date);
  21. a.setLast_update(formattedDate);
  22. actorRepository.save(a);
  23. return "OK!";
  24. }
  25. @PostMapping(path="/delete")
  26. public @ResponseBody String deleteActorById(@RequestParam int id) {
  27. for(Actor a : this.actorRepository.findAll()) {
  28. if(a.getActor_id() == id) {
  29. this.actorRepository.deleteById(id);
  30. return "DELETED!";
  31. }
  32. }
  33. return "USER NOT FOUND " + id;
  34. }
  35. public int getMaxId() {
  36. int max = 0;
  37. for(Actor a : actorRepository.findAll()) {
  38. if(a.getActor_id() > max) {
  39. max = a.getActor_id();
  40. }
  41. }
  42. return max;
  43. }
  44. @GetMapping(path="/all")
  45. public String showActor(Model model) {
  46. model.addAttribute("actors", this.actorRepository.findAll());
  47. return "actor";
  48. }
  49. }

DbTestApplication.java:

  1. package com.dbtest.dbTest;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public class DbTestApplication {
  6. public static void main(String[] args) {
  7. SpringApplication.run(DbTestApplication.class, args);
  8. }
  9. }

actor.html:

  1. <!DOCTYPE html>
  2. <html xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title th:text="Listado de actores"></title>
  6. </head>
  7. <body>
  8. <table>
  9. <thead>
  10. <tr>
  11. <th>ID</th>
  12. <th>Nombre</th>
  13. <th>Apellido</th>
  14. <th>&Uacute;ltima actualizaci&oacute;n</th>
  15. </tr>
  16. </thead>
  17. <tbody>
  18. <tr th:each="actor : ${actors}">
  19. <td th:text="${actor.actor_id}"></td>
  20. <td th:text="${actor.first_name}"></td>
  21. <td th:text="${actor.last_name}"></td>
  22. <td th:text="${actor.last_update}"></td>
  23. </tr>
  24. </tbody>
  25. </table>
  26. </body>
  27. </html>

application.properties:

  1. spring.jpa.hibernate.ddl-auto=update
  2. spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/sakila
  3. spring.datasource.username=root
  4. spring.datasource.password=root
  5. spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
  6. logging.level.root=INFO
  7. logging.file.name=spring.log
  1. <details>
  2. <summary>英文:</summary>
  3. I&#180;m just learning Spring framework and recently founded the mentioned problem doing a simple app which tries to connect with a mysql database.
  4. [Here is a screen capture][1]
  5. My code is here also:
  6. Actor.java:
  7. package com.dbtest.dbTest;
  8. import jakarta.persistence.Entity;
  9. import jakarta.persistence.Id;
  10. @Entity
  11. public class Actor {
  12. @Id
  13. private Integer actor_id;
  14. private String first_name;
  15. private String last_name;
  16. private String last_update;
  17. public Actor(Integer actor_id, String first_name, String last_name, String last_update) {
  18. this.actor_id = actor_id;
  19. this.first_name = first_name;
  20. this.last_name = last_name;
  21. this.last_update = last_update;
  22. }
  23. public Actor() {}
  24. public Integer getActor_id() {
  25. return actor_id;
  26. }
  27. public void setActor_id(Integer actor_id) {
  28. this.actor_id = actor_id;
  29. }
  30. public String getFirst_name() {
  31. return first_name;
  32. }
  33. public void setFirst_name(String first_name) {
  34. this.first_name = first_name;
  35. }
  36. public String getLast_name() {
  37. return last_name;
  38. }
  39. public void setLast_name(String last_name) {
  40. this.last_name = last_name;
  41. }
  42. public String getLast_update() {
  43. return last_update;
  44. }
  45. public void setLast_update(String last_update) {
  46. this.last_update = last_update;
  47. }
  48. }
  49. ActorRepository.java:
  50. package com.dbtest.dbTest;
  51. import org.springframework.data.repository.CrudRepository;
  52. //This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository
  53. //CRUD refers Create, Read, Update, Delete
  54. public interface ActorRepository extends CrudRepository&lt;Actor, Integer&gt; {
  55. }
  56. MainController.java:
  57. package com.dbtest.dbTest;
  58. import java.util.Date;
  59. import java.text.SimpleDateFormat;
  60. import org.springframework.beans.factory.annotation.Autowired;
  61. import org.springframework.ui.Model;
  62. import org.springframework.web.bind.annotation.GetMapping;
  63. import org.springframework.web.bind.annotation.PostMapping;
  64. import org.springframework.web.bind.annotation.RequestMapping;
  65. import org.springframework.web.bind.annotation.RequestParam;
  66. import org.springframework.web.bind.annotation.ResponseBody;
  67. import org.springframework.web.bind.annotation.RestController;
  68. @RestController
  69. @RequestMapping(path=&quot;/actor&quot;)
  70. public class MainController {
  71. @Autowired
  72. private ActorRepository actorRepository;
  73. @PostMapping(path=&quot;/add&quot;)
  74. public @ResponseBody String addNewActor(@RequestParam String first_name, @RequestParam String last_name) {
  75. Actor a = new Actor();
  76. a.setActor_id(this.getMaxId()+1);
  77. a.setFirst_name(first_name);
  78. a.setLast_name(last_name);
  79. Date date = new Date(System.currentTimeMillis());
  80. SimpleDateFormat sdf = new SimpleDateFormat(&quot;yyyy/MM/dd HH:mm:ss&quot;);
  81. String formattedDate = sdf.format(date);
  82. a.setLast_update(formattedDate);
  83. actorRepository.save(a);
  84. return &quot;OK!&quot;;
  85. }
  86. @PostMapping(path=&quot;/delete&quot;)
  87. public @ResponseBody String deleteActorById(@RequestParam int id) {
  88. for(Actor a : this.actorRepository.findAll()) {
  89. if(a.getActor_id() == id) {
  90. this.actorRepository.deleteById(id);
  91. return &quot;DELETED!&quot;;
  92. }
  93. }
  94. return &quot;USER NOT FOUND &quot;+id;
  95. }
  96. public int getMaxId() {
  97. int max = 0;
  98. for(Actor a :actorRepository.findAll()) {
  99. if(a.getActor_id() &gt; max) {
  100. max = a.getActor_id();
  101. }
  102. }
  103. return max;
  104. }
  105. @GetMapping(path=&quot;/all&quot;)
  106. public String showActor(Model model) {
  107. model.addAttribute(&quot;actors&quot;, this.actorRepository.findAll());
  108. return &quot;actor&quot;;
  109. }
  110. }
  111. DbTestApplication.java:
  112. package com.dbtest.dbTest;
  113. import org.springframework.boot.SpringApplication;
  114. import org.springframework.boot.autoconfigure.SpringBootApplication;
  115. @SpringBootApplication
  116. public class DbTestApplication {
  117. public static void main(String[] args) {
  118. SpringApplication.run(DbTestApplication.class, args);
  119. }
  120. }
  121. actor.html:
  122. &lt;!DOCTYPE html&gt;
  123. &lt;html xmlns:th=&quot;http://www.thymeleaf.org&quot;&gt;
  124. &lt;head&gt;
  125. &lt;meta charset=&quot;UTF-8&quot;&gt;
  126. &lt;title th:text=&quot;Listado de actores&quot;&gt;&lt;/title&gt;
  127. &lt;/head&gt;
  128. &lt;body&gt;
  129. &lt;table&gt;
  130. &lt;thead&gt;
  131. &lt;tr&gt;
  132. &lt;th&gt;ID&lt;/th&gt;
  133. &lt;th&gt;Nombre&lt;/th&gt;
  134. &lt;th&gt;Apellido&lt;/th&gt;
  135. &lt;th&gt;&#218;ltima actualizaci&#243;n&lt;/th&gt;
  136. &lt;/tr&gt;
  137. &lt;/thead&gt;
  138. &lt;tbody&gt;
  139. &lt;tr th:each=&quot;actor : ${actors}&quot;&gt;
  140. &lt;td th:each=&quot;${actor.actor_id}&quot;&gt;&lt;/td&gt;
  141. &lt;td th:each=&quot;${actor.first_name}&quot;&gt;&lt;/td&gt;
  142. &lt;td th:each=&quot;${actor.last_name}&quot;&gt;&lt;/td&gt;
  143. &lt;td th:each=&quot;${actor.last_update}&quot;&gt;&lt;/td&gt;
  144. &lt;/tr&gt;
  145. &lt;/tbody&gt;
  146. &lt;/table&gt;
  147. &lt;/body&gt;
  148. &lt;/html&gt;
  149. application.properties:
  150. spring.jpa.hibernate.ddl-auto=update
  151. spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/sakila
  152. spring.datasource.username=root
  153. spring.datasource.password=root
  154. spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
  155. logging.level.root=INFO
  156. logging.file.name=spring.log
  157. [Directory hierarchy here][2]
  158. Thanks in advance :)
  159. [1]: https://i.stack.imgur.com/fMGLc.png
  160. [2]: https://i.stack.imgur.com/AcZqK.png
  161. </details>
  162. # 答案1
  163. **得分**: 1
  164. `@Controller` 用于返回视图,`@RestController` 用于返回 JSON 响应。如果你想在 Thymeleaf 和 MVC 项目中使用,应该使用 `@Controller`。只需记住,在其他地方需要返回一个视图,而不是 `return &quot;OK!&quot;;`,因为这可能不是你的 HTML 页面的名称。
  165. <details>
  166. <summary>英文:</summary>
  167. `@Controller` is used to return a view, `@RestController` is used to return a JSON response. If you want to use thymeleaf and MVC project, you should be using `@Controller`
  168. Just keep in mind that that you need to return a view in other places not `return &quot;OK!&quot;;` because that is not probably a name of html page that you have.
  169. </details>

huangapple
  • 本文由 发表于 2023年4月19日 23:27:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76056298.html
匿名

发表评论

匿名网友

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

确定