【发布时间】:2016-04-01 20:03:18
【问题描述】:
我想测试下面的弹簧控制器,它读取http request attributes 并作用于它们。我可以通过在我的网络浏览器中输入localhost:8080/someURL 来触发下面的控制器代码。但结果是{"id":1,"content":"null and null and null"},表示null 命名为request attributes 中的值。 如何向包含指定request attributes 的值的localhost:8080/someURL 等命名网址发送请求,以便确认接收控制器代码正常工作?
这是控制器的代码:
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPa ram;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
@Controller
public class SomeController {
private final AtomicLong counter = new AtomicLong();
@RequestMapping(value = "/someURL", method=RequestMethod.GET)
public @ResponseBody Greeting receiveSMS(HttpServletRequest req){
String att1 = (String) req.getAttribute("att1");
String att2 = (String) req.getAttribute("att2");
String att3 = (String) req.getAttribute("att3");
String total = att1 + " and " + att2 + " and " + att3;
return new Greeting(counter.incrementAndGet(), String.format(total));
}
}
注意:我正在尝试在 Spring the PHP functionality that is given in the script at the following link 中重新创建。我没有在下面写过这种代码,如果我对问题的构想不佳,我将不胜感激重新构想的建议。以及指向任何示例解决方案的链接,例如 JUNIT 或用于重新创建请求的其他方法。
【问题讨论】:
-
来自浏览器的请求永远不会包含任何属性。它可以拥有属性的唯一方法是,如果某些其他资源将这些属性放在请求中,然后转发(或包含)到此控制器。或者如果服务器上的某些过滤器或拦截器之前放置了它们。
-
所以,要么之前有这样的资源,你应该测试那个资源或者写一个单元测试,或者有这样的资源,请求应该直接来自浏览器,并且那么代码就不正确了。
-
@JBNizet 这是一个将从第三方放入 Web 服务的 URL。我不会使用
total字符串回复,而是将三个request attributes传递给算法。为了测试目的,将它们作为响应发送更容易。如果您说SYSOtotal字符串更好,我可以这样做,但我仍然需要向包含命名attributes的 url 发送请求。我该怎么做? -
你不能从外部传递属性。时期。任何客户端都无法将属性传递给您的控制器。您需要将它们设为参数、标头或路径变量,即可以使用 HTTP 发送的内容。
-
@JBNizet 感谢您指导这个答案。
标签: java spring http spring-mvc servlets