【发布时间】: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