首页 > 其他分享 >Spring框架3--Web

Spring框架3--Web

时间:2023-02-21 19:45:48浏览次数:30  
标签:web Web -- Spring springframework org DispatcherServlet servlet

Spring框架之Web

Javaweb三大组件和四大域

image-20230217205249783

顺便:Javaweb中的四大域,作用范围如下:PageContext<Request<Session<ServletContext(Application)

域对象 属性的作用范围
PageContext 仅限于当前jsp页面,在servlet中无法获取该对象
Request 仅限于同一个请求,主要用于请求转发,服务器跳转有效,客户端跳转无效
Session 仅限于一次会话,从浏览器打开直到关闭称为一次会话,搭配cookie使用
Application 限于当前Web应用,是范围最大的属性作用范围,只要在一处设置属性,在其他各处的jsp或servlet中都可以获取到,在servlet中对应于ServletContext对象

Spring-Web实现

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");//创建Spring容器
        UserService userService = (UserService) applicationContext.getBean("userService");//获取Bean
        User user = userService.login("zhangsan", "123");
        System.out.println(user);
    }


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}

正常实现的话需要在对应业务的文件中先创建Spring容器,然后再获取对应的Bean对象,业务代码重复。实际上创建容器的过程可以在程序开始执行的时候创建一个单例对象,之后再次使用时只要拿到这个对象直接使用即可,具体实现可以在ServletContext监听器中实现。

  • Spring整合Servlet:

    <!DOCTYPE web-app PUBLIC
     "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
     "http://java.sun.com/dtd/web-app_2_3.dtd" >
    
    <!--web.xml文件-->
    <web-app>
      <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
      </context-param>
        <!--指定加载的配置文件-->
      
      <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
        <!--监听器-->
    </web-app>
    

    然后将Servlet文件中的内容更改为:

    @WebServlet("/loginServlet")
    public class LoginServlet extends HttpServlet {
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            ServletContext servletContext = req.getServletContext();
            WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);//Spring容器
            UserService userService = (UserService) webApplicationContext.getBean("userService");//获取Bean
            User user = userService.login("zhangsan", "123");
            System.out.println(user);
        }
    
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            this.doPost(req, resp);
        }
    }
    

整合Web的痛点

传统的MVC+三层架构:

image-20230218203541253

原始Javaweb开发中,Servlet充当Controller的角色, Jsp充当View角色, JavaBean充当模型角色,后期Ajax异
步流行后,在加上现在前后端分离开发模式成熟后, View就被原始HtmI+ Vue替代。原始Javaweb开发中,
Servlet充当Controller有很多弊端,显而易见的有如下几个:

image-20230218203728586

利用一个Servlet负责共有行为,JavaBean负责对应的业务行为:

image-20230218204043765

负责共有行为的Servlet称为前端控制器,应具有以下作用:

  • 具备可以映射到业务Bean的能力
  • 具备可以解析请求参数、封装实体等共有功能
  • 具备响应视图及响应其他数据的功能

SpringMVC

  • 配置过程
image-20230218211515868
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <servlet>
      <!--前端控制器DispatchServlet-->
    <servlet-name>DispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring_mvc.xml</param-value>
    </init-param> <!--加载的配置文件-->
      <load-on-startup>2</load-on-startup>
      <!--启动时加载 大于0生效,数字越小优先级越高-->
  </servlet>
  
  <servlet-mapping>
    <servlet-name>DispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping> 
</web-app>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.azy.web.controller"/>
	<!--交给Spring容器-->
</beans>
@Controller
public class UserController {
    @RequestMapping("/show")
    public String show(){
        System.out.println("show ...");
        return "index.jsp"
    }
}
  • SpringMVC的工作原理

    image-20230219124829443
    • 客户端发出一个http请求给web服务器,web服务器对http请求进行解析,如果匹配DispatcherServlet的请求映射路径(在web.xml中指定),web容器将请求转交给DispatcherServlet.
    • DipatcherServlet接收到这个请求之后将根据请求的信息(包括URL、Http方法、请求报文头和请求参数Cookie等)以及HandlerMapping的配置找到处理请求的处理器(Handler
    • DispatcherServlet根据HandlerMapping找到对应的Handler,将处理权交给HandlerHandler将具体的处理进行封装),再由具体的HandlerAdapterHandler进行具体的调用。
    • Handler对数据处理完成以后将返回一个ModelAndView对象给DispatcherServlet
    • Handler返回的ModelAndView是一个逻辑视图并不是一个正式的视图,DispatcherSevlet通过ViewResolver将逻辑视图转化为真正的视图View。
    • Dispatcher通过model解析出ModelAndView中的参数进行解析最终展现出完整的view并返回给客户端。

在文件DispatcherServlet.properties中包含默认的各部分组件:

org.springframework.web.servlet.HandlerMapping=org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,\
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping,\
org.springframework.web.servlet.function.support.RouterFunctionMapping

