无法将数据保存到 mysql db,在 gradle 项目中,bean 名称“goal”的 BindingResult 和普通目标对象都不能用作请求属性

Posted

技术标签:

【中文标题】无法将数据保存到 mysql db,在 gradle 项目中,bean 名称“goal”的 BindingResult 和普通目标对象都不能用作请求属性【英文标题】:not able to savedata to mysql db, in gradle project, Neither BindingResult nor plain target object for bean name 'goal' available as request attribute 【发布时间】:2015-08-22 11:12:05 【问题描述】:

我在看教程,我创建了用户登录并验证了用户,当我创建 addGoal 时,我的目标没有进入我的 mysql 数据库,因为我能够登录,所以我的数据库连接是正确的,我正在使用thymeleaf 和 javaconfig 用于我的注释,请帮我解决这个问题,我是新手。我认为我的 addGoal.html 中有错误,因为我使用的是 thymeleaf,我认为我没有正确执行,请有人帮我修复它,我认为我没有正确处理 @modelattribute

目标等级是:

package com.pluralsight.model;

import hello.User;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.validator.constraints.Range;
import org.springframework.web.bind.annotation.ModelAttribute;


@Entity
@Table(name="goals")

public class Goal 

	public static final String FIND_ALL_GOALS = "findALLGoals";
	public static final String FIND_GOAL_REPORTS = "findGoalReports";
	
	@Id
	@GeneratedValue
	@Column(name="GOAL_ID")
	private Long id;
	
	@Range(min = 1, max = 120)
	@Column(name="MINUTES")
	private int minutes;
	
//	@OneToMany(mappedBy="goal",cascade=CascadeType.ALL, fetch=FetchType.LAZY)
//	private List<Exercise> exercises = new ArrayList<Exercise>();
	
	@ManyToOne
	@JoinColumn(name="USER_NAME")
	private User user;
//	
//	public List<Exercise> getExercises() 
//		return exercises;
//	

	public User getUser() 
		return user;
	

	public void setUser(User user) 
		this.user = user;
	

	public Long getId() 
		return id;
	


	public int getMinutes() 
		return minutes;
	

//	public void setExercises(List<Exercise> exercises) 
//		this.exercises = exercises;
//	

	public void setId(Long id) 
		this.id = id;
	

	public void setMinutes(int minutes) 
		this.minutes = minutes;
	
	

这是我的目标控制器.java

package com.pluralsight.controller;

import java.util.List;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.pluralsight.model.Goal;
import com.pluralsight.model.GoalReport;
import com.pluralsight.model.User;
import com.pluralsight.service.GoalService;

@Controller
@SessionAttributes("goal")
public class GoalController 

	@Autowired
	private GoalService goalService;
	
	@RequestMapping(value = "addGoal", method = RequestMethod.GET)
	public String addGoal(Model model, HttpSession session ) 
		//Goal goal = new Goal();
		
		Goal goal = (Goal)session.getAttribute("goal");
		
		if(goal == null)
			goal = new Goal();
			goal.setMinutes(10);
		
		
		model.addAttribute("goal", goal);
		
		return "addGoal";
	
	
	@RequestMapping(value = "addGoal", method = RequestMethod.POST)
	public String updateGoal(@Valid @ModelAttribute Goal goal, BindingResult result) 
		
		System.out.println("result has errors: " + result.hasErrors());
		
		System.out.println("Goal set: " + goal.getMinutes());
		
		if(result.hasErrors()) 
			return "addGoal";
		else
			goalService.save(goal);
		
		
		return "redirect:index.jsp";
	
	
	@RequestMapping(value="getGoals", method= RequestMethod.GET)
	public String getGoals(Model model)
		List<Goal> goals = goalService.findAllGoals();
		model.addAttribute("goals", goals);
		return "getGoals";
	
	

	@RequestMapping(value="getGoalReports", method= RequestMethod.GET)
	public String getGoalReports(Model model)
		List<GoalReport> goalReports = goalService.findAllGoalReports();
		model.addAttribute("goalReports", goalReports);
		return "getGoalReports";
	

这是我的目标存储库

package com.pluralsight.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import org.springframework.stereotype.Repository;


import com.pluralsight.model.Goal;

@Repository("goalRepository")
public interface GoalRepository extends JpaRepository<Goal, Long>
	

这是我的 GoalServiceImpl.java

package com.pluralsight.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pluralsight.model.Goal;
import com.pluralsight.model.GoalReport;
import com.pluralsight.repository.GoalRepository;

