2016-11-30 60 views
0

我想从thymeleaf输入一个值,我的Java类。如何从春天启动百里香叶获得的输入值,以java类?

从thymeleaf

简单的脚本,我怎么会能够检索datPlanted到我的java类?

尝试下列servlet教程

@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);   
} 
} 

我试图按照教程,但我不知道我应该/不使用servlet来。我的应用程序是用Springboot,Java和Thymeleaf创建的。我究竟做错了什么?我愿意接受其他选择,我正试图理解并学习如何解决这个问题。

回答

1

没有什么内在的错误,直接使用servlet但两者Spring MVC和引导提供了很多工具,使您的生活更轻松,让你的代码更简洁。我会为您提供一些需要深入研究的领域,但请参阅GitHub上的更多示例以供进一步阅读。当你翻翻文档,请仔细看@ModelAttributeth:object@RequestParam

假设您的foo.html:

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

窗体使用Thymeleaf的th:object符号,我们可以参考使用Spring的ModelAttribute方法的参数。

那么你的控制器可以有:

@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"; 
    }  
} 

注意,在上面的控制器,我们没有必要扩展任何其他类。只需注释并设置即可。

如果你正在寻找打印在Java代码名为myParam的URL参数的值,春天让你在与你@RequestParam控制器做到这一点很容易的。它甚至可以将其转换之类的东西Integer类型无需任何额外的工作就在你身边:

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

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

我还没有包括的步骤处理日期正确,因为这是超出范围对于这个问题我,但你可以看看添加像这样到控制器,如果你遇到的问题:

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

编辑:SomeBean是一个POJO:

public class SomeBean { 

    private LocalDate datePlanted; 

    //include getter and setter 

} 
+0

谢谢你,这么德泰引导的解释,我使用Spring Boot目前我还没有创建或遇到任何bean。我能做些什么来创建一个bean?遵循你的方法“someBean”。我必须为此创建一个xml配置文件吗? – Jesse

+0

不,谷歌术语POJO(普通Java对象) – bphilipnyc

+0

我跟着你的逻辑,我收到一条暧昧的处理程序错误。是因为我使用了ModelAndView吗? – Jesse