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

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

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>&Uacute;ltima actualizaci&oacute;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&#180;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&lt;Actor, Integer&gt; {
}
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=&quot;/actor&quot;)
public class MainController {
@Autowired
private ActorRepository actorRepository;
@PostMapping(path=&quot;/add&quot;) 
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(&quot;yyyy/MM/dd HH:mm:ss&quot;);
String formattedDate = sdf.format(date);
a.setLast_update(formattedDate);
actorRepository.save(a);
return &quot;OK!&quot;;
}
@PostMapping(path=&quot;/delete&quot;)
public @ResponseBody String deleteActorById(@RequestParam int id) {
for(Actor a : this.actorRepository.findAll()) {
if(a.getActor_id() == id) {
this.actorRepository.deleteById(id);
return &quot;DELETED!&quot;;
}
}
return &quot;USER NOT FOUND &quot;+id;
}
public int getMaxId() {
int max = 0;
for(Actor a :actorRepository.findAll()) {
if(a.getActor_id() &gt; max) {
max = a.getActor_id();
}
}
return max;
}
@GetMapping(path=&quot;/all&quot;)
public String showActor(Model model) {
model.addAttribute(&quot;actors&quot;, this.actorRepository.findAll());
return &quot;actor&quot;;
}
}
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:
&lt;!DOCTYPE html&gt;
&lt;html xmlns:th=&quot;http://www.thymeleaf.org&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;UTF-8&quot;&gt;
&lt;title th:text=&quot;Listado de actores&quot;&gt;&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;ID&lt;/th&gt;
&lt;th&gt;Nombre&lt;/th&gt;
&lt;th&gt;Apellido&lt;/th&gt;
&lt;th&gt;&#218;ltima actualizaci&#243;n&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr th:each=&quot;actor : ${actors}&quot;&gt;
&lt;td th:each=&quot;${actor.actor_id}&quot;&gt;&lt;/td&gt;
&lt;td th:each=&quot;${actor.first_name}&quot;&gt;&lt;/td&gt;
&lt;td th:each=&quot;${actor.last_name}&quot;&gt;&lt;/td&gt;
&lt;td th:each=&quot;${actor.last_update}&quot;&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;/body&gt;
&lt;/html&gt;
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 &quot;OK!&quot;;`,因为这可能不是你的 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 &quot;OK!&quot;;` because that is not probably a name of html page that you have.
</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:

确定