英文:
Why is Spring returning a String instead of HTML view
问题
我只会翻译代码部分,不包括代码注释和文件名。
Actor.java:
```java
package com.dbtest.dbTest;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
@Entity
public class Actor {
@Id
private Integer actor_id;
private String first_name;
private String last_name;
private String last_update;
public Actor(Integer actor_id, String first_name, String last_name, String last_update) {
this.actor_id = actor_id;
this.first_name = first_name;
this.last_name = last_name;
this.last_update = last_update;
}
public Actor() {}
public Integer getActor_id() {
return actor_id;
}
public void setActor_id(Integer actor_id) {
this.actor_id = actor_id;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getLast_update() {
return last_update;
}
public void setLast_update(String last_update) {
this.last_update = last_update;
}
}
ActorRepository.java:
package com.dbtest.dbTest;
import org.springframework.data.repository.CrudRepository;
public interface ActorRepository extends CrudRepository<Actor, Integer> {
}
MainController.java:
package com.dbtest.dbTest;
import java.util.Date;
import java.text.SimpleDateFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(path="/actor")
public class MainController {
@Autowired
private ActorRepository actorRepository;
@PostMapping(path="/add")
public @ResponseBody String addNewActor(@RequestParam String first_name, @RequestParam String last_name) {
Actor a = new Actor();
a.setActor_id(this.getMaxId()+1);
a.setFirst_name(first_name);
a.setLast_name(last_name);
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String formattedDate = sdf.format(date);
a.setLast_update(formattedDate);
actorRepository.save(a);
return "OK!";
}
@PostMapping(path="/delete")
public @ResponseBody String deleteActorById(@RequestParam int id) {
for(Actor a : this.actorRepository.findAll()) {
if(a.getActor_id() == id) {
this.actorRepository.deleteById(id);
return "DELETED!";
}
}
return "USER NOT FOUND " + id;
}
public int getMaxId() {
int max = 0;
for(Actor a : actorRepository.findAll()) {
if(a.getActor_id() > max) {
max = a.getActor_id();
}
}
return max;
}
@GetMapping(path="/all")
public String showActor(Model model) {
model.addAttribute("actors", this.actorRepository.findAll());
return "actor";
}
}
DbTestApplication.java:
package com.dbtest.dbTest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DbTestApplication {
public static void main(String[] args) {
SpringApplication.run(DbTestApplication.class, args);
}
}
actor.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title th:text="Listado de actores"></title>
</head>
<body>
<table>
<thead>
<tr>
<th>ID</th>
<th>Nombre</th>
<th>Apellido</th>
<th>Última actualización</th>
</tr>
</thead>
<tbody>
<tr th:each="actor : ${actors}">
<td th:text="${actor.actor_id}"></td>
<td th:text="${actor.first_name}"></td>
<td th:text="${actor.last_name}"></td>
<td th:text="${actor.last_update}"></td>
</tr>
</tbody>
</table>
</body>
</html>
application.properties:
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/sakila
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
logging.level.root=INFO
logging.file.name=spring.log
<details>
<summary>英文:</summary>
I´m just learning Spring framework and recently founded the mentioned problem doing a simple app which tries to connect with a mysql database.
[Here is a screen capture][1]
My code is here also:
Actor.java:
package com.dbtest.dbTest;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
@Entity
public class Actor {
@Id
private Integer actor_id;
private String first_name;
private String last_name;
private String last_update;
public Actor(Integer actor_id, String first_name, String last_name, String last_update) {
this.actor_id = actor_id;
this.first_name = first_name;
this.last_name = last_name;
this.last_update = last_update;
}
public Actor() {}
public Integer getActor_id() {
return actor_id;
}
public void setActor_id(Integer actor_id) {
this.actor_id = actor_id;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getLast_update() {
return last_update;
}
public void setLast_update(String last_update) {
this.last_update = last_update;
}
}
ActorRepository.java:
package com.dbtest.dbTest;
import org.springframework.data.repository.CrudRepository;
//This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository
//CRUD refers Create, Read, Update, Delete
public interface ActorRepository extends CrudRepository<Actor, Integer> {
}
MainController.java:
package com.dbtest.dbTest;
import java.util.Date;
import java.text.SimpleDateFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(path="/actor")
public class MainController {
@Autowired
private ActorRepository actorRepository;
@PostMapping(path="/add")
public @ResponseBody String addNewActor(@RequestParam String first_name, @RequestParam String last_name) {
Actor a = new Actor();
a.setActor_id(this.getMaxId()+1);
a.setFirst_name(first_name);
a.setLast_name(last_name);
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String formattedDate = sdf.format(date);
a.setLast_update(formattedDate);
actorRepository.save(a);
return "OK!";
}
@PostMapping(path="/delete")
public @ResponseBody String deleteActorById(@RequestParam int id) {
for(Actor a : this.actorRepository.findAll()) {
if(a.getActor_id() == id) {
this.actorRepository.deleteById(id);
return "DELETED!";
}
}
return "USER NOT FOUND "+id;
}
public int getMaxId() {
int max = 0;
for(Actor a :actorRepository.findAll()) {
if(a.getActor_id() > max) {
max = a.getActor_id();
}
}
return max;
}
@GetMapping(path="/all")
public String showActor(Model model) {
model.addAttribute("actors", this.actorRepository.findAll());
return "actor";
}
}
DbTestApplication.java:
package com.dbtest.dbTest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DbTestApplication {
public static void main(String[] args) {
SpringApplication.run(DbTestApplication.class, args);
}
}
actor.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title th:text="Listado de actores"></title>
</head>
<body>
<table>
<thead>
<tr>
<th>ID</th>
<th>Nombre</th>
<th>Apellido</th>
<th>Última actualización</th>
</tr>
</thead>
<tbody>
<tr th:each="actor : ${actors}">
<td th:each="${actor.actor_id}"></td>
<td th:each="${actor.first_name}"></td>
<td th:each="${actor.last_name}"></td>
<td th:each="${actor.last_update}"></td>
</tr>
</tbody>
</table>
</body>
</html>
application.properties:
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/sakila
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
logging.level.root=INFO
logging.file.name=spring.log
[Directory hierarchy here][2]
Thanks in advance :)
[1]: https://i.stack.imgur.com/fMGLc.png
[2]: https://i.stack.imgur.com/AcZqK.png
</details>
# 答案1
**得分**: 1
`@Controller` 用于返回视图,`@RestController` 用于返回 JSON 响应。如果你想在 Thymeleaf 和 MVC 项目中使用,应该使用 `@Controller`。只需记住,在其他地方需要返回一个视图,而不是 `return "OK!";`,因为这可能不是你的 HTML 页面的名称。
<details>
<summary>英文:</summary>
`@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`
Just keep in mind that that you need to return a view in other places not `return "OK!";` because that is not probably a name of html page that you have.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论