有 Java 编程相关的问题?

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

JavaSpringRequestMapping测试代码不起作用

我正在学习Spring5,我不能使用@RequestMapping注释,也不知道为什么

@RequestMapping包含@Component注释,所以我想我可以使用它

initRequest按字符串包含URL参数

我只是希望initRequest(/hello)参数绑定URL

这是我的密码

public class SimpleControllerTest extends AbstractDispatcherServletTest {
@Test
public void helloSimpleController() throws ServletException, IOException {
    setClasses(HelloController.class);
    initRequest("/hello").addParameter("name", "spring");
    runService();
    assertModel("message", "Hello spring");
    assertViewName("/WEB-INF/view/hello.jsp");
}

@Test(expected=Exception.class)
public void noParameterHelloSimpleController() throws ServletException, IOException {
    setClasses(HelloController.class);
    initRequest("/hello");
    runService();
}

@Component("/hello")
//@RequestMapping("/hello")
static class HelloController extends SimpleController {
    public HelloController() {
        this.setRequiredParams(new String[] {"name"});
        this.setViewName("/WEB-INF/view/hello.jsp");
    }

    public void control(Map<String, String> params, Map<String, Object> model) throws Exception {
        model.put("message", "Hello " + params.get("name"));
    }
}

static abstract class SimpleController implements Controller {
    private String[] requiredParams;
    private String viewName;

    public void setRequiredParams(String[] requiredParams) {
        this.requiredParams = requiredParams;
    }

    public void setViewName(String viewName) {
        this.viewName = viewName;
    }

    final public ModelAndView handleRequest(HttpServletRequest req,
                                            HttpServletResponse res) throws Exception {
        ...
    }


    public abstract void control(Map<String, String> params, Map<String, Object> model) throws Exception;
}

}


共 (1) 个答案

  1. # 1 楼答案

    你需要学习你的Spring基础知识。您对注释的理解是不正确和不完整的。以下链接提供了有关这些方面的良好知识。通过这些步骤,修改您的代码,您将在不需要帮助的情况下解决此问题

    Spring Framework Annotations

    Spring Annotations - JournalDev