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("")

基于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. ASP.NET Core 选项模式源码学习Options Configure(一)

    前言 ASP.NET Core 后我们的配置变得更加轻量级了,在ASP.NET Core中,配置模型得到了显著的扩展和增强,应用程序配置可以存储在多环境变量配置中,appsettings.json用户 ...

  2. redis数据类型--hash

    /** Redis应用之Hash数据类型* 问题1:操作命令* 问题2:存储实现原理和数据结构* 问题3:应用场景* */ 先了解下什么是hash,什么是hash碰撞:hash:是包含键值对的kv的数 ...

  3. [TimLinux] JavaScript table的td内容超过宽度缩为三个点

    1. 思路 CSS控制td内容自动缩为三个点 JS控制鼠标悬浮显示td全部内容 2. 实现 HTML代码: <!DOCTYPE html> <html> <head> ...

  4. POJ 3281 Dining(网络流-拆点)

    Cows are such finicky eaters. Each cow has a preference for certain foods and drinks, and she will c ...

  5. PyCharm配置Gitee

    PyCharm配置Gitee 第一步:下载安装Git https://git-scm.com/download/win 第二步:打开PyCharm,配置Git File->Setting-> ...

  6. 视频发布 2019 中国.NET 开发者峰会

    2019 年,注定会是 .NET Core 社区发展的关键一年,诸多重大事件在这一年发生!正如大家所期待的那样,刷新中国 .NET 社区的年度盛会--2019 中国 .NET 开发者峰会(.NET C ...

  7. Django 04

    目录 视图层 三个常用方法 JsonResponse FBV 和 CBV 模板层 模板语法 模板传值 过滤器 标签 自定义过滤器和标签 模板的继承 模板的导入 视图层 三个常用方法 HttpRespo ...

  8. 【JS】307- 复习 Object.assign 原理及其实现

    点击上方"前端自习课"关注,学习起来~ }let b = {    name: "muyiy",    book: {        title: " ...

  9. 关于 Kafka 的一些面试题目

    上周客串了一下面试官,在这里就简单记录一下期间我问到的一些关于 Kafka 的面试题目,这些都是我平时在学习 Kafka 的一些总结要点. 谈谈你对 kafka 的整体认识? 问这个问题主要是想知道面 ...

  10. 用心整理 | Spring AOP 干货文章,图文并茂,附带 AOP 示例 ~

    Spring AOP 是 Java 面试的必考点,我们需要了解 AOP 的基本概念及原理.那么 Spring AOP 到底是啥,为什么面试官这么喜欢问它呢?本文先介绍 AOP 的基本概念,然后根据 A ...