基于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创建 ...
随机推荐
- 自古逢秋悲寂寥,奈何今秋热成雕?Python使用Pyecharts统计全国温度Top10并绘图
秋词-刘禹锡 自古逢秋悲寂寥, 我言秋日胜春朝. 晴空一鹤排云上, 便引诗情到碧霄. 古人谈及秋天,都是悲凉寂寥,那么-.我好想回到古代的秋天啊!明明到了秋天,为什么最近的气温比夏天还热. 之前做天气 ...
- native-base中Input,Textarea等组件在ios平台下不能输入中文
在上文react-native中TextInput在ios平台下不能输入中文已经解决. 但是在native-base中Input和Textarea都存在这样的问题.为了不要写多个组件,封装以下代码: ...
- Python学习笔记—自动化部署【新手必学】
前言本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理.作者:唯恋殊雨 目录 pexpect fabric pexpect P ...
- windows下安装ssdb
官方下载 http://ssdb.io/docs/install.html 这是官方网站 官方建议 Do not run SSDB server on Windows system for a pro ...
- Python多版本管理器pyenv
查看Linux版本 [root@web ~]# cat /etc/redhat-release CentOS Linux release (Core) [root@web ~]# uname -a L ...
- 【Jackson】使用学习
Jackson学习 文档:http://tutorials.jenkov.com/java-json/index.html https://github.com/FasterXML/jackson/w ...
- CCPC Wannafly Winter Camp Div2 部分题解
Day 1, Div 2, Prob. B - 吃豆豆 题目大意 wls有一个\(n\)行\(m\)列的棋盘,对于第\(i\)行第\(j\)列的格子,每过\(T[i][j]\)秒会在上面出现一个糖果, ...
- contiue和break的用法
contiue和break的作用分别是什么: 1.continue的意思是终止本次循环,直接进入下一次循环. 注意: continue不能加在循环体的最后一步执行的代码,因为代码加上去毫无意义 2.b ...
- 安装lispbox出现:error while loading shared libraries: libjpeg.so.62: cannot open shared object file: No such file or directory
如下图,运行lispbox出现如下报错(第一个命令): 检索之后发现解决办法:Solution to libjpeg.so.62 输入一下两条命令(第二条也必须执行): sudo apt-get up ...
- 聊一聊看似简单的Promise.prototype.then()方法
Promise.prototype.then() Proise实例的then方法是定义在原型对象Promise.prototype上的,它的作用是为Promise实例添加状态改变时的回调函数. 该方法 ...