2017-08-29 29 views
1

任何人都可以幫助我。我無法理解,爲什麼@RequestParameter或用request.getParameter()不工作(( 我的控制器:無法獲得請求參數從視圖到控制器Spring MVC

@Controller 
public class CheatController extends WebMvcConfigurerAdapter { 

@RequestMapping(value = "/hello", method = RequestMethod.GET) 
public String hello(@RequestParam("gg") String gg, Model model) { 
    return "hello"; 
} 
} 

而我的觀點:

<html> 
<body> 
<form action="#" th:action="@{/hello}" method="get"> 
<input type="text" id="gg" name="gg" placeholder="Your data"/> 
<input type="submit" /> 
</form> 
<span th:if="${gg != null}" th:text="${gg}">Static summary</span> 
</body> 
</html> 

回答

0

我無法理解它在獲取和發送PARAMS怎樣的影響,但它幫助我(我評論代碼和平,並開始工作)。任何人都可以解釋爲什麼發生?

@Configuration 
public class DefaultView extends WebMvcConfigurerAdapter { 

    @Override 
    public void addViewControllers(ViewControllerRegistry registry) { 
     //registry.addViewController("/hello").setViewName("hello"); 
     registry.addViewController("/all").setViewName("all"); 

     registry.setOrder(Ordered.HIGHEST_PRECEDENCE); 
     super.addViewControllers(registry); 
    } 
} 
0

好像你在@RequestParam

錯誤

嘗試通過更換這行public String hello(@RequestParam("gg") String gg, Model model)

public String hello(@RequestParam(required = false, defaultValue = "") String gg, Model model) 

我們在上面的行中設置的是,gg不是必需的,如果您的參數gg爲空或爲空,則defaultValue將爲「」。你可以刪除這個選項,但是測試Controller是否正常工作是一個好方法,並且如果你知道你會一直收到一個gg參數,你可以刪除它。

0

should be using POST instead of GET on your form

<form action="#" th:action="@{/hello}" method="get">

您也可以簡化控制器代碼:

@Controller 
public class CheatController { 

    @GetMapping("/hello") 
    public String hello(@RequestParam("gg") String gg, 
         Model model) { 
     ... 
     return "hello"; 
    } 
} 
相關問題