2

I am trying to get a value from thymeleaf input into my java class.

Simple script from thymeleaf:

<input type="text" id="datePlanted" name="datePlanted" th:value="*{datePlanted}"/>

How would I be able to retrieve datPlanted into my java class?

Attempted the following servlet tutorial:

@WebServlet("/")
public class LoginServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException, IOException {
        // read form fields
        String username = request.getParameter("datePlanted");

        System.out.println("date: " + datePlanted);

        // do some processing here...
        // get response writer
        PrintWriter writer = response.getWriter();
        // return response
        writer.println(htmlRespone);
    }
}

I tried to follow a tutorial but I am not sure that I should/should not be using servlets. My Application is created with Spring Boot, Java, and Thymeleaf. What am I doing wrong? I am open to other options, I am trying to understand and learn how to solve this problem.

Mahozad
  • 18,032
  • 13
  • 118
  • 133
JayC
  • 2,144
  • 8
  • 42
  • 77

1 Answers1

4

There's nothing inherently wrong with using servlets directly but both Spring MVC and Boot offer many tools to make your life easier and make your code more concise. I'll provide you with some areas to delve into, but do take a look at more examples on GitHub for further reading. When you're looking through the docs, take a close look at @ModelAttribute, th:object, and @RequestParam.

Let's you have foo.html:

<form th:action="@{/foo}" th:object="${someBean}" method="post">
   <input type="text" id="datePlanted" name="datePlanted" />
   <button type="submit">Add</button>
</form>

The form uses Thymeleaf's th:object notation which we can refer to using Spring's ModelAttribute method parameter.

Then your Controller could have:

@Controller
public class MyController {

    @GetMapping("/foo")
    public String showPage(Model model) {
        model.addAttribute("someBean", new SomeBean()); //assume SomeBean has a property called datePlanted
        return "foo";
    }

    @PostMapping("/foo")
    public String showPage(@ModelAttribute("someBean") SomeBean bean) {

        System.out.println("Date planted: " + bean.getDatePlanted()); //in reality, you'd use a logger instead :)
        return "redirect:someOtherPage";
    }    
}

Note that in the above controller, we didn't need to extend any other class. Just annotate and you're set.

If you're looking to print the value of a URL parameter named myParam in your Java code, Spring let's you do this easily in your controller with @RequestParam. It can even convert it to things like Integer types without any extra work on your side:

    @PostMapping("/foo")
    public String showPage(@ModelAttribute("someBean") SomeBean bean, @RequestParam("myParam") Integer myIntegerParam) {

        System.out.println("My param: " + myIntegerParam);
        return "redirect:someOtherPage";
    }    

I'm also not including the steps to handle dates appropriately since that is out of scope for this question, but you can look at adding something like this to your controller if you come across issues:

@InitBinder
public void initBinder(WebDataBinder binder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
    binder.registerCustomEditor(Date.class, new CustomDateEditor(
            dateFormat, true));
}

Edit: SomeBean is a POJO:

public class SomeBean {

   private LocalDate datePlanted;

   //include getter and setter

}
Community
  • 1
  • 1
riddle_me_this
  • 8,575
  • 10
  • 55
  • 80
  • Thank you for such detailed explanation, I am using Spring Boot currently I have not created or encountered any beans. What can I do to create a bean? To follow your method "someBean". Do I have to create an xml configuration file for that? – JayC Nov 30 '16 at 23:21
  • I followed your logic, and I receive a ambiguous handler error. Is it because I used ModelAndView? – JayC Dec 01 '16 at 15:21
  • Hmm - you'll want to take a look around SO and post a new question as appropriate (but I'd venture that someone has already seen your issue, so please take a good look before posting). – riddle_me_this Dec 01 '16 at 15:22