SpringMVC+Spring+mybatis+redis项目从零开始--Springmvc配置实现

来源:互联网 发布:淘宝设计教程 编辑:程序博客网 时间:2024/06/04 19:52

文章列表:

一.SSM项目-分布式项目结构搭建
二.SSM项目-Spring mybatis mysql配置实现
三.SSM项目-redis缓存策略和配置实现
四.SSM项目-Springmvc配置实现

四、SSM项目-Springmvc配置实现

上几章我们简单介绍了SSM项目工程结构、SSM相关配置和集成Redis实现等,本章将实现Springmvc等相关配置,同时通过简单的文件上传、图片上传等实例。

1.     Springmvc简介

Spring Web MVC是一种基于Java的实现了Web MVC设计模式的请求驱动类型的轻量级Web框架,即使用了MVC架构模式的思想,将web层进行职责解耦,基于请求驱动指的就是使用请求-响应模型,框架的目的就是帮助我们简化开发,Spring Web MVC也是要简化我们日常Web开发的。

另外还有一种基于组件的、事件驱动的Web框架在此就不介绍了,如Tapestry、JSF等。

Spring Web MVC也是服务到工作者模式的实现,但进行可优化。前端控制器是DispatcherServlet应用控制器其实拆为处理器映射器(Handler Mapping)进行处理器管理和视图解析器(ViewResolver)进行视图管理;页面控制器/动作/处理器为Controller接口(仅包含ModelAndView handleRequest(request, response) 方法)的实现(也可以是任何的POJO类);支持本地化(Locale)解析、主题(Theme)解析及文件上传等;提供了非常灵活的数据验证、格式化和数据绑定机制;提供了强大的约定大于配置(惯例优先原则)的契约式编程支持。

2.    Springmvc优势

1)   让我们能非常简单的设计出干净的Web层和薄薄的Web层;

2)   进行更简洁的Web层的开发;

3)   天生与Spring框架集成(如IoC容器、AOP等);

4)   提供强大的约定大于配置的契约式编程支持;

5)   能简单的进行Web层的单元测试;

6)   支持灵活的URL到页面控制器的映射;

7)   非常容易与其他视图技术集成,如Velocity、FreeMarker等等,因为模型数据不放在特定的API里,而是放在一个Model里(Map数据结构实现,因此很容易被其他框架使用);

8)   非常灵活的数据验证、格式化和数据绑定机制,能使用任何对象进行数据绑定,不必实现特定框架的API;

9)   提供一套强大的JSP标签库,简化JSP开发;

10)支持灵活的本地化、主题等解析;

11)更加简单的异常处理;

12)对静态资源的支持;

13) 支持Restful风格。

3.    Springmvc原理

 

4.     Springmvc常用注解

Springmvc中常用注解有RequestMapping、RequestParam、ResponseBody、PathVariable等,下面我们将一一介绍。

4.1  RequsetMapping

RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。

RequestMapping注解有六个属性,下面我们把她分成三类进行说明(下面有相应示例)。

a、 value, method;

value:     指定请求的实际地址,指定的地址可以是URITemplate 模式(后面将会说明);

method:  指定请求的method类型, GET、POST、PUT、DELETE等;

b、consumes,produces

consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;

produces:    指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;

c、params,headers

params: 指定request中必须包含某些参数值是,才让该方法处理。

headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。

4.2  RequstParam

@requestParam主要用于在SpringMVC后台控制层获取参数,

类似一种是request.getParameter("name"),它有三个常用参数:defaultValue = "0", required = false, value ="isApp";defaultValue 表示设置默认值,required 通过boolean设置是否是必须要传入的参数,value 值表示接受的传入的参数类型。

4.3  PathVariable

用于将请求URL中的模板变量映射到功能处理方法的参数上,即取出uri模板中的变量作为参数。

{id}在这个请求的URL里就是个变量,可以使用@PathVariable来获取。

@PathVariable和@RequestParam的区别就在于:

@RequestParam用来获得静态的URL请求参数;

@PathVariable用来获得动态的URL请求入参。


4.4  ResponseBody 

该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。

使用时机:返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用;

4.5  新版本引入注解

Spring4.3中引进了

{@GetMapping、@PostMapping、@PutMapping、@DeleteMapping、@PatchMapping},来帮助简化常用的HTTP方法的映射,并更好地表达被注解方法的语义。

  以@GetMapping为例,Spring官方文档说:

  @GetMapping是一个组合注解,是@RequestMapping(method =RequestMethod.GET)的缩写。该注解将HTTP Get 映射到 特定的处理方法上。

5.     Springmvc相关配置

