Spring MVC项目搭建

添加依赖

(省略)

Spring MVC配置类

@Configuration
@EnableWebMvc
@ComponentScan("com.sjx.springmvc")
public class MyMvcConfig extends WebMvcConfigurerAdapter{
@Bean
public InternalResourceViewResolver viewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/classes/views/");
viewResolver.setSuffix(".jsp");
viewResolver.setViewClass(JstlView.class);
return viewResolver;
}
}

Web配置,实现WebApplicationInitializer接口代替web.xml文件

public class WebInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(MyMvcConfig.class);
ctx.setServletContext(servletContext); Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
}

Spring MVC的常用注解

  • @controller
    @controller注解在类上,表明这个类为Spring MVC的Controller,并讲Web请求映射到注解了@RequestMapping的方法上

  • @RequestMapping
    @RequestMapping是用来映射Web请求的的方法,可以注解在类上,方法上的@RequestMapping路径会继承类上的路基,并且produces属性可以设置请求的媒体类型

  • @ResponseBody
    @ResponseBody可以注解类上也可注解在方法上,支持把返回值放入response体内,而不是返回一个页面

  • @RequestBody
    @RequestBody注解在参数前,允许请求的参数在request体中,而不是直接放在链接地址的后面

  • @PathVariable
    @PathVariable用来接受路劲参数,次注解用在参数前面,如pathvar/{str},可接受参数str

  • @RestController
    @RestController是一个组合注解,是@Controller和@ResponseBody的组合

@Controller
@RequestMapping("/anno")
public class DemoAnnoController { @RequestMapping(produces = "text/plain;charset=UTF-8")
public @ResponseBody String index(HttpServletRequest request) {
return "url" + request.getRequestURI() + "can access";
} // http://localhost:8080/springmvc1/anno/pathvar/sjx@RequestMapping(value = "pathvar/{str}", produces = "text/plain;charset=UTF-8")
public @ResponseBody String demoPathVar(@PathVariable String str, HttpServletRequest request) {
return "url" + request.getRequestURI() + " can access str:" + str;
} // http://localhost:8080/springmvc1/anno/requestParam?id=25@RequestMapping(value = "/requestParam", produces = "text/plain;charset=UTF-8")
public @ResponseBody String passRequestParam(Long id, HttpServletRequest request) {
return "url" + request.getRequestURI() + " can access id:" + id;
} @RequestMapping(value = "/obj", produces = "application/json;charset=UTF-8")
@ResponseBodypublic String passObj(DemoObj obj, HttpServletRequest request) {
return "url" + request.getRequestURI() + " can access, obj id:" + obj.getId() + " obj name:" + obj.getName();
} @RequestMapping(value = { "/name1", "/name2" }, produces = "text/plain;charset=UTF-8")
public @ResponseBody String remove(HttpServletRequest request) {
return "url: " + request.getRequestURL() + " can access";
}
}

Spring MVC的基本配置

拦截器配置

  • 拦截器类
    1. 继承HandlerInterceptorAdapter实现自定义拦截器
    2. 重写preHandle方法,请求发生时执行
    3. 重写postHandle方法,请求结束是执行
public class DemoInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
long startTime = System.currentTimeMillis();
request.setAttribute("startTime", startTime);
return true;
} @Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
Long startTime = (Long) request.getAttribute("startTime");
Long currentTime = System.currentTimeMillis();
long handlerTime = currentTime - startTime;
System.out.println("一次请求的时间为" + handlerTime + "ms");
request.setAttribute("handlerTime", handlerTime);
}
}
  • 配置
    1. 配置拦截器的Bean
    2. 重写addInterceptors(InterceptorRegistry registry)方法,添加拦截器
@Configuration
@EnableWebMvc
@ComponentScan("com.sjx.springmvc")
public class MyMvcConfig extends WebMvcConfigurerAdapter{
@Bean
public InternalResourceViewResolver viewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/classes/views/");
viewResolver.setSuffix(".jsp");
viewResolver.setViewClass(JstlView.class);
return viewResolver;
} //自定义拦截器
@Bean
public DemoInterceptor handlerTimeInterceptor(){
return new DemoInterceptor();
} //添加拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(handlerTimeInterceptor());
}
}

@ControllerAdvice

使用@ControllerAdvice注解可以将对于控制器的全局配置放在一起

  • @ExceptionHandler 用于处理全局处理器中的异常
  • @ModelAttribute 本来是用于将键值对绑定到Model里,这里用于让全局的@RequestMapping都能接收到此键值对
//声明一个全局通知  此注解包含了
@Component
@ControllerAdvice
public class ExceptionHandlerAdvice { //拦截所有的异常 显示error界面@ExceptionHandler(value = Exception.class)
public ModelAndView exception(Exception exception, WebRequest request) {
ModelAndView view = new ModelAndView("error");// error界面
view.addObject("errorMessage", exception.getMessage());
return view;
} //所有用@RequestMapping注解的方法 都能获取这个键值对
    @ModelAttribute
    public void addAttribute(Model mode) {
mode.addAttribue("msg", "额外信息");
}
}

文件上传配置

  • 添加依赖
<!-- 文件上传 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2</version>
</dependency>
<!-- 简化文件操作 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
  • 上传页面
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传</title>
</head>
<body>
<div class="upload">
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file"><br><input type="submit" value="上传文件">
</form>
</div>
</body>
</html>
  • 添加upLoad的ViewController
