有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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)的链接或用于重新创建请求的其他方法


共 (3) 个答案

  1. # 1 楼答案

    CheckoutSpring MVC Test framework-代替手动触发一些URL,而是编写单元测试

    关于你的笔记

    是的,这就是参数。在php中,您有$\u GET和$\u POST,或者(如果您不关心方法的话)只需$\u请求即可访问请求参数。将getAttribute()重新编码为getParameter(),或使用@RequestParam注释将其放入方法签名中

    @RequestMapping(value = "/receiveSMS", method=RequestMethod.GET)
    public @ResponseBody Greeting receiveSMS(@RequestParam("from") String from,
           @RequestParam("to") String to, @RequestParam("body") String body){
    
    }
    

    现在你可以试试http://localhost:8080/yourapp/receiveSMS?from=me&to=you&body=stackoverflow

    旁注:

    如果希望从客户端发送该信息,则应使用getParameter()调用

  2. # 3 楼答案

    请求属性仅为服务器端构造。尝试改用请求参数

    @RequestMapping(value = "/someURL", method = RequestMethod.GET)
    public @ResponseBody Greeting receiveSMS(@RequestParam("att1") String att1, @RequestParam("att2") String att2, @RequestParam("att3") String att3){
        String total = String.format("%s and %s and %s", att1, att2, att3);
        return new Greeting(counter.incrementAndGet(), total);
    }
    

    然后发送以下表单的请求:

    http://localhost:8080/someURL?att1=value1&att2=value2&att3=value3
    

    您应该能够读取您试图传递的值