Spring MVC

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

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

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

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

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

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

  1. package day;
  2.  
  3. import javax.servlet.ServletContext;
  4. import javax.servlet.ServletException;
  5. import javax.servlet.ServletRegistration;
  6.  
  7. import org.springframework.web.WebApplicationInitializer;
  8. import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
  9. import org.springframework.web.servlet.DispatcherServlet;
  10.  
  11. /**
  12. * Tomcat 启动的时候会检测是否有WebApplicationInitializer接口的类
  13. * 若检测到有这个类,就会实例化它,并调用他的onStartup方法
  14. * @author 张泽
  15. */
  16. public class WebInitializer implements WebApplicationInitializer {
  17.  
  18. @Override
  19. public void onStartup(ServletContext servletContext)
  20. throws ServletException {
  21. System.out.println("startup invoker the method");
  22.  
  23. //-- 1. 构造Spring容器
  24. AnnotationConfigWebApplicationContext ctx =
  25. new AnnotationConfigWebApplicationContext();
  26. //-- 2. Spring容器加载配置
  27. ctx.register(AppConfig.class);
  28. //-- 3. Spring容器接管servletContext应用上下文对象
  29. ctx.setServletContext(servletContext);
  30. //-- 4. 添加Servlet(至少添加一个Servlet,SpringMVC框架实现的入口Servlet)
  31. ServletRegistration.Dynamic servlet =
  32. servletContext.addServlet("dispatcher",new DispatcherServlet(ctx));
  33. servlet.addMapping("/");
  34. servlet.setLoadOnStartup(1);
  35. }
  36. //-- 你想使用Spring,就得有Spring容器得实例,
  37. //-- 你想使用SpringMVC就得配置DispatcherServlet得实例,
  38. //-- 还要把这两个东西放到ServletContext 对象里,为什么呢?
  39. //-- 因为他们两个都是重量级对象
  40. }

调用类

  1. package day;
  2.  
  3. import java.io.IOException;
  4. import java.io.PrintWriter;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7.  
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletResponse;
  10.  
  11. import org.springframework.stereotype.Controller;
  12. import org.springframework.web.bind.annotation.RequestMapping;
  13. import org.springframework.web.bind.annotation.ResponseBody;
  14. import org.springframework.web.servlet.ModelAndView;
  15.  
  16. import com.alibaba.fastjson.JSON;
  17.  
  18. import day.entity.User;
  19.  
  20. @Controller
  21. public class HelloController {
  22. @RequestMapping("/hello")
  23. public void hello() {
  24. System.out.println("hello");
  25. }
  26.  
  27. @RequestMapping("/hi")
  28. public void hi() {
  29. System.out.println("hi");
  30. }
  31.  
  32. @RequestMapping("/index") //-- 代表映射路径
  33. public String index(HttpServletRequest request, HttpServletResponse response) { //-- 方法名
  34. String name = request.getParameter("name");
  35. System.out.println(name);
  36. try {
  37. PrintWriter out = response.getWriter();
  38. out.write("adsfasdfasdf"+name);
  39. out.close();
  40. } catch (IOException e) {
  41. e.printStackTrace();
  42. }
  43.  
  44. return "index";//-- 页面得名字
  45. }
  46. /**
  47. * 返回字符串
  48. * @return
  49. */
  50. @RequestMapping("/data")
  51. @ResponseBody
  52. public String aaa() {
  53. List<User> users = new ArrayList<User>();
  54. users.add(new User("zz",15));
  55. users.add(new User("zz",15));
  56. users.add(new User("zz",15));
  57. //-- 2. 用alibaba得fastJson工具
  58. String jsonStr = JSON.toJSONString(users);
  59. return jsonStr;
  60. //return "[{'name':zz,'age':15}]";
  61. }
  62. /**
  63. * 返回得是页面,并且可以给页面传递数据
  64. * @return
  65. */
  66. @RequestMapping("/test")
  67. public ModelAndView bbb(HttpServletRequest request,HttpServletResponse response) {
  68.  
  69. ModelAndView mv = new ModelAndView("test");
  70. //-- do something query data
  71. mv.addObject("message", "宝塔镇河妖");
  72. return mv;
  73.  
  74. //底层:
  75. // request.setAttribute("message", "hello");
  76. // try {
  77. // request.getRequestDispatcher("/WEB-INF/test.jsp").forward(request, response);
  78. // } catch (ServletException e) {
  79. // // TODO Auto-generated catch block
  80. // e.printStackTrace();
  81. // } catch (IOException e) {
  82. // // TODO Auto-generated catch block
  83. // e.printStackTrace();
  84. // }
  85. }
  86. }

其他小知识点:

之前的访问连接: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("")