org.springframework.web.servlet.HandlerAdapter=org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,\
org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,\
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter,\
org.springframework.web.servlet.function.support.HandlerFunctionAdapter

org.springframework.web.servlet.ViewResolver=org.springframework.web.servlet.view.InternalResourceViewResolver

可以自定义各个组件,在spring_mvc.xml文件中进行配置即可:

<context:component-scan base-package="com.azy.web.controller"/>

<bean class="org.springframework.web.servlet.mvc.method.annotation.
             RequestMappingHandlerAdapter"> <!--配置HandlerAdapter-->
    <property name="messageConverters">
        <list>
            <bean class="org.springframework.http.converter.json.
                         MappingJackson2HttpMessageConverter"/>
        </list><!--注入JSON数据转换为实体类的转换器-->
    </property>
</bean>

配置好JSON转换器后,在使用JSON数据传输时就可以自动转换为实体类对象。

Spring整合SpringMVC

  • xml方式:
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <!--Spring加载-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
    
    
  <servlet>
      <!--前端控制器DispatchServlet-->
    <servlet-name>DispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring_mvc.xml</param-value>
    </init-param> <!--加载的配置文件-->
      <load-on-startup>2</load-on-startup>
      <!--启动时加载 大于0生效,数字越小优先级越高-->
  </servlet>
  
  <servlet-mapping>
    <servlet-name>DispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping> 
</web-app>
<!--spring_mvc.xml-->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.azy.web.controller"/>
	<!--交给Spring容器-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.
             RequestMappingHandlerAdapter"> <!--配置HandlerAdapter-->
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.json.
                             MappingJackson2HttpMessageConverter"/>
            </list><!--注入JSON数据转换为实体类的转换器-->
        </property>
	</bean>
</beans>

<!--applicationContext.xml-->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.azy.web.service"/>
</beans>
@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/show")
    public String show(@RequestBody User user){//JSON可以自动转换
        System.out.println(user);
        return "/index.jsp";
    }
}

标签:web,Web,--,Spring,springframework,org,DispatcherServlet,servlet
From: https://www.cnblogs.com/wuzhimao/p/17142164.html

相关文章

  • 继承Thread开启多线程下载图片(不推荐,java的单一继承性)
    packagecom.Java;importorg.apache.commons.io.FileUtils;importjava.io.File;importjava.io.IOException;importjava.net.URL;//练习多线程Thread,实现多线程下载图片......
  • VUE+Element+若依随笔001:点击左侧菜单跳转外部链接配置并传参数
    一、后台菜单配置部分:1、菜单管理中:新增父级目录2、配置内容: 菜单名称:测试用菜单 菜单路径:https://www.baidu.com/ 此处需要配置要跳转你的外部链接 组件名称:testMenu 组件......
  • windows下编译pdfium
    当前流程截至2023/2/20有效1、提前安装好工具链VS2017+SDK Win10SDK10.0.20348 +Gitforwindows+tortoisegit+代理2、下载depot_tools命令行中设置环境变......
  • k8s多节点二进制部署以及Dashboard UI
    一、多Maser集群架构的了解Kubernetes作为容器集群系统,通过健康检查+重启策略实现了Pod故障自我修复能力,通过调度算法实现将Pod分布式部署,并保持预期副本数,根据Node失效......
  • clickhouse(数据库-表-表字段相关操作)
    1、查看数据库版本selectversion();2、创建数据库createdatabasetmp;--创建数据库指定引擎,Ordinary是默认引擎,可以不指定,Ordinary引擎下面可以创建任意引擎表cre......
  • HDUOJ 2000-2100
    2024C语言合法标识符ProblemDescription输入一个字符串,判断其是否是C的合法标识符。 Input输入数据包含多个测试实例,数据的第一行是一个整数n,表示测试实例的个数,然......
  • RabbitMQ消息中间件
    课程简介课程导读:RabbitMQ中间件本课程带你轻松入门,深度掌握RabbitMQ。 RabbitMQ是实现了高级消息队列协议(AMQP)的开源消息代理软件(亦称面向消息的中间件)。RabbitMQ服务......
  • 变量的使用
    name='潮潮'age=18gender='男'print(name,age,gender)王峰18男赋值顺序是从右边望左边括号符号必须小写不能大写a=1b=[1,2,3,4,5]c=(1,2,3,4,5......
  • 类与接口
    类与对象类定义一种全新的数据类型,包含一组变量和函数;对象是类这种类型对应的实例。比如类相当于人类这个概念,而对象指的是人类中的每个人都是这个类中的一个对象;源文......
  • m基于高阶累积量和信号子空间的信噪比估计方法的matlab仿真
    1.算法描述       随着信息技术的飞速发展,信息战逐渐成为战争的一个重要方式。因此,掌握战场的信息控制权是赢得战争的重要因素。在信息战中,为了干扰和破坏对方的通......