2016-11-30 58 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