简体   繁体   English

在 Spring 中使用 @QueryParam

[英]Using @QueryParam in Spring

I'm looking for a simple example of using @QueryParam in Spring.我正在寻找在 Spring 中使用 @QueryParam 的简单示例。 My thought is to have an link as that looks like this that will get the id value, run my java class and present the String that is returned.我的想法是有一个看起来像这样的链接,它将获取 id 值,运行我的 java class 并显示返回的字符串。 My problem is that the returning value is not found.我的问题是找不到返回值。

http://localhost:8080/recipesinfo?id=274596 http://localhost:8080/recipesinfo?id=274596

There was an unexpected error (type=Internal Server Error, status=500).出现意外错误(类型=内部服务器错误,状态=500)。 Exception evaluating SpringEL expression: "recipesinfo.step" (template: "recipesinfo_result" - line 12, col 22)评估 SpringEL 表达式的异常:“recipesinfo.step”(模板:“recipesinfo_result” - 第 12 行,第 22 列)

DemoApplication.java DemoApplication.java

RecipesInfo repinfo = new RecipesInfo();
@RequestMapping("/recipesinfo")
public String getInfo (@RequestParam("id") int id) throws IOException {

    repinfo.execute(id);

    return "recipesinfo_result";
 }




public static void main(String[] args) throws Exception {
    SpringApplication.run(DemoApplication.class, args);

}        

recipesinfo_result.html食谱info_result.html

<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Recipes</title>
</head>
<body>
<p class="title"><a  th:text="${recipesinfo.step}"></a><br></body>
</html>

RecipesInfo.java RecipesInfo.java

public String execute(int id) throws IOException { 

//using id in a Http request here and returning String step (the problem isn't here)

      return step;
      }

I have done something similar to this in a Web Service which is working but that one is just returning JSON.我在 Web 服务中做了类似的事情,该服务正在运行,但只是返回 JSON。

You need to bind your query parameters to model for pass it to your view page.您需要将查询参数绑定到 model 以将其传递到您的视图页面。

@RequestMapping("/recipesinfo")
public String getInfo (@RequestParam("id") int id, Model theModel)) throws IOException {
    theModel.addAttribute("recipesinfo",id);

    return "recipesinfo_result";
 }

recipesinfo_result.html食谱info_result.html

<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Recipes</title>
</head>
<body>
<p class="title"><a  th:text="${recipesinfo}"></a><br></body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM