2017-08-29 45 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"; 
    } 
} 
相关问题