@Service("goalService")
public class GoalServiceImpl implements GoalService 

	@Autowired
	private GoalRepository goalRepository;
	
	
	@Transactional
	public Goal save(Goal goal) 
		return goalRepository.save(goal);
	


	public List<Goal> findAllGoals() 
		
		return (List<Goal>) goalRepository.findAll();
	


	public List<GoalReport> findAllGoalReports() 
		return null;
//		return goalRepository.findAllGoalReports();
	

这是我的 addGoal.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:th="http://www.thymeleaf.org"
	xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>

</head>
<body>
	<div class="navbar navbar-fixed-top navbar-inverse">
		<div class="navbar-inner">
			<div class="container">
				<a class="brand" href="#"> Add Goal </a>
				<ul class="nav"></ul>
			</div>
		</div>
	</div>
	<div class="container">
		<div>
			<h1>Add Goal</h1>
			<p>Add your workout goal in minutes for the day.</p>
		</div>

		<form th:action="@/addGoal" method="post">
			<div>
				<label> Enter Minutes : <input type="text" name="minutes" />
				</label>
			</div>
			<div>
				<input type="submit" value="Submit" />
			</div>
		</form>

		<div class="control-group"></div>
	</div>
</body>
</html>

当我将 addGoal.html 中的表单更改为

		<form action="#" th:action="@/addGoal" th:object="$goal" method="post">
			<p> enter Minutes: <input type="text" th:field="*goal.minutes"/></p>
			<p><input type="submit" value="enter goal minutes"/></p>
			
		</form>

然后我收到错误:Bean 名称“目标”的 BindingResult 和普通目标对象都不能用作请求属性

【问题讨论】:

能否给我们看看目标类的代码 @Aeseir 我添加了目标类 你有两个不同的 addGoal.html 文件,你正在使用哪个? @Aeseir 当我在上面的 addGoal.html 中重播表单时,我收到错误“Bean name 'goal' 的 BindingResult 和普通目标对象都不能用作请求属性”,我是使用第一个addGoal.html,我的结果没有添加到我的数据库中,没有错误或警告,无论如何你指导我如何制作上面的演示,宁静的,我需要摆脱登录表单和所有,并制作它宁静 现在我正在使用 restful 服务 发送数据,现在当我添加目标时,错误如下:Error resolving template "addGoal", template might not exist or might not be accessible by any of the configured Template Resolvers 【参考方案1】:

让我们先退后一步关注躁动状态。 对于您的表单,请使用:

<form th:object="$goal" th:action="@/addGoal" method="post">
            <div>
                <label> Enter Minutes : <input type="text" th:field="*minutes" />
                </label>
            </div>
            <div>
                <input type="submit" value="Submit" />
            </div>
        </form>

下一个变化:

@RequestMapping(value = "addGoal", method = RequestMethod.GET)
    public String addGoal(Model model, HttpSession session ) 
        Goal goal = new Goal();

        Goal sessionGoal = (Goal)session.getAttribute("goal");

        if(sessionGoal == null && sessionGoal.getMinutes() == 0)
            goal.setMinutes(10);
        
else 
goal.setMinutes(sessionGoal.getMinutes());


        model.addAttribute("goal", goal);

        return "addGoal";
    

你也在做 return "redirect:index.jsp";然而你正在使用 Thymeleaf。这是行不通的。 您需要根据您的 home 参数“重定向:/index”或“重定向:/”。

编辑 1: 在 addGoal 的 POST 方法中更改以下行:

@RequestMapping(value = "addGoal", method = RequestMethod.POST)
    public String updateGoal(@Valid @ModelAttribute("goal") Goal goal, BindingResult result) 

【讨论】:

感谢回复,但是没有用,错误Neither BindingResult nor plain target object for bean name 'goal' available as request attribute,我有两个方法addGoal和updateGoal,在更新目标中我重定向到索引 添加了额外的更改以使其现在应该修复它 感谢您的时间,它已修复,我开始使用不同的项目进行练习

以上是关于无法将数据保存到 mysql db,在 gradle 项目中,bean 名称“goal”的 BindingResult 和普通目标对象都不能用作请求属性的主要内容,如果未能解决你的问题,请参考以下文章

将python中的值保存到mysql db

如何将从blob url获取的音频数据保存到mysql db中的文件系统和路径中

无法使用 MySQL 连接器/ODBC 将 Access DB 连接到 ODBC DSN

如何从 MySQL 数据库的内容中即时创建 Access DB 并在本地保存

NodeJS:无法将数据保存到 MySQL

将日期保存到数据库并使用 PHP 获取