基于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("")
基于Maven 的 Spring MVC的更多相关文章
- 基于maven来Spring MVC的环境搭建遇到“坑”
1.注解配置路径问题: 在web.xml中配置spring mvc 路径时, 应该配置如下:classpath:classpath:spring-* 2.jdk版本和Spring MVC版本不一致问题 ...
- 基于Maven的Spring + Spring MVC + Mybatis的环境搭建
基于Maven的Spring + Spring MVC + Mybatis的环境搭建项目开发,先将环境先搭建起来.上次做了一个Spring + Spring MVC + Mybatis + Log4J ...
- 基于maven进行spring 和mybatis的整合(Myeclpise)
学习日记:基于maven进行spring和mybatis的整合,进行分页查询 什么是maven:maven是一个项目管理工具,使用maven可以自动管理java项目的整个生命周期,包括编译.构建.测试 ...
- Spring7:基于注解的Spring MVC(下篇)
Model 上一篇文章<Spring6:基于注解的Spring MVC(上篇)>,讲了Spring MVC环境搭建.@RequestMapping以及参数绑定,这是Spring MVC中最 ...
- Spring:基于注解的Spring MVC
什么是Spring MVC Spring MVC框架是一个MVC框架,通过实现Model-View-Controller模式来很好地将数据.业务与展现进行分离.从这样一个角度来说,Spring MVC ...
- 用maven创建Spring MVC项目
用maven创建Spring MVC项目 mvn archetype:generate -DgroupId=fry-arthur -DartifactId=spring-mvc-study -Darc ...
- [Java] Maven 建立 Spring MVC 工程
GIT: https://github.com/yangyxd/Maven.SpringMVC.Web 1. 建立 WebApp 工程 下一步: 下一步: 选择 maven-archetype-web ...
- Eclipse Maven构建Spring MVC项目
工作中项目开发使用Maven管理项目的构建.打包.编译,框架採用的是Spring MVC框架,而且实现了多模块.多项目的管理.自己也简单的參与了架构的设计.对于刚開始学习的人来说,使用Maven构建项 ...
- IDEA 通过Maven创建Spring MVC项目搭建
概述 本篇随笔主要记录内容如下: 1.通过Maven创建基于Spring Framework类库的MVC项目,免去了繁琐的XML配置: 2.在Idea里面配置Tomcat的测试启动项: Maven创建 ...
随机推荐
- Nacos集群配置实例(windows下测试)
1.首先 fork 一份 nacos 的代码到自己的 github 库,然后把代码 clone 到本地. git地址:https://github.com/alibaba/nacos.git 2.然后 ...
- python解析ifconfig 输出成字典
有个需求需要将ifcofig输出解析出来,这里将写的整理出来.方便后续使用. eth0 Link encap:Ethernet HWaddr 00:50:53:b2:23:e6 inet addr:1 ...
- 2017 ACM/ICPC 沈阳 I题 Little Boxes
Little boxes on the hillside. Little boxes made of ticky-tacky. Little boxes. Little boxes. Little b ...
- 《Dotnet9》系列-开源C# Winform控件库1《HZHControls》强力推荐
大家好,我是Dotnet9小编,一个从事dotnet开发8年+的程序员.我最近在写dotnet分享文章,希望能让更多人看到dotnet的发展,了解更多dotnet技术,帮助dotnet程序员应用dot ...
- windows下tomcat闪退问题(启动失败)
1. 第一种情况:Java jdk环境变量没配置或配置有问题 java jdk详细的配置过程这里贴一下:https://jingyan.baidu.com/article/6dad5075d1dc40 ...
- 【HTTP】402- 深入理解http2.0协议,看这篇就够了!
本文字数:3825字 预计阅读时间:20分钟 导读 http2.0是一种安全高效的下一代http传输协议.安全是因为http2.0建立在https协议的基础上,高效是因为它是通过二进制分帧来进行数据传 ...
- 每周一练 之 数据结构与算法(Queue)
这是第二周的练习题,这里补充下咯,五一节马上就要到了,自己的计划先安排上了,开发一个有趣的玩意儿. 下面是之前分享的链接: 1.每周一练 之 数据结构与算法(Stack) 2.每周一练 之 数据结构与 ...
- CentOS 7.4搭建LAMP,LAMP:Linux、Apache、MySQL、PHP
CentOS 7.4搭建LAMP,LAMP:Linux.Apache.MySQL.PHP. 目录: 第一部分 准备工作 第二部分 安装Apache服务 第三部分 安装MySQL服务 第四部分 搭建PH ...
- super()派生使用中的常见两个错误
""" super()派生可以继承父类的属性 --super()派生继承父类的语法是:super().__init__() --super().__init__()中的_ ...
- [ASP.NET Core 3框架揭秘] 配置[3]:配置模型总体设计
在<读取配置数据>([上篇],[下篇])上面一节中,我们通过实例的方式演示了几种典型的配置读取方式,接下来我们从设计的维度来重写认识配置模型.配置的编程模型涉及到三个核心对象,分别通过三个 ...