SpringMVC【三】Controller/RequestMapping/结果跳转方式/数据处理

时间:2020-06-28 00:36:55   收藏:0   阅读:228

4、控制器 Controller

控制器:

注意:

4.1 实现 Controller 接口

Controller 是一个接口(函数式接口),在 org.springframework.web.servlet.mvc 包下,实现该接口的类获得控制器功能,接口中只有一个方法,源码如下:

@FunctionalInterface
public interface Controller {
	//处理请求且返回一个模型与视图对象
   @Nullable
   ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception;
}

测试:

  1. SpringMVC 的配置文件中只有视图解析器

    不用配置处理器和适配器就可以使用,因为 Spring 自动帮我们配置了

  2. 编写一个 controller 类

    // 只要实现了 Controller 接口的类,说明这就是一个控制器了
    public class ControllerDemoTest1 implements Controller {
        public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
            ModelAndView mv = new ModelAndView();
            
            mv.addObject("msg","hello, ControllerDemoTest1");
            mv.setViewName("test");
            
            return mv;
        }
    }
    
  3. 在 SpringMVC 配置文件中注册请求的 bean,name 对应请求路径,class 对应处理请求的类

    <bean name="/t1" class="com.song.controller.ControllerDemoTest1"/>
    
  4. WEB-INF/jsp 目录下编写前端 test.jsp,对应视图解析器

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
    	${msg}
    </body>
    </html>
    
  5. 配置 Tomcat 运行测试,在浏览器地址栏输入 http://localhost:8080/t1

  6. 测试结果:页面上会显示 hello, ControllerDemoTest1

4.2 使用注解 @Controller【平时使用的最多的方式】

@Controller 注解类型用于声明 Spring 类的实例是一个控制器(IOC 中还有 3 个相同功能的注解):

测试:

  1. SpringMVC 的配置文件中除了配置视图解析器,还要配置自动扫描包

    因为 Spring 可以使用扫描机制来找到应用程序中所有基于注解的控制器类,为了保证 Spring 能找到我们的控制器,需要在配置文件中声明组件扫描。

    <context:component-scan base-package="com.song.controller"/>
    
  2. 编写一个 controller 类,使用注解实现;

    // 被这个注解的类中的所有方法,如果返回值是String,并且有具体的页面可以跳转,那么就会被视图解析器解析
    @Controller // 代表这个类会被 Spring接管,
    public class ControllerTest2 {
    
        @RequestMapping("/t2")   //映射访问路径
        public String test(Model model){
    		//Spring MVC会自动实例化一个Model对象用于向视图中传值
            model.addAttribute("msg", "Hello, ControllerTest2");
    		//返回视图位置
            return "test"; //  WEB-INF/jsp/test.jsp
        }
    }
    
  3. 配置 Tomcat 运行测试,在浏览器地址栏输入 http://localhost:8080/t2

  4. 测试结果:页面上会显示 hello, ControllerDemoTest2

注意:这两种实现控制器的方式,两个请求都可以指向一个视图,但是页面的结果是不一样的,从这里可以看出视图是被复用的,即控制器与视图之间是弱耦合关系。

5、RequestMapping

@RequestMapping 注解用于映射 url 到控制器类或一个特定的处理程序方法。

可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。

@Controller
public class ControllerTest3 {

    @RequestMapping("t1")
    public String test1(Model model){
        model.addAttribute("msg", "test3");
        return "test";
    }
}
@Controller
//@RequestMapping("/c3")
public class ControllerTest3 {

    //@RequestMapping("/t1")
    public String test1(Model model){
        model.addAttribute("msg", "test3");
        return "test";
    }
}

注意:一般直接在方法上写 //@RequestMapping("/c3/t1"),和同时在类和方法上注解作用一样。

6、结果跳转方式

6.1 ModelAndView

设置 ModelAndView 对象 , 根据 view 的名称和视图解析器跳到指定的页面

页面 : 视图解析器前缀 + viewName + 视图解析器后缀

public class ControllerDemoTest1 implements Controller {
   
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView mv = new ModelAndView();
        
        mv.addObject("msg","hello, ControllerDemoTest1");
        mv.setViewName("test");
        //返回一个模型视图对象
        return mv;
    }
}

6.2 ServletAPI

通过设置 ServletAPI , 不需要视图解析器

  1. 通过 HttpServletResponse 进行输出

  2. 通过 HttpServletResponse 实现重定向

  3. 通过 HttpServletRequest 实现转发

@Controller
public class ModelTest {

    @RequestMapping("/m/t1")
    public String test1(HttpServletResponse response, HttpServletRequest request){
        HttpSession session = request.getSession();
        System.out.println(session.getId());
        return "test";
    }
    
    @RequestMapping("/m/t2")
   	public void test2(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
       	rsp.getWriter().println("Hello,Spring By servlet API");
  }

