首页 > 编程语言 > 详细

第87天学习打卡(SpringMVC Controller及RestFul风格 结果跳转方式 数据处理)

时间:2021-04-05 22:16:05      阅读:46      评论:0      收藏:0      [点我收藏+]

3.1配置版

 <?xml version="1.0" encoding="UTF-8"?>
 <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
          version="4.0">
     <!--配置DispatcherServlet:这个是SpringMVC的核心:请求分发器,前端控制器-->
     <servlet>
         <servlet-name>springmvc</servlet-name>
         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
         <!--DispatcherServlet要绑定Spring的配置文件-->
         <init-param>
             <param-name>contextConfigLocation</param-name>
             <param-value>classpath:springmvc-servlet.xml</param-value>
         </init-param>
         <!--启动级别 1 服务器启动它就启动-->
         <load-on-startup>1</load-on-startup>
     </servlet>
     <!--
 在springMVC中,/   /*
 /:只匹配所有的请求,不会去匹配jsp页面
 /*: 匹配所有的请求,包括jsp页面
 -->
     <servlet-mapping>
         <servlet-name>springmvc</servlet-name>
         <url-pattern>/</url-pattern>
     </servlet-mapping>
 ?
 </web-app>

springmvc-servlet.xml

 <?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
         https://www.springframework.org/schema/beans/spring-beans.xsd">
     <!--处理器映射器-->
     <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
     <!--处理器适配器-->
     <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
     <!--视图解析器:模板引擎Thymeleaf Freemarker-->
     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
         <!--前缀-->
         <property name="prefix" value="/WEB-INF/jsp/"/>
         <!--后缀-->
         <property name="suffix" value=".jsp"/>
 ?
     </bean>
       <bean id="/hello" class="com.kuang.controller.HelloController"/>
 ?
 </beans>

 

HelloController:

 package com.kuang.controller;
 ?
 import org.springframework.web.servlet.ModelAndView;
 import org.springframework.web.servlet.mvc.Controller;
 ?
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 ?
 public class HelloController implements Controller {
     @Override
     public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
         ModelAndView mv = new ModelAndView();
 ?
         //业务代码
         String result = "HelloSpringMVC";
         mv.addObject("msg",result);
 ?
         //视图跳转
         mv.setViewName("test");
 ?
         return mv;
    }
 }
 ?

3.2注解版

1.由于Maven可能存在资源过滤的问题,我们将配置完善

 <build>
         <resources>
             <resource>
                 <directory>src/main/java</directory>
                 <includes>
                     <include>**/*.properties</include>
                     <include>**/*.xml</include>
                 </includes>
                 <filtering>false</filtering>
             </resource>
             <resource>
                 <directory>src/main/resources</directory>
                 <includes>
                     <include>**/*.properties</include>
                     <include>**/*.xml</include>
                 </includes>
                 <filtering>false</filtering>
             </resource>
         </resources>
     </build>

2.配置web.xml

注意点:

  • 注意web.xml版本问题,要最新版

  • 注册DispatcherServlet

  • 关联SpringMVC的配置文件

  • 启动级别为1

  • 映射路径为/【不要用/* 会404】

3.添加SpringMVC配置文件

  • 让IOC的注解生效

  • 静态资源过滤:HTML . JS. CSS. 图片, 视频...

  • MVC的注解驱动

  • 配置视图解析器

在resources目录下添加springmvc-servlet.xml 配置文件,配置的形式与spring容器配置基本类似,为了支持基于注解的IOC,设置了自动扫描包的功能,具体配置信息如下:

 <?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
         https://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/context
         https://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/mvc
         https://www.springframework.org/schema/mvc/spring-mvc.xsd">
     
     <!--自动扫描包,让指定包下的注解生效,由IOC容器统一管理-->
 ?
     <context:component-scan base-package="com.kuang.controller"/>
 <!--让Spring MVC不处理静态资源-->
     <mvc:default-servlet-handler/>
 <!--
 支持mvc注解驱动
    在spring中一般采用@RequestMapping注解来完成映射关系
    要想使@RequestMapping注解生效
    必须向上下文中注册DefaultAnnotationHandlerMapping
    和AnnotationMethodHandlerAdapter实例
    这两个实例分别在类级别和方法级别处理
    而annotation-driven配置帮助我们自动完成上述两个实例的注入
 ?
 -->
     <mvc:annotation-driven/>
 <!--视图解析器-->
     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
         <!--前缀-->
         <property name="prefix" value="/WEB-INF/jsp/"/>
                 <!--后缀-->
         <property name="suffix" value=".jsp"/>
     </bean>
 ?
 ?
 </beans>

4.创建Controller

编写一个Java控制类:com.kuang.controller.HelloController,注意编码规范

 package com.kuang.controller;
 ?
 import org.springframework.stereotype.Controller;
 import org.springframework.ui.Model;
 import org.springframework.web.bind.annotation.RequestMapping;
 ?
 @Controller
 public class HelloController {
     @RequestMapping("/hello")
     public String hello(Model model){
         //封装数据
         model.addAttribute("msg","Hello, SpringMVCAnnotation!");
 ?
         return "hello";// 会被视图解析器处理
 ?
    }
 }
 ?

 

小结

实现步骤其实非常简单

1新建一个web项目

2.导入相关jar包

3.编写springmvc配置文件

4.接下来就是去创建对应的控制类,controller

6.最后完善前端视图和controller之间的对应

7.测试运行调试

使用springMVC必须配置的三大件

处理器映射器 处理器适配器 视图解析器

通常,我们只需要手动配置视图解析器,而处理器映射器 和处理器适配器只需要开启注解驱动即可,而省去了大段的xml配置。

4 SpringMVC: Controller 及RestFul风格

4.1 控制器Controller

  • 控制器 负责提供访问应用程序的行为,通常通过接口定义或注解定义两种方法实现。

  • 控制器负责解析用户的请求并将其转换为一个模型

  • 在Spring MVC中一个控制器类可以包含多个方法

  • 在Spring MVC中,对于Controller的配置方式有很多种

4.2 实现Controller接口

第一种实现方式

Controller是一个接口,在org.springframework.web.servlet.mvc包下,接口中只有一个方法:

1.编写一个Controller类,ControllerTest1

 package com.kuang.controller;
 ?
 import org.springframework.web.servlet.ModelAndView;
 import org.springframework.web.servlet.mvc.Controller;
 ?
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 ?
 //只要实现了Controller 接口的类,说明这就是一个控制器了
 ?
 public class ControllerTest1 implements Controller {
     @Override
     public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
         ModelAndView mv = new ModelAndView();
         mv.addObject("msg","ControllerTest1");
         mv.setViewName("test");
         return mv;
    }
 }
 ?

 

springmvc-servlet.xml

 <?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
         https://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/context
         https://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/mvc
         https://www.springframework.org/schema/mvc/spring-mvc.xsd">
 ?
 <!--   <context:component-scan base-package="com.kuang.controller"/>-->
 ?
 <!--   <mvc:default-servlet-handler/>-->
 ?
 <!--   <mvc:annotation-driven/>-->
 ?
     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
         <property name="prefix" value="/WEB-INF/jsp/"/>
         <property name="suffix" value=".jsp"/>
     </bean>
     <bean name="/t1" class="com.kuang.controller.ControllerTest1"/>
 </beans>

 

web.xml

 <?xml version="1.0" encoding="UTF-8"?>
 <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
          version="4.0">
     <servlet>
         <servlet-name>springmvc</servlet-name>
         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 ?
         <init-param>
             <param-name>contextConfigLocation</param-name>
             <param-value>classpath:springmvc-servlet.xml</param-value>
         </init-param>
         <load-on-startup>1</load-on-startup>
     </servlet>
     <servlet-mapping>
         <servlet-name>springmvc</servlet-name>
         <url-pattern>/</url-pattern>
     </servlet-mapping>
 ?
 </web-app>

说明:

  • 实现接口Controller定义控制器是较老发办法

  • 缺点是:一个控制器中只有一个方法,如果要多个方法则需要定义多个Controller;定义的方式比较麻烦

4.3 使用注解@Controller

 

 @Component  组件
 @Sevice   service
 @Controller controller
 @Repository   dao

springmvc-servlet.xml

 <?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
         https://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/context
         https://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/mvc
         https://www.springframework.org/schema/mvc/spring-mvc.xsd">
 ?
   <context:component-scan base-package="com.kuang.controller"/>
 ?
 <!--   <mvc:default-servlet-handler/>-->
 ?
 <!--   <mvc:annotation-driven/>-->
 ?
     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
         <property name="prefix" value="/WEB-INF/jsp/"/>
         <property name="suffix" value=".jsp"/>
     </bean>
 </beans>

 

ControllerTest2

 package com.kuang.controller;
 ?
 import org.springframework.stereotype.Controller;
 import org.springframework.ui.Model;
 import org.springframework.web.bind.annotation.RequestMapping;
 ?
 @Controller //这个类会被Spring接管 ,被这个注解的类中的所有方法,如果返回值是String 并且有具体页面可以跳转,那么就会被这个视图解析器解析
 public class ControllerTest2 {
     @RequestMapping("/t2")
     public String test1(Model model){
         model.addAttribute("msg"," ControllerTest2");
         return "test";
    }
 }
 ?

 

可以发现,我们的两个请求都可以指向一个视图,但是页面结果是不一样的,从这里可以看出视图是被复用 的,而控制器与视图之间是弱耦合关系

4.4RequestMapping

@RequestMapping

  • @RequestMapping 注解用于映射url到控制器或一个特定的处理程序方法。可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径

  • 为了测试结论更加准确,我们可以加上一个项目测试myweb

 package com.kuang.controller;
 ?
 import org.springframework.stereotype.Controller;
 import org.springframework.ui.Model;
 import org.springframework.web.bind.annotation.RequestMapping;
 ?
 @Controller
 @RequestMapping("/c3")
 public class ControllerTest3 {
     @RequestMapping("/t1")
 ?
     public String test1(Model model){
         model.addAttribute("msg","ControllerTest3");
 ?
         return "admin/test";
    }
 }
 ?

 

访问路径:http://localhost:8080/c3/t1。需要先指定类的路径再指定方法的路径。

4.5 RestFul风格

概念:Restful就是一个资源定位及资源操作的风格。不是标准也不是协议,只是一种风格。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存机制。它是以斜线访问资源的比如:localhost:8080/method

功能

  • 资源:互联网所有的事物都可以被抽象为资源

  • 资源操作:使用POST DELETE PUT GET

  • 分别对应 添加、删除 修改 查询

技术分享图片

传统方式操作资源:通过不同的参数来实现不同的效果!方法单一,post和get

传统的:

 package com.kuang.controller;
 ?
 import org.springframework.stereotype.Controller;
 import org.springframework.ui.Model;
 import org.springframework.web.bind.annotation.RequestMapping;
 ?
 @Controller
 public class RestFulController {
 @RequestMapping("/add")   //Model用来传数据
     public String test1(int a, int b, Model model){
         int res = a + b ;
         model.addAttribute("msg","结果为" + res);
         return "test";
    }
 }
 ?

 

http://localhost:8080/add?a=1&b=2

使用RESTful操作资源:可以通过不同的请求方法来实现不同的效果!

技术分享图片

 

 package com.kuang.controller;
 ?
 import org.springframework.stereotype.Controller;
 import org.springframework.ui.Model;
 import org.springframework.web.bind.annotation.*;
 ?
 @Controller
 public class RestFulController {
     //原来的:http://localhost:8080/add?a=1&b=2
     //RestFul:http://localhost:8080/add/a/b       http://localhost:8080/add/1/2 这样写可以去识别 a b 然后对应值
 //@RequestMapping("/add/{a}/{b}")
 ?
     @PostMapping("/add/{a}/{b}")
     public String test1(@PathVariable int a, @PathVariable String b, Model model){ //Model用来传数据
         String res = a + b ;
         model.addAttribute("msg","结果1为" + res);
         return "test";
    }
     @GetMapping ("/add/{a}/{b}")
     public String test2(@PathVariable int a, @PathVariable String b, Model model){ //Model用来传数据
         String res = a + b ;
         model.addAttribute("msg","结果2为" + res);
         return "test";
    }
 }
 ?

@PostMapping 和 @GetMapping请求的地址是一样的 只是一个是post实现 一个是get实现

在Spring MVC中可以使用@PathVariable 注解,让方法参数的值对应绑定到一个URL模板变量上。

 package com.kuang.controller;
 ?
 import org.springframework.stereotype.Controller;
 import org.springframework.ui.Model;
 import org.springframework.web.bind.annotation.PathVariable;
 import org.springframework.web.bind.annotation.RequestMapping;
 ?
 @Controller
 public class RestFulController {
     //原来的:http://localhost:8080/add?a=1&b=2
     //RestFul:http://localhost:8080/add/a/b       http://localhost:8080/add/1/2 这样写可以去识别 a b 然后对应值
 @RequestMapping("/add/{a}/{b}")   //Model用来传数据
     public String test1(@PathVariable int a, @PathVariable int b, Model model){
         int res = a + b ;
         model.addAttribute("msg","结果为" + res);
         return "test";
    }
 }
 ?

 

 package com.kuang.controller;
 ?
 import org.springframework.stereotype.Controller;
 import org.springframework.ui.Model;
 import org.springframework.web.bind.annotation.*;
 ?
 @Controller
 public class RestFulController {
 ?
    @RequestMapping(value="/add/{a}/{b}", method = RequestMethod.GET)
     public String test1(@PathVariable int a, @PathVariable String b, Model model){ //Model用来传数据
         String res = a + b ;
         model.addAttribute("msg","结果1为" + res);
         return "test";
    }
   
 }
 ?

 

使用method属性指定请求类型

用于约束请求的类型,可以收窄请求范围。指定请求谓词的类型如GET POST ,OPTIONS ,PUT ,PATCH ,DELETE ,TRACE等

 

RestFul风格的好处:

  • 使路径变得更加简洁

  • 获得参数更加方便,框架会自动进行类型转换

  • 通过路径变量的类型可以约束访问参数,如果类型不一样,则访问不到对应的请求方法。

5 结果跳转方式

ModelAndView

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

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

ServletAPI

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

1.通过HttpServletResponse进行输出

2..通过HttpServletResponse实现重定向

3..通过HttpServletRequest实现转发

测试:

 package com.kuang.controller;
 ?
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.RequestMapping;
 ?
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;
 ?
 @Controller
 public class ModelTest1 {
 @RequestMapping("/m1/t1")
     public String test1(HttpServletRequest request, HttpServletResponse response){
     HttpSession session = request.getSession();
     System.out.println(session.getId());
     return "test";
    }
 }
 ?

SpringMVC

通过SpringMVC来实现转发和重定向-无需视图解析器

测试前需要将视图解析器注释掉

没有视图解析器的情况下

 package com.kuang.controller;
 ?
 import org.springframework.stereotype.Controller;
 import org.springframework.ui.Model;
 import org.springframework.web.bind.annotation.RequestMapping;
 ?
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.HttpSession;
 ?
 @Controller
 public class ModelTest1 {
 @RequestMapping("/m1/t1")
     public String test1(Model model){
 ?
     //转发
     model.addAttribute("msg","ModelTest1");
     //return "forward:/WEB-INF/jsp/test.jsp";
 //重定向
     return "redirect:/index.jsp";
    }
 }
 ?

 

通过SpringMVC来实现转发和重定向- 有视图解析器

重定向,不需要视图解析器,本质就是重新请求一个新地方,所以注意路径问题。

可以重定向到另外一个请求实现。举例

 @Controller
 public class ResultSpringMVC2{
     @RequestMapping("/rsm2/t1")
     public String test1(){
         //转发
         return "test";
    }
     @RequestMapping("/rsm2/t2")
     public String test2(){
         //重定向
         return "redirect:/index.jsp";
         
    }
 }

6 SpringMVC:数据处理

处理提交数据

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

提交数据:https://localhost:8080/hello?name=doudou

处理方法:

 @RequestMapping("/hello")
 public String hello(String name){
     System.out.println(name);
     return
     
 }
 ?

后台输出doudou

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

提交数据:http://localhost:/8080/hello?username=doudou

处理方法

 //@RequestParam("username"):username 提交的域的名称
  @RequestMapping("/hello")
 public String hello(@RequestParam("username")String name){
     System.out.println(name);
     return "hello";
 }

后台输出:doudou

3.提交的是一个对象

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

说明:如果使用对象的话,前端传递的参数名和对象名必须一致,否则就是null.

数据显示到前端

第一种:通过ModelAndView

第二种:通过ModelMap

第三种:通过Model

 

 LinkedHashMap
 ModelMap:继承了LinkedHashMap,所以他拥有LinkedHashMap的全部功能!
 Model:精简版(大部分情况下,我们都直接使用Model)
 Model:只有寥寥几个方法社和用于储存数据,简化了新手对于Model对象的操作和理解
 ModelMap:继承了LinkedMap,除了实现了自身的一些方法,同样继承了LinkedMap的方法和特性。
 ModelAndView:可以在储存数据的同时,可以进行设置返回的逻辑视图,进行控制展示层的跳转
 package com.kuang.controller;
 ?
 import com.kuang.pojo.User;
 import org.springframework.stereotype.Controller;
 import org.springframework.ui.Model;
 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestParam;
 ?
 @Controller
 @RequestMapping("/user")
 public class UserController {
 ?
     //localhost: 8080/user/t1 ? name=xxx;
     @GetMapping("/t1")
     public String test1(@RequestParam("username") String name, Model model){
     //1.接收前端参数
     System.out.println("接收到前端的参数为:"+name);
 ?
     //2.将返回的结果传递给前端
     model.addAttribute("msg",name);
 ?
     //3.视图跳转
 ?
         return "test";
    }
     /*
     1.接收端用户传递参数,判断参数的名字,假设名字直接在方法上,可以直接使用
     2.假设传递的是一个对象User,匹配User对象中的字段名:如果名字不一致则OK,否则,匹配不到
 ?
 ?
     */
     //前端接收的是一个对象: id name age
     @GetMapping("/t2")
     public String test2(User user){
         System.out.println(user);
         return "test";
 ?
    }
 ?
 }
 ?

User:

 package com.kuang.pojo;
 ?
 import lombok.AllArgsConstructor;
 import lombok.Data;
 import lombok.NoArgsConstructor;
 ?
 @Data
 @AllArgsConstructor
 @NoArgsConstructor
 public class User {
 ?
     private int id;
     private String name;
     private int age;
 ?
 ?
 }
 ?

 

springmvc-servlet.xml:不要忘记把视图解析开启

 <?xml version="1.0" encoding="UTF-8"?>
 <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
         https://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/context
         https://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/mvc
         https://www.springframework.org/schema/mvc/spring-mvc.xsd">
 ?
   <context:component-scan base-package="com.kuang.controller"/>
 ?
 <!--   <mvc:default-servlet-handler/>-->
 ?
 <!--   <mvc:annotation-driven/>-->
 ?
     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
         <property name="prefix" value="/WEB-INF/jsp/"/>
         <property name="suffix" value=".jsp"/>
     </bean>
 ?
 ?
 </beans>

 

第87天学习打卡(SpringMVC Controller及RestFul风格 结果跳转方式 数据处理)

原文:https://www.cnblogs.com/doudoutj/p/14619318.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!