有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JavaSpringMVC:表单如何将对象传输到控制器??总是400错误

当我尝试访问http://localhost:8080/XX/articles/addArticle
而提交表单时,总是会出现“400错误请求”错误。 我试着查找原因,我得到的只是从表单传输的对象与我的模型类型不同(,这是一个Article对象?这里)。然而,我认为我真的不明白

所有代码都在这里,配置都很好
以下是两种型号:
文章爪哇

@Entity
@Table(name="article_inf")
public class Article {
    private int articleId;
    private String title;
    private User author;
    private String content;
    public Article() {
    }
    public Article(String title, User author, String content) {
        this.title = title;
        this.author = author;
        this.content = content;
    }
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    public int getArticleId() {
        return articleId;
    }
    public void setArticleId(int articleId) {
        this.articleId = articleId;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    @ManyToOne(targetEntity=User.class)
    @JoinColumn(name="author", referencedColumnName="userId", nullable=false)
    public User getAuthor() {
        return author;
    }
    public void setAuthor(User author) {
        this.author = author;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }

用户。爪哇

@Entity
@Table(name="agri_user_inf")
public class User {
    private int userId;
    private String userName;
    private String password;
    private String cellPhone;
    private List<Article> articles;
    public User() {
        articles = new ArrayList<>();
    }
    public User(String userName, String password, String cellPhone) {
        this.userName = userName;
        this.password = password;
        this.cellPhone = cellPhone;
    }
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    public int getUserId() {
        return userId;
    }
    public void setUserId(int userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getCellPhone() {
        return cellPhone;
    }
    public void setCellPhone(String cellPhone) {
        this.cellPhone = cellPhone;
    }
    @OneToMany(targetEntity=Article.class, mappedBy="author")
    public List<Article> getArticles() {
        return articles;
    }
    public void setArticles(List<Article> articles) {
        this.articles = articles;
    }

控制器
财务总监。爪哇

@Controller
@RequestMapping("articles")
public class ArticleController {
    private ArticleDao articleDao;
    @Autowired
    public ArticleController(ArticleDao articleDao) {
        this.articleDao = articleDao;
    }
    @RequestMapping(value="addArticle", method=GET)
    public String addArticle(ModelMap modelMap) {
        List<User> authors = userDao.getAllUsers();
        // add all authors
        modelMap.addAttribute("authors", authors);
        return "articles/addArticleForm";
    }
    @RequestMapping(value="addArticle", method=POST)
    public String addArticle(Article article) {
        articleDao.addArticle(article);
        return "redirect:/articles";
    }
    // other code

我的表格是一张表格。jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <form method="post">
        title: <input type="text" name="title"/><br/>
        author: <select name="author">
                <c:forEach items="${authors}" var="author">
                    <option value="${author}">${author.userName}</option>
                </c:forEach>
            </select>
            <br/>
        content: <input type="text" name="content"/><br/>
        <input type="submit" value="add"/>
    </form>
</body>
</html>

共 (2) 个答案

  1. # 1 楼答案

    我得到了解决方案:

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
        <form method="post">
            title: <input type="text" name="title"/><br/>
            author: <select name="author.userId">
                    <c:forEach items="${authors}" var="author">
                        <option value="${author.userId}">${author.userName}</option>
                    </c:forEach>
                </select>
                <br/>
            content: <input type="text" name="content"/><br/>
            <input type="submit" value="add"/>
        </form>
    </body>
    </html>
    

    更改名称<;选择>;标记从“author”到“author.userId”。这很有效

  2. # 2 楼答案

    1. 你违反了休息原则。始终在端点和之后的资源名称中使用版本。示例-/api/v1/articles。之后,在HttpMethods的帮助下访问您的资源。示例-如果你想

    1.1添加新文章,使用POST请求到/api/v1/articles 1.2删除现有文章,使用delete请求/api/v1/articles/{articleId} 1.3获取一篇文章,使用get请求/api/v1/articles/{articleId} 1.4获取所有文章,使用get请求到/api/v1/Articles 1.5更新现有文章,使用PUT请求到/api/v1/articles/{articleId}

    1. 永远不要使用实体,它将在所有层的数据库中持久化。将实体与视图连接是一种不好的做法,相反,您可以使用DTO

    2. 在控制器层中使用与视图中同名的@ModelAttribute注释来处理传入的项目对象。范例

      公共字符串addArticle(@modeldattribute(“article”)article)

    3. 要首先添加新文章,您需要创建端点,该端点在ModelMap内返回空文章对象。然后,您必须在前端(JSP)中处理此问题,并按照步骤3提交此表单

    希望这会有所帮助