• 基于Maven 的 Spring MVC


    Spring MVC

    他是基于MVC的设计模式做出来的,他是Spring对Servlet的进一步的封装
      MVC:Model  View  Controller

    如何使用Spring MVC?(Spring 和 Spring MVC整合)
        a. pom.xml 导入 SpringMVC.jar

    <!-- Spring 5 与SpringMVC -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
             <version>${spring.version}</version>
        </dependency>


        b. 配置(xml 标注):AppConfig类
            @Configurable
            @EnableWebMvc
            @ComponentScan({"day"})

    package day;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.EnableWebMvc;
    import org.springframework.web.servlet.view.JstlView;
    import org.springframework.web.servlet.view.UrlBasedViewResolver;
    
    /**
     * 基于注解的配置类(JavaConfig配置)
     * @author 张泽
     */
    
    @Configuration
    @EnableWebMvc
    @ComponentScan({"day"})
    public class AppConfig {
        /**
         * jsp的解析器
         * 这个Bean的作用就是告诉Spring MVC 你写的JSP文件的位置
         * @return
         */
        @Bean 
        public UrlBasedViewResolver setupViewResolver() {
            UrlBasedViewResolver resolver = new UrlBasedViewResolver();
            resolver.setPrefix("/WEB-INF/");//-- 位置 受保护的,不可以直接访问
            resolver.setSuffix(".jsp"); //-- jsp文件的后缀,你在写页面的时候就省略掉后缀
            resolver.setViewClass(JstlView.class);
            return resolver;
        }
    }
    /**
        换句话说:我们要先配置好那个Servlet,并且在服务器启动的时候把它实例化
        (1)tomcat启动的时候,SpringMVC框架写了监听器ContextListener(ServletContextListener)
        (2)在ServletContextListener中实例化这个核心的Servlet
        (3)这个Serlet拦截一切请求
        (4)拦截请求后,在获取请求的路径转发给对应的Controller
        (5)Controller再进行相应的请求的处理
        
    想法:所有的Bean要纳入到Spring容器来管理,才能实现面向接口的编程
    Tomcat 启动后,会不会有Spring容器。
    当Tomcat启动的时候,我们实例化一个Spring容器。然后把它放到ServletContext
    SpringMVC:
        (1)在Tomcat启动的时候,实例化一个Spring容器放入到ServletContext对象里
        (2)并且在ServletContext中实例化那个核心的Servlet
        (3)而且该Servlet拦截一切请求
        
    */

          
            WebInitializer类:web容器启动得时候会调用该类得onStartup方法初始化工作:Spring容器与SpringMVC框架

    package day;
    
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRegistration;
    
    import org.springframework.web.WebApplicationInitializer;
    import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
    import org.springframework.web.servlet.DispatcherServlet;
    
    /**
     * Tomcat 启动的时候会检测是否有WebApplicationInitializer接口的类
     * 若检测到有这个类,就会实例化它,并调用他的onStartup方法
     * @author 张泽
     */
    public class WebInitializer implements WebApplicationInitializer {
    
        @Override
        public void onStartup(ServletContext servletContext) 
                throws ServletException {
            System.out.println("startup invoker the method");
            
            //--  1. 构造Spring容器
            AnnotationConfigWebApplicationContext ctx = 
                    new AnnotationConfigWebApplicationContext();
            //-- 2. Spring容器加载配置
            ctx.register(AppConfig.class);
            //-- 3. Spring容器接管servletContext应用上下文对象
            ctx.setServletContext(servletContext);
            //-- 4. 添加Servlet(至少添加一个Servlet,SpringMVC框架实现的入口Servlet)
            ServletRegistration.Dynamic servlet = 
                    servletContext.addServlet("dispatcher",new DispatcherServlet(ctx));
            servlet.addMapping("/");
            servlet.setLoadOnStartup(1);
        }
    //-- 你想使用Spring,就得有Spring容器得实例,
    //-- 你想使用SpringMVC就得配置DispatcherServlet得实例,
    //-- 还要把这两个东西放到ServletContext 对象里,为什么呢?
    //-- 因为他们两个都是重量级对象
    }

     
         调用类

    package day;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.servlet.ModelAndView;
    
    import com.alibaba.fastjson.JSON;
    
    import day.entity.User;
    
    @Controller
    public class HelloController {
        @RequestMapping("/hello")
        public void hello() {
            System.out.println("hello");
        }
        
        @RequestMapping("/hi")
        public void hi() {
            System.out.println("hi");
        }
        
        @RequestMapping("/index")  //-- 代表映射路径
        public String index(HttpServletRequest request,    HttpServletResponse response) {   //-- 方法名
            String name = request.getParameter("name");
            System.out.println(name);
            try {
                PrintWriter out = response.getWriter();
                out.write("adsfasdfasdf"+name);
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            
            return "index";//-- 页面得名字
        }
        /**
         * 返回字符串
         * @return
         */
        @RequestMapping("/data")
        @ResponseBody
        public String aaa() {
            List<User> users = new ArrayList<User>();
            users.add(new User("zz",15));
            users.add(new User("zz",15));
            users.add(new User("zz",15));
            //-- 2. 用alibaba得fastJson工具
            String jsonStr = JSON.toJSONString(users);
            return jsonStr;
            //return "[{'name':zz,'age':15}]";
        }
        /**
         * 返回得是页面,并且可以给页面传递数据
         * @return 
         */
        @RequestMapping("/test")
        public ModelAndView bbb(HttpServletRequest request,HttpServletResponse response) {
            
            ModelAndView mv = new ModelAndView("test");
            //-- do something query data
            mv.addObject("message", "宝塔镇河妖");
            return mv;
            
            //底层:
    //        request.setAttribute("message", "hello");
    //        try {
    //            request.getRequestDispatcher("/WEB-INF/test.jsp").forward(request, response);
    //        } catch (ServletException e) {
    //            // TODO Auto-generated catch block
    //            e.printStackTrace();
    //        } catch (IOException e) {
    //            // TODO Auto-generated catch block
    //            e.printStackTrace();
    //        }
        }
    }


            
    其他小知识点:

    之前的访问连接:URL: http://localhost:8080/hello?name=xxx&word=122
        RestFul形式接口:
            http://localhost:8080/hello/name/zhangsan/password/123456
        
        实现:hello/zhangsan/123456    
        @RequestMapping("/hello/{name}/{password}")
        public String getUser(
            @pathVariable("name") String name,
            @pathVariable("password") String password){}
     
        

    Get与Post请求:

      方法一:
          @RequestMapping(value="",method=RequestMethod.GET)

        @RequestMapping(value="",method=RequestMethod.Post)
        方法二:
          Get请求:@GetMapping("")   相等于: @RequestMapping(value="",method=RequestMethod.GET)
          Post请求:@PostMappping("")

  • 相关阅读:
    001.云桌面整体解决方案实施
    Netty基础招式——ChannelHandler的最佳实践
    架构设计之数据分片
    Go是一门什么样的语言?
    Jenkins汉化配置
    Window安装构建神器Jenkins
    uni-app&H5&Android混合开发三 || uni-app调用Android原生方法的三种方式
    如何使用Hugging Face中的datasets
    关于torch.nn.LSTM()的输入和输出
    pytorch中的nn.CrossEntropyLoss()计算原理
  • 原文地址:https://www.cnblogs.com/zhangze-lifetime/p/11807260.html
Copyright © 2020-2023  润新知