【问题标题】:spring requestmapping testing code doesn't worksspring requestmapping测试代码不起作用
【发布时间】:2020-10-10 04:15:30
【问题描述】:

我正在学习spring 5,我不能使用@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;
}

}

【问题讨论】:

  • 什么是AbstractDispatcherServletTest?你为什么不使用MockMvc?你在使用什么Controller 类,因为它不是 Spring MVC 的控制器?从基本的 Spring MVC 教程开始,因为它将引导您了解需要学习的基础知识。
  • AbstractDispatcherServletTest 类包含模拟对象 MockHttpServletRequest 、 MockHttpServletResponse 、 MockServletConfig 、MockHttpSession 和 dispatcherservlet
  • 这是我的错误代码 org.springframework.web.servlet.DispatcherServlet noHandlerFound WARNING: No mapping found for HTTP request with URI [/hello] in DispatcherServlet with name 'spring'

标签: java spring spring-test request-mapping


【解决方案1】:

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

Spring Framework Annotations

Spring Annotations - JournalDev

【讨论】:

  • 我已经读过了,但是控制器注释在我将示例代码放在示例中之前不起作用
猜你喜欢
  • 2012-05-02
  • 1970-01-01
  • 2016-10-27
  • 1970-01-01
  • 2019-07-28
  • 1970-01-01
  • 2017-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多