基于Maven 的 Spring MVC的更多相关文章

  1. 基于maven来Spring MVC的环境搭建遇到“坑”

    1.注解配置路径问题: 在web.xml中配置spring mvc 路径时, 应该配置如下:classpath:classpath:spring-* 2.jdk版本和Spring MVC版本不一致问题 ...

  2. 基于Maven的Spring + Spring MVC + Mybatis的环境搭建

    基于Maven的Spring + Spring MVC + Mybatis的环境搭建项目开发,先将环境先搭建起来.上次做了一个Spring + Spring MVC + Mybatis + Log4J ...

  3. 基于maven进行spring 和mybatis的整合(Myeclpise)

    学习日记:基于maven进行spring和mybatis的整合,进行分页查询 什么是maven:maven是一个项目管理工具,使用maven可以自动管理java项目的整个生命周期,包括编译.构建.测试 ...

  4. Spring7:基于注解的Spring MVC(下篇)

    Model 上一篇文章<Spring6:基于注解的Spring MVC(上篇)>,讲了Spring MVC环境搭建.@RequestMapping以及参数绑定,这是Spring MVC中最 ...

  5. Spring:基于注解的Spring MVC

    什么是Spring MVC Spring MVC框架是一个MVC框架,通过实现Model-View-Controller模式来很好地将数据.业务与展现进行分离.从这样一个角度来说,Spring MVC ...

  6. 用maven创建Spring MVC项目

    用maven创建Spring MVC项目 mvn archetype:generate -DgroupId=fry-arthur -DartifactId=spring-mvc-study -Darc ...

  7. [Java] Maven 建立 Spring MVC 工程

    GIT: https://github.com/yangyxd/Maven.SpringMVC.Web 1. 建立 WebApp 工程 下一步: 下一步: 选择 maven-archetype-web ...

  8. Eclipse Maven构建Spring MVC项目

    工作中项目开发使用Maven管理项目的构建.打包.编译,框架採用的是Spring MVC框架,而且实现了多模块.多项目的管理.自己也简单的參与了架构的设计.对于刚開始学习的人来说,使用Maven构建项 ...

  9. IDEA 通过Maven创建Spring MVC项目搭建

    概述 本篇随笔主要记录内容如下: 1.通过Maven创建基于Spring Framework类库的MVC项目,免去了繁琐的XML配置: 2.在Idea里面配置Tomcat的测试启动项: Maven创建 ...

随机推荐

  1. Nacos集群配置实例(windows下测试)

    1.首先 fork 一份 nacos 的代码到自己的 github 库,然后把代码 clone 到本地. git地址:https://github.com/alibaba/nacos.git 2.然后 ...

  2. python解析ifconfig 输出成字典

    有个需求需要将ifcofig输出解析出来,这里将写的整理出来.方便后续使用. eth0 Link encap:Ethernet HWaddr 00:50:53:b2:23:e6 inet addr:1 ...

  3. 2017 ACM/ICPC 沈阳 I题 Little Boxes

    Little boxes on the hillside. Little boxes made of ticky-tacky. Little boxes. Little boxes. Little b ...

  4. 《Dotnet9》系列-开源C# Winform控件库1《HZHControls》强力推荐

    大家好,我是Dotnet9小编,一个从事dotnet开发8年+的程序员.我最近在写dotnet分享文章,希望能让更多人看到dotnet的发展,了解更多dotnet技术,帮助dotnet程序员应用dot ...

  5. windows下tomcat闪退问题(启动失败)

    1. 第一种情况:Java jdk环境变量没配置或配置有问题 java jdk详细的配置过程这里贴一下:https://jingyan.baidu.com/article/6dad5075d1dc40 ...

  6. 【HTTP】402- 深入理解http2.0协议,看这篇就够了!

    本文字数:3825字 预计阅读时间:20分钟 导读 http2.0是一种安全高效的下一代http传输协议.安全是因为http2.0建立在https协议的基础上,高效是因为它是通过二进制分帧来进行数据传 ...

  7. 每周一练 之 数据结构与算法(Queue)

    这是第二周的练习题,这里补充下咯,五一节马上就要到了,自己的计划先安排上了,开发一个有趣的玩意儿. 下面是之前分享的链接: 1.每周一练 之 数据结构与算法(Stack) 2.每周一练 之 数据结构与 ...

  8. CentOS 7.4搭建LAMP,LAMP:Linux、Apache、MySQL、PHP

    CentOS 7.4搭建LAMP,LAMP:Linux.Apache.MySQL.PHP. 目录: 第一部分 准备工作 第二部分 安装Apache服务 第三部分 安装MySQL服务 第四部分 搭建PH ...

  9. super()派生使用中的常见两个错误

    """ super()派生可以继承父类的属性 --super()派生继承父类的语法是:super().__init__() --super().__init__()中的_ ...

  10. [ASP.NET Core 3框架揭秘] 配置[3]:配置模型总体设计

    在<读取配置数据>([上篇],[下篇])上面一节中,我们通过实例的方式演示了几种典型的配置读取方式,接下来我们从设计的维度来重写认识配置模型.配置的编程模型涉及到三个核心对象,分别通过三个 ...