5.1 springmvc.xml配置

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"><context:component-scan base-package="com.ssm.manager.controller" /><mvc:annotation-driven /><beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/jsp/" /><property name="suffix" value=".jsp" /></bean><!-- 资源映射 --><mvc:resources location="/WEB-INF/css/" mapping="/css/**" /><mvc:resources location="/WEB-INF/js/" mapping="/js/**" /><!-- 定义文件上传解析器 --><bean id="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><!-- 设定默认编码 --><property name="defaultEncoding" value="UTF-8"></property><!-- 设定文件上传的最大值5MB,5*1024*1024 --><!-- 指定所上传文件的总大小不能超过200KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 --><property name="maxUploadSize" value="5242880"></property></bean><!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 --><bean id="exceptionResolver"class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"><property name="exceptionMappings"><props><!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到WebContent目录下的error.jsp页面 --><propkey="org.springframework.web.multipart.MaxUploadSizeExceededException">error</prop></props></property></bean></beans>

5.2 web.xml配置

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"id="ssm" version="2.5"><display-name>ssm-manager</display-name><welcome-file-list><welcome-file>index.html</welcome-file><welcome-file>index.htm</welcome-file><welcome-file>index.jsp</welcome-file><welcome-file>default.html</welcome-file><welcome-file>default.htm</welcome-file><welcome-file>default.jsp</welcome-file></welcome-file-list><!-- 加载spring容器 --><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring/applicationContext-service.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!-- 解决post乱码 --><filter><filter-name>CharacterEncodingFilter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>utf-8</param-value></init-param></filter><filter-mapping><filter-name>CharacterEncodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><!-- springmvc的前端控制器 --><servlet><servlet-name>ssm-manager</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><!-- contextConfigLocation不是必须的, 如果不配置contextConfigLocation, springmvc的配置文件默认在:WEB-INF/servlet的name+"-servlet.xml" --><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring/springmvc.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>ssm-manager</servlet-name><url-pattern>/</url-pattern></servlet-mapping></web-app>

6.     实例文件上传下载

6.1  jsp文件

<%@ 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>SSM项目实战-上传</title><body><form action="uploadFile" method="post" enctype="multipart/form-data">文件1: <input type="file" name="myfiles" /><br /> 文件2: <inputtype="file" name="myfiles" /><br /> 文件3: <input type="file"name="myfiles" /><br /> <input type="submit" value="上传"></form><a href="download?fileName=20170206151413281020950798404189.jpg">下载</a></body></head>

6.2  controller文件 

package com.ssm.manager.controller;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.text.SimpleDateFormat;import java.util.Date;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.RequestParam;import org.springframework.web.multipart.MultipartFile;import com.ssm.commons.FileUtil;@Controllerpublic class TestController {@RequestMapping("/")public String index() {return "index";}@RequestMapping("/hello")public String hello() {return "hello";}@RequestMapping("/upload")public String upload() {return "upload";}@RequestMapping("/uploadFile")public String upload(@RequestParam MultipartFile[] myfiles,HttpServletRequest request) throws IOException {if (myfiles == null || myfiles.length == 0) {return "upload";}for (MultipartFile file : myfiles) {// 此处MultipartFile[]表明是多文件,如果是单文件MultipartFile就行了if (file.isEmpty()) {System.out.println("文件未上传!");} else {// 得到上传的文件名String fileName = file.getOriginalFilename();boolean isImage = FileUtil.isImage(fileName);// 得到服务器项目发布运行所在地址String sourcePath = "";if (isImage) {sourcePath = request.getSession().getServletContext().getRealPath("image")+ File.separator;} else {sourcePath = request.getSession().getServletContext().getRealPath("tempFile")+ File.separator;}// 此处未使用UUID来生成唯一标识,用日期做为标识String path = sourcePath+ new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + fileName;// 查看文件上传路径,方便查找System.out.println(path);// 把文件上传至path的路径File localFile = new File(path);file.transferTo(localFile);}}return "success";}@RequestMapping("/download")public void download(String fileName, HttpServletRequest request,HttpServletResponse response) {response.setCharacterEncoding("utf-8");response.setContentType("multipart/form-data");response.setHeader("Content-Disposition", "attachment;fileName="+ fileName);try {String path = request.getSession().getServletContext().getRealPath("image")+ File.separator;InputStream inputStream = new FileInputStream(new File(path+ fileName));OutputStream os = response.getOutputStream();byte[] b = new byte[2048];int length;while ((length = inputStream.read(b)) > 0) {os.write(b, 0, length);}// 这里主要关闭。os.flush();os.close();inputStream.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}// 返回值要注意,要不然就出现下面这句错误!// java+getOutputStream() has already been called for this response}}

7.     总结 

至此,我们Springmvc+spring+mybatis+mysql+redis的web项目介绍完毕。我们通过四章分别从项目结构、Spring+mybatis集成、Spring+mybatis+redis集成和Springmvc+spring+mybatis+redis集成实现ssm项目。本系列文章只是简单介绍原理,使用方式,如果想深入了解,需要自身通过其他途径加强。

谢谢!

8. 代码

代码地址:http://download.csdn.net/download/a123demi/10029883

GITHUB地址:https://github.com/a123demi/spring_ssm


阅读全文
1 0
原创粉丝点击