Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Spring with Hibernate File Uploads and Entity Updates in Spring + Hibernate A File Upload Form in Thymeleaf

Sahil Chawla
Sahil Chawla
5,834 Points

HTML Form is not able to transfer one of the field values to controller.

I am working on a project where I have created two Model Classes named Environment and ApacheServer.

Apache Server class has @ManyToOne mapping with Environment class. I moved my Dao code from customized code to JPA Data Repositories and after making this change, my HTML form is not able to transfer environment.id value to controller.

The rest of the values are being passed.

ApacheServer Class: import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size;

@Entity public class ApacheServer { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;

@Column(unique = true)
@NotNull
@Size(min = 1, max = 10)
private String serverName;

@NotNull
@Size(min = 1, max = 30)
private String hostname;
private String ipAddress;
private String configPath;
private String logPath;
private String sslCertificatePath;
private String sslKeyFile;
private String sslWalletPath;
private String qosFile;
private String matchUrlPath;
private String restartScript;

public ApacheServer() {
}

@ManyToOne(optional = false,fetch = FetchType.LAZY,cascade = CascadeType.ALL)
private Environment environment;

Environment Class: @Entity public class Environment {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(unique = true)
@NotNull
@Size(min = 1, max = 10)
private String name;

@NotNull()
@Pattern(regexp = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]")
private String url;

@OneToMany(mappedBy = "environment")
private List<ApacheServer> apacheServers;

public Environment(){}

HTML Form: <div class="container"> <form th:action="@{/apache}" method="post" th:object="${apache}"> <div class="row"> <div class="col s12"> <h2>New Apache Server</h2> </div> </div> <div class="divider"></div> <div class="row"> <div class="col s12 l8" th:classappend="${#fields.hasErrors('serverName')}? 'error' : ''"> <input type="text" th:field="*{serverName}" placeholder="Apache Server Name"/> <div class="error-message" th:if="${#fields.hasErrors('serverName')}" th:errors="*{serverName}"></div> </div> </div> <div class="row"> <div class="col s12 l8" th:classappend="${#fields.hasErrors('hostname')}? 'error' : ''"> <input type="text" th:field="*{hostname}" placeholder="Hostname"/> <div class="error-message" th:if="${#fields.hasErrors('hostname')}" th:errors="*{hostname}"></div> </div> </div> <div class="row"> <div class="col s12 l8"> <select th:field="*{environment.id}" class="cs-select cs-skin-border"> <option value="1" disabled="disabled">Select an Environment</option> <option th:each="env : ${environments}" th:value="${env.id}" th:text="${env.name}" style="color:#59b3b3"></option> </select> </div> </div>

Controller Methods: @RequestMapping("/apache/add") public String addApacheServer(Model model){ if(!model.containsAttribute("apache")) { model.addAttribute("apache", new ApacheServer()); model.addAttribute("environments",environmentService.findAll()); } return "environment/components/Apache/form"; }

@RequestMapping(value = "/apache", method = RequestMethod.POST) public String addApacheServer(@Valid ApacheServer apacheServer, BindingResult bindingResult, RedirectAttributes redirectAttributes){ if(bindingResult.hasErrors()){ // Include validation errors upon redirect redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.apacheServer",bindingResult);

            // Redirect Back to the form
            redirectAttributes.addFlashAttribute("apache", apacheServer);
            return "redirect:/apache/add" ;
        }
        try {
            apacheServerService.save(apacheServer);
            redirectAttributes.addFlashAttribute("flash", new FlashMessage("Apache Server Successfully added!", FlashMessage.Status.SUCCESS));
            return String.format("redirect:/apache/%s", apacheServer.getId());
        }catch (Exception e){
            e.printStackTrace();
            redirectAttributes.addFlashAttribute("flash", new FlashMessage("Apache Server Couldn't be added! Please check Logs!", FlashMessage.Status.FAILURE));
            return "redirect:/apache";
        }

    }