Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面。Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块。使用 Spring 可插入的 MVC 架构,从而在使用Spring进行WEB开发时,可以选择使用Spring的SpringMVC框架或集成其他MVC开发框架,如Struts1,Struts2等。

框架

编辑

  通过策略接口,Spring 框架是高度可配置的,而且包含多种视图技术,例如 JavaServer Pages(JSP)技术、VelocityTilesiText和POI。Spring MVC 框架并不知道使用的视图,所以不会强迫您只使用 JSP 技术。Spring MVC 分离了控制器、模型对象、过滤器以及处理程序对象的角色,这种分离让它们更容易进行定制。

优点

编辑

  Lifecycle for overriding binding, validation, etc,易于同其它View框架(Tiles等)无缝集成,采用IOC便于测试。
它是一个典型的教科书式的mvc构架,而不像struts等都是变种或者不是完全基于mvc系统的框架,对于初学者或者想了解mvc的人来说我觉得 spring是最好的,它的实现就是教科书!第二它和tapestry一样是一个纯正的servlet系统,这也是它和tapestry相比 struts所具有的优势。而且框架本身有代码,看起来容易理解。
 
搭建环境:

一、导包

二、配置

首先编写spring的配置文件  spring-all.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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd"> <context:component-scan base-package="com.*" />
<mvc:annotation-driven />
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/page/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 文件上传需要配置的类 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 文件总大小(单位是b) -->
<property name="maxUploadSize" value="10000000"></property>
<!-- 单个文件大小 -->
<property name="maxUploadSizePerFile" value="2000000"></property>
<!-- 字符集 -->
<property name="defaultEncoding" value="utf-8"></property>
</bean> <!-- 转换编码为utf-8的bean -->
<bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean
class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean>
</beans>

编写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"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-all.xml</param-value>
</init-param>
<!-- 启动时加载 -->
<load-on-startup>1</load-on-startup>
</servlet> <!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>

定义一个实体类

package com.model;

import java.util.Date;

import org.springframework.format.annotation.DateTimeFormat;

public class Person {
private Integer id;
private String name;
@DateTimeFormat(pattern="yyyyMMdd")
private Date birthday; public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", birthday=" + birthday + "]";
} }

编写具体实现的控制文件 PersonController.java