//集中处理跳转页面
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/toUpload").setViewName("/upload");
}
  • 配置MultipartResolver
//配置MultipartResolver,用MultipartFile 接受文件上传
@Bean
public MultipartResolver multipartResolver(){
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(1000000);
return multipartResolver;
}
  • 控制器
@Controller
public class UploadController {
@RequestMapping(value = "upload", method = RequestMethod.POST)
public @ResponseBody String upload(MultipartFile file) {
try {
// 使用 commons-io包实现快读文件写入磁盘
FileUtils.writeByteArrayToFile(new File("e:/upload/" + file.getOriginalFilename()), file.getBytes());
return "success";
} catch (IOException e) {
e.printStackTrace();
return "fail";
}
}
}

Spring MVC小结的更多相关文章

  1. Spring MVC小结1

    由于最近刚开始学Spring MVC,所以来讲一下自己的理解. 首先进行环境配置: 1.jdk 2.myeclipse 3.tomcat 4.maven 配置maven的时候出现了一个小的问题,JAV ...

  2. Spring学习(十一)--Spring MVC

    1.MVC模式 (1)视图 通过视图展示应用数据    向应用数据提供更新动作   向控制器提交用户动作   运行控制器选择不同视图 (2)模型提供 封装应用数据状态  响应数据状态查询  提供应用功 ...

  3. Spring mvc中@RequestMapping 6个基本用法小结(转载)

    小结下spring mvc中的@RequestMapping的用法. 1)最基本的,方法级别上应用,例如: @RequestMapping(value="/departments" ...

  4. spring mvc中的拦截器小结 .

    在spring mvc中,拦截器其实比较简单了,下面简单小结并demo下. preHandle:预处理回调方法,实现处理器的预处理(如登录检查),第三个参数为响应的处理器(如我们上一章的Control ...

  5. Spring mvc中@RequestMapping 6个基本用法小结

    Spring mvc中@RequestMapping 6个基本用法小结 小结下spring mvc中的@RequestMapping的用法. 1)最基本的,方法级别上应用,例如: @RequestMa ...

  6. 转:Spring mvc中@RequestMapping 6个基本用法小结

    Spring mvc中@RequestMapping 6个基本用法小结 发表于3年前(2013-02-17 19:58)   阅读(11698) | 评论(1) 13人收藏此文章, 我要收藏 赞3 4 ...

  7. Spring MVC 原理小结

    主要由DispatcherServlet.处理器映射.处理器.视图解析器.视图组成   1.DispatcherServlet接收到一个HTTP请求,根据对应配置文件中的处理机映射,找到处理器(Han ...

  8. Spring mvc 模式小结

    http://www.taobaotesting.com/blogs/2375 1.spring mvc简介 Spring MVC框架是一个MVC框架,通过实现Model-View-Controlle ...

  9. spring in action 5.1 小结 spring mvc起步

    0 配置 DispatcherServlet 是 spring mvc的核心,常规配置方法可以查看之前博客.springMVC简单例子 在此使用servlet 3 规范和 spring3.1 功能增强 ...

随机推荐

  1. winform app.config文件的动态配置

    获取 获取应用程序exe.config文件中  节点value值 /// <summary> /// 功能: 读取应用程序exe.config文件中 /// appSettings节点下 ...

  2. (33)odoo中产品价格字段

    打开product.template 和 product.product 模型发现有很多关于价格描述的字段 product.template:        price        list_pri ...

  3. 读javascript高级程序设计11-事件

    一.事件流 事件流指从页面中接收事件的顺序. 1.事件冒泡(常用) IE中采用的事件流是事件冒泡,先从具体的接收元素,然后逐步向上传播到不具体的元素. 2.事件捕获(少用) Netscapte采用事件 ...

  4. iOS开发网络篇—网络编程基础

    iOS开发网络篇—网络编程基础 一.为什么要学习网络编程 1.简单说明 在移动互联网时代,移动应用的特征有: (1)几乎所有应用都需要用到网络,比如QQ.微博.网易新闻.优酷.百度地图 (2)只有通过 ...

  5. ros使用rplidar hector_mapping建地图

    ros中建地图方式有两种: 首先1.首先下载hector_slam包到你工作空间的src下 命令: cd ~/catkin/src git clone https://github.com/tu-da ...

  6. mysql命令行创建存储过程命令行定时执行sql语句

    mysql -uroot -p show databases; use scm; show tables; show procedure status; 其他命令: SHOW VARIABLES LI ...

  7. 在standalone模式下运行yarn 0.9.0对HDFS上的数据进行计算

    1.通读http://spark.incubator.apache.org/docs/latest/spark-standalone.html 2.在每台机器上将spark安装到/opt/spark ...

  8. C++ 之 const 随笔记

    const关键字,相信对C语言有所了解的同学都应该知道他的作用:1.修饰常量,2.修饰指针,3.修饰函数 1.修饰常量 const修饰后的变量被定义为常量 2.修饰指针 当用const修饰指针的时候, ...

  9. shell多行注释

    :<<BLOCK ....被注释的多行内容 BLOCK :<< 'BLOCK ....被注释的多行内容 BLOCK'

  10. ios中通知的简单使用

    通知的机制是一对多,而block和delegate的机制是一对一,通知是好用,但小伙伴么要记得通知比较耗性能哦~~~ 谁要发送消息,谁就发出通知,谁要接受消息,谁就销毁通知. 下面直接来看代码: // ...