   	@RequestMapping("/m/t3")
   	public void test3(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
       	rsp.sendRedirect("/index.jsp");
  }

   	@RequestMapping("/m/t4")
   	public void test4(HttpServletRequest req, HttpServletResponse rsp) throws Exception {
      	 //转发
       	req.setAttribute("msg","/m/t4");
       	req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,rsp);
  }
}

6.3 SpringMVC

通过 SpringMVC 来实现转发和重定向有两种方式:需要视图解析器和没有视图解析器

public class ModelTest1 {
	// 没有视图解析器
    @RequestMapping("m1/t2")
    public String test2(Model model){
        model.addAttribute("msg","model test2");
        // 转发
//        return "/WEB-INF/jsp/test.jsp";
//        return "forward:/WEB-INF/jsp/test.jsp";
        // 重定向
        return "redirect:/index.jsp";
	}
    
    // 有视图解析器,默认转发,重定向的话要加上 redirect:/
    @RequestMapping("m1/t3")
    public String test3(Model model){
        model.addAttribute("msg","model test3");
        // 转发
//        return "test";
        // 重定向
        return "redirect:/index.jsp";
    }

7、数据处理

7.1 处理提交数据

  1. 提交的域名称和处理方法的参数名一致

    • Controller 类:

      提交的域名称为 name,方法参数名为 name,可以直接识别

    @Controller
    @RequestMapping("/user")
    public class UserController {
    
        // localhost:8080/user/t1?name=xxx
        @GetMapping("/t1")
        public String test1(String name, Model model){
            //1.接收前端参数
            System.out.println("接收到前端的参数为" + name);
            //2.将返回的结果传递给前端 Model
            model.addAttribute("msg", name);
    
            return "test";
        }
    }
    
    • 结果:
    提交数据: localhost:8080/user/t1?name=xxx
    控制台输出:xxx
    前端 test.jsp 页面显示:xxx
    
  2. 提交的域名称和处理方法的参数名不一致

    • Controller 类:

      提交的域名称为 username,方法参数名为 name,要用 @RequestParam(" ") 注解将来自前端的参数命名为和前端提交的域名称一致。【建议来自前端的参数都加上这个注解 @RequestParam】

    // localhost:8080/user/t1?username=xxx
    // @RequestParam 建议来自前端的参数都加上这个
    @GetMapping("/t1")
    public String test1(@RequestParam("username") String name, Model model){
        //1.接收前端参数
        System.out.println("接收到前端的参数为" + name);
        //2.将返回的结果传递给前端 Model
        model.addAttribute("msg", name);
    
        return "test";
    }
    
    • 结果:
    提交数据: localhost:8080/user/t1?username=xxx
    控制台输出:xxx
    前端 test.jsp 页面显示:xxx
    
  3. 提交的是一个对象

    要求提交的表单域和对象的属性名一致 , 方法中的参数使用对象即可。

    注意:如果使用对象,前端传递的参数名和对象中的属性名必须一致,否则就是null。

    • 实体类 User
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class User {
        private int id;
        private String name;
        private int age;
    }
    
    • Controller 类:
    // 前端接收的是一个对象 id name age
    /*
        1.接收前端用户传递的参数,判断参数的名字,假设名字直接在方法上,可以直接使用
        2.假设传递的是一个对象,匹配对象的字段名,如果名字一致则 OK,否则,匹配不到
     */
    @GetMapping("/t2")
    public String test2(User user){
        System.out.println(user);
        return "test";
    }
    
    • 结果
    提交数据: localhost:8080/user/t1?name=zhangsan&id=1&age=3
    控制台输出:User(id=1, name=zhangsan, age=3)
    

7.2 数据显示到前端

  1. 通过 ModelAndView(实现 Controller 接口)

    public class ControllerDemoTest1 implements Controller {
        
        public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
            ModelAndView mv = new ModelAndView();
            mv.addObject("msg","hello, ControllerDemoTest1");
            mv.setViewName("test");
    
            return mv;
        }
    }
    
  2. 通过 ModelMap

    @Controller
    @RequestMapping("/user")
    public class UserController {
        
        @GetMapping("/t3")
        public String test3(ModelMap map){
            map.addAttribute("msg","ModelMap");
    
            return "test";
        }
    }
    
  3. 通过 Model

    @Controller
    @RequestMapping("/user")
    public class UserController {
        
        @GetMapping("/t1")
        public String test1(@RequestParam("username") String name, Model model){
            model.addAttribute("msg", name);
    
            return "test";
        }
    }
    

三种方式的对比:

7.3 乱码问题

将后台的中文数据显示页面时会出现乱码问题,乱码问题都是通过过滤器解决。

注意:get 方式不会乱码,post 方式会乱码。

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!