在类上与方法上添加相应注解即可。

    • @Controller:表示当前类为处理器,创建处理器对象。
    • @RequestMapping:表示当前方法为处理器方法。该方法要对 value 属性所指定的 URI进行处理与响应。被注解的方法的方法名可以随意。

    image.png

    1. package com.wzy.controller;
    2. import org.springframework.stereotype.Controller;
    3. import org.springframework.web.bind.annotation.RequestMapping;
    4. import org.springframework.web.servlet.ModelAndView;
    5. @Controller
    6. public class MyController {
    7. /**
    8. * RequestMapping 请求映射,把指定的请求交给方法处理
    9. * 当启动服务器时候,访问的是 / 也就是上下文路径,接收并执行方法
    10. * / 表示 http://localhost:8080/springmvc/
    11. * 返回 http://localhost:8080/springmvc/ + 视图解析器前缀 WEB-INF/templates/ + index + 后缀.html
    12. * @return
    13. */
    14. @RequestMapping(value = "/")
    15. public String index() {
    16. return "index";//返回视图名称
    17. }
    18. @RequestMapping(value = "/target")
    19. public String toTarget() {
    20. return "target";
    21. }
    22. }