package com.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile; import com.model.Person; @Controller
public class PersonController { //页面跳转
@RequestMapping("test")
public String test(){ return "success";
} //传值,字符串和数字
@RequestMapping("test0/{ss}")
public String test0(@PathVariable("ss")String str){
System.out.println(str);
//System.out.println(num);
return "error";
} @RequestMapping(value="test1",method={RequestMethod.POST,RequestMethod.GET})
public String test1(@RequestParam("str")String str,@RequestParam("num")int num){
System.out.println(str);
System.out.println(num);
return "error";
}
@RequestMapping(value="test2")
public String test2(@RequestParam("str")String str,@RequestParam("num")int num){
System.out.println(str);
System.out.println(num);
return "error";
} //传日期型参数
@RequestMapping("test3")
public String test3(@RequestParam("date")@DateTimeFormat(pattern="yyyyMMdd")Date date){ System.out.println(date);
return "success";
} //传递实体类
@RequestMapping("test4")
public String test4(Person p){
System.out.println(p);
return "success";
} //传递数组
@RequestMapping("test5")
public String test5(@RequestParam("strs[]")String[] strs){
for(String s:strs){
System.out.println(s);
}
return "success";
} //带日期型参数的实体类
@RequestMapping("test6")
public String test6(Person p){
System.out.println(p);
return "success";
} @ResponseBody
@RequestMapping("test7")
public String test7(Person p){
System.out.println(p);
String json = "{\"success\":true}";
return json;
} //@ResponseBody
@RequestMapping("test8")
public String test8(@RequestParam("file")MultipartFile file,HttpServletRequest request){ String path = request.getServletContext().getRealPath("/files");
String fileName = file.getOriginalFilename();
System.out.println(fileName);
fileName+=new Date().getTime();
File filenew = new File(path+"/"+fileName); try {
file.transferTo(filenew);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "success";
} @RequestMapping("testm")
public String testm(@RequestParam("file")MultipartFile[] files,HttpServletRequest request){ String path = request.getServletContext().getRealPath("/files");
for(int i=0;i<files.length;i++){
String fileName = files[i].getOriginalFilename();
System.out.println(fileName);
fileName+=new Date().getTime();
File filenew = new File(path+"/"+fileName);
try {
files[i].transferTo(filenew);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} return "success";
} @RequestMapping(value = "test9")
// public ResponseEntity<byte[]> download(String fileName, File file) throws
// IOException {
public ResponseEntity<byte[]> download(HttpServletRequest request, @RequestParam("filename") String filename)
throws IOException {
//filename = new String(filename.getBytes("UTF-8"), "iso-8859-1");// 为了解决中文名称乱码问题
String path = request.getServletContext().getRealPath("/files");
path += "\\" + filename;
File file = new File(path);
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment",filename);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
}
}

定义一个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>Insert title here</title>
<script type="text/javascript" src="js/jquery-1.11.2.min.js"></script>
</head>
<body>
<a href="test.do">测试</a>
<a href="test0/haha.do">测试0</a><br>
<a href="test1.do?str=nihao&num=123">测试1</a><br>
<form action="test2.do" method="post">
<input type="text" name="str">
<input type="text" name="num">
<input type="submit" value="提交">
</form><br>
<a href="test3.do?date=20170419">测试2</a><br> <form action="test4.do" method="post">
<input type="text" name="id">
<input type="text" name="name">
<input type="submit" value="提交">
</form><br> <form action="test5.do" method="post">
<input type="text" name="strs[]">
<input type="text" name="strs[]">
<input type="submit" value="提交">
</form><br> <form action="test6.do" method="post">
<input type="text" name="id">
<input type="text" name="name">
<input type="text" name="birthday">
<input type="submit" value="提交">
</form><br> <form id="form">
<input type="text" name="id">
<input type="text" name="name">
<input type="text" name="birthday">
<input id="btn" type="button" value="提交">
</form><br> <form action="test8.do" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="文件上传" />
</form><br> <form action="testm.do" method="post" enctype="multipart/form-data">
<input multiple="true" type="file" name="file" />
<input type="submit" value="文件上传" />
</form><br> <a href="test9.do?filename=jsonarray.rb">下载测试-jsonarray.rb</a><br>
<a href="test9.do?filename=content.docx">下载测试-content.docx</a><br> <script type="text/javascript">
$(function(){
$("#btn").click(function(){
var f = $("#form").serializeArray();
$.ajax({
url:"test7.do",
data:f,
dataType:"json",
type:"POST",
success:function(d){
console.log(d);
},
error:function(msg){
console.log(msg.responseText);
}
});
});
}); /* $(function(){
$("#btn_upload").click(function(){
var f = $("#formupload").serializeArray();
$.ajax({
url:"test8.do",
data:f,
dataType:"json",
type:"POST",
success:function(d){
console.log(d);
},
error:function(msg){
console.log(msg.responseText);
}
});
});
}); */
</script>
</body>
</html>

实现效果如下:

Spring_mvc的搭建以及实现的更多相关文章

  1. 原:maven+springMVC+mybatis+junit详细搭建过程

    阅读目录 1.  工程目录结构整理清楚 2.  引入依赖包 3. 配置数据库连接属性 4.  配置spring配置文件 5.  java代码编写(model,dao,service层代码) 6.  m ...

  2. spring_mvc入门项目的小总结

    1.先搭建一个maven的web项目 ,然后把文件夹完善一下,创建一个java的文件夹和resource的问件夹,并指定他们各自的功能. 导入pom.xml文件的依赖 <properties&g ...

  3. 带你搭建一个简单的mybatis项目:IDEA+spring+springMVC+mybatis+Mysql

    最近小编有点闲,突发奇想想重温一下mybatis,然后在脑海中搜索了一下,纳尼,居然不太会用了,想到这里都是泪啊!!现在我所呆的的公司使用的是springboot+hebinate,编程都是使用的JP ...

  4. Online Judge(OJ)搭建(第一版)

    搭建 OJ 需要的知识(重要性排序): Java SE(Basic Knowledge, String, FileWriter, JavaCompiler, URLClassLoader, Secur ...

  5. Angular2入门系列教程1-使用Angular-cli搭建Angular2开发环境

    一直在学Angular2,百忙之中抽点时间来写个简单的教程. 2016年是前端飞速发展的一年,前端越来越形成了(web component)组件化的编程模式:以前Jquery通吃一切的田园时代一去不复 ...

  6. 总结:Mac前端开发环境的搭建(配置)

    新年新气象,在2016年的第一天,我入手了人生中第一台自己的电脑(大一时好友赠送的电脑在一次无意中烧坏了主板,此后便不断借用别人的或者网站的).macbook air,身上已无分文...接下来半年的房 ...

  7. Angular企业级开发(5)-项目框架搭建

    1.AngularJS Seed项目目录结构 AngularJS官方网站提供了一个angular-phonecat项目,另外一个就是Angular-Seed项目.所以大多数团队会基于Angular-S ...

  8. 【分享】标准springMVC+mybatis项目maven搭建最精简教程

    文章由来:公司有个实习同学需要做毕业设计,不会搭建环境,我就代劳了,顺便分享给刚入门的小伙伴,我是自学的JAVA,所以我懂的.... (大图直接观看显示很模糊,请在图片上点击右键然后在新窗口打开看) ...

  9. 一起学微软Power BI系列-使用技巧(4)Power BI中国版企业环境搭建和帐号问题

    千呼万唤的Power BI中国版终于落地了,相信12月初的微软技术大会之后已经铺天盖地的新闻出现了,不错,Power BI中国版真的来了,但还有些遗憾,国际版的一些重量级服务如power bi emb ...

随机推荐

  1. DA层(数据访问层)的方法不用静态的

    1.静态方法,不会经过构造函数,所以你不能通过构造函数来初始参数,你只能通过传递参数,来初始他当你有多种参数需要传递的时候,你就要不断重载他了.当然你可以用参数型的类型,不过如果参数有一定结构,就很麻 ...

  2. Android(java)学习笔记119:BroadcastReceiver之 短信发送的广播接收者

    有时候,我们需要开发出来一个短信监听器,监听用户发送的短信记录,下面就是一个案例,这里同样需要使用广播机制. 下面同样是代码示例,MainActivity.java 和  activity_main. ...

  3. Ubuntu下编译C++ OpenCV程序并运行

            因为想试跑yolov3的缘故,所以装了ubuntu系统,直接通过U盘装的,并不像他们说的“折腾”,反而一切非常顺利,比装软件还简单.然后就是要用C++跑opencv的程序用于比赛,出于 ...

  4. Ecshop首页购物车数量调取问题

    在page_header.lbi中调用SQL: <?php $sql = 'SELECT SUM(goods_number) AS number' . ' FROM ' . $GLOBALS[' ...

  5. Launch Instance---source for openstack

    If you want to create an instance that uses ephemeral storage, meaning the instance data is lost whe ...

  6. C# 使用Epplus导出Excel [5]:样式

    C# 使用Epplus导出Excel [1]:导出固定列数据 C# 使用Epplus导出Excel [2]:导出动态列数据 C# 使用Epplus导出Excel [3]:合并列连续相同数据 C# 使用 ...

  7. 【概率dp 高斯消元】bzoj3270: 博物馆

    一类成环概率dp的操作模式 Description 有一天Petya和他的朋友Vasya在进行他们众多旅行中的一次旅行,他们决定去参观一座城堡博物馆.这座博物馆有着特别的样式.它包含由m条走廊连接的n ...

  8. Python + Bottle + 谷歌搜索Api 实现简单搜索引擎

    1.运行环境 python3 centos7 2.Bottle的使用 使用bottle主要是因为它仅用python自带的库即可实现对web的搭建. bottle源码分析 bottle使用教程 3.代码 ...

  9. 教程笔记《JavaScript深入浅出》

    一.数据类型 javascript是弱数据类型语言,不需要显式的定义类型,一共有如下六种数据类型 五种基本类型:number,string,boolean,null,undefined 一种复合类型: ...

  10. Python入门基础--字符编码与文件处理

    字符编码 文本编辑器存取文件的原理 #1.打开编辑器就打开了启动了一个进程,是在内存中的,所以,用编辑器编写的内容也都是存放与内存中的,断电后数据丢失 #2.要想永久保存,需要点击保存按钮:编辑器把内 ...