java如何向spring控制器的http请求添加属性?
我想测试下面的spring控制器,它读取http request attributes
并对其进行操作。我可以通过在我的web浏览器中键入localhost:8080/someURL
来触发下面的控制器代码。但是结果是{"id":1,"content":"null and null and null"}
,它表示命名的request attributes
中的null
值如何向包含指定request attributes
值的命名url(如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)的链接或用于重新创建请求的其他方法
# 1 楼答案
CheckoutSpring MVC Test framework-代替手动触发一些URL,而是编写单元测试
关于你的笔记
是的,这就是参数。在php中,您有$\u GET和$\u POST,或者(如果您不关心方法的话)只需$\u请求即可访问请求参数。将getAttribute()重新编码为getParameter(),或使用@RequestParam注释将其放入方法签名中
现在你可以试试http://localhost:8080/yourapp/receiveSMS?from=me&to=you&body=stackoverflow
旁注:
如果希望从客户端发送该信息,则应使用
getParameter()
调用# 2 楼答案
测试如下内容:
http://localhost:8080/someURL?att1=value1&att2=value2&att3=value3
它将显示传递到URL中的值1、值2和值3
# 3 楼答案
请求属性仅为服务器端构造。尝试改用请求参数:
然后发送以下表单的请求:
您应该能够读取您试图传递的值