Zeusox
Zeusox

Reputation: 8448

Send values from thymeleaf to a spring boot service class

I am testing a spring boot application which uses thymeleaf, but I could not find any docs explaining how to send select options values from thymeleaf to a spring boot service class.

Basically, what I am trying to achieve is get values from the select tag so that I can insert them to the database through the method below: Please note: this method is in the service class => it has both get and post mapping in the controller class.

public void addNewJob(JobPostEntity jobPostEntity, @RequestParam(value="selectCategory") String selectCategory) {
    jobPostEntity.setJobcategory("test");
    jobPostRepository.save(jobPostEntity);
}

the thymeleaf file is:

<form th:action="@{/newjob}" th:object="${addNewJob}" method="post">
        <div class="form-group">
            <label for="">Offer Title</label> 
            <input type="text" th:field="*{jobtitle}"  class="form-control" placeholder="Entre Offer Title">
                 <small class="form-text text-muted">We'll never share your email
                with anyone else.</small>
        </div>

        <div class="form-group">
            <label >Company Name</label>
             <input type="text" th:field="*{jobcompany}"  class="form-control" placeholder="Enter Company Name">
        </div>


        <div class="form-group dropdown">
            <label for="sel1">Choose Category (select one):</label> 
            <select name="*selectCategory"
                class="form-control" id="selectCategory"
                onchange="getSelectedValue();" th:field="*{selectCategory}">

                <option  value="">Select Option</option>
                <option  value="software_engineer">Software Engineer</option>
                <option value="graphic_design ">Graphic Design</option>
                <option value="customer_service ">Customer Service</option>
                <option value="marketing" >Marketing</option>
                <option value="healthcare">Health Care</option>

            </select>
        </div>

        <div class="form-group">
            <label for="exampleInputPassword1">Offer</label>
            <textarea class="form-control" th:field="*{jobtext}" placeholder="Describe your job offer"></textarea>
        </div>
        <button type="submit" class="btn btn-primary">Submit Offer</button>
    </form>

Upvotes: 0

Views: 2992

Answers (1)

gybandi
gybandi

Reputation: 1898

First, you need to properly configure your controller class. I assume this is where your addNewJob method is located, so I use this in my example. You need to have a @GetMapping (which is the same as @RequestMapping(method = RequestMethod.GET) that returns the name of the view (this is your thymeleaf file - in the example below I used jobForm.html for this) and maps to a specific path (/test in example).

  @GetMapping("/test")
  public String getTestView() {
    return "jobform";
  }

You will also need a method which creates/retrieve the model object you use to fill the form with. This is mapped as th:object=${addNewJob} in the form:

  @ModelAttribute(value = "addNewJob")
  public JobPostEntity newEntity() {
    return new JobPostEntity();
  }

Finally, you will need a method with @PostMapping, that's called when you submit your form. In your example, that's mapped to /newjob, so I used this too:

  @PostMapping(value = "/newjob")
  public void addNewJob(
      @ModelAttribute("addNewJob") final JobPostEntity myEntity) {
    System.out.println("got dto: " + myEntity);
    System.out.println("selectCategory: " + myEntity.getSelectedCategory());
  }

To summarize the controller would look something like this:

@Controller
public class TestController {

  @GetMapping("/test")
  public String getTestView() {
    return "jobform";
  }

  @PostMapping(value = "/newjob")
  public void addNewJob(
      @ModelAttribute("addNewJob") final JobPostEntity myEntity) {
    System.out.println("got dto: " + myEntity);
    System.out.println("selectCategory: " + selectCategory);
  }

  @ModelAttribute(value = "addNewJob")
  public JobPostEntity newEntity() {
    return new JobPostEntity();
  }

}

As for the select option to work, I'd also put that field in the modelAttribute, so you don't have to treat them separately:

public class JobPostEntity {

  private String jobtitle;
  private String jobcompany;
  private String jobtext;
  private String selectCategory;
 //getters/setters
}

Your pasted html code also contains a few issues:

  • you don't have the opening tags for form
  • the select tag doesn't have thymeleaf mapping for it (th:field)
  • the input tags doesn't have closing elements

The fixed version, which works for me, looks something like this (excluding the body/head/etc wrapper tags):

<form th:action="@{/newjob}" th:object="${addNewJob}" method="post">
        <div class="form-group">
            <label for="">Offer Title</label> 
            <input type="text" th:field="*{jobtitle}"  class="form-control" placeholder="Entre Offer Title" />
                 <small class="form-text text-muted">We'll never share your email
                with anyone else.</small>
        </div>

        <div class="form-group">
            <label >Company Name</label>
             <input type="text" th:field="*{jobcompany}"  class="form-control" placeholder="Enter Company Name"/>
        </div>


        <div class="form-group dropdown">
            <label for="sel1">Choose Category (select one):</label> 
            <select name="*selectCategory"
                class="form-control" id="selectCategory"
                onchange="getSelectedValue();"
                th:field="*{selectCategory}">

                <option value="">Select Option</option>
                <option value="software_engineer">Software Engineer</option>
                <option value="graphic_design ">Graphic Design</option>
                <option value="customer_service ">Customer Service</option>
                <option value="marketing" >Marketing</option>
                <option value="healthcare">Health Care</option>

            </select>
        </div>

        <div class="form-group">
            <label for="exampleInputPassword1">Offer</label>
            <textarea class="form-control" th:field="*{jobtext}" placeholder="Describe your job offer"></textarea>
        </div>
        <button type="submit" class="btn btn-primary">Submit Offer</button>
    </form>

if you start your application and type http://localhost:8080/test (if you use the default context path / port ) in your browser, the form should appear and work as expected.

also, you can find a pretty good tutorial on here http://www.baeldung.com/thymeleaf-in-spring-mvc

Upvotes: 2

Related Questions