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. pc端常见布局---水平居中布局 单元素不定宽度

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...

  2. 进度条插件使用demo

    1.下载地址: http://down.htmleaf.com/1502/201502031710.zip 2.效果图: 3.HTML代码:其中80设置当前所占百分比,即蓝色部分比例:注意引入必须的j ...

  3. POJ Charm Bracelet 挑饰品 (常规01背包)

    问题:去珠宝店抢饰品,给出饰品种数n,能带走的重量m,以及每种饰品的重量w与价值v.求能带走的最大量. 思路:常规01背包. #include <iostream> using names ...

  4. 从程序猿到SAP产品经理,我是如何转型的?

    文章作者:Jason Xia(夏建军) Jerry: 今天的文章来自Jason Xia, 我的老同事,和我一样从2007年进入SAP成都研究院工作至今.这篇文章讲述了Jason是如何从一名SAP资深开 ...

  5. polygon 画图

    cityscape数据集,我现在想根据json文件中的polygon画出整个road的区域,这是运行的脚本.这个文件必须使用coco的pythonAPI的包,把这个脚本放在pythonAPI文件夹下就 ...

  6. appium---启动app

    自动化测试是测试人员必备的一项技能,所谓的自动化就是通过代码完成了手工的操作,今天就总结下如何通过python启动app 环境条件 1.安装python:下载地址 2.安装JDK:下载地址 3.安装A ...

  7. 【转】VC自定义消息

    MFC一般可利用ClassWizard类向导添加消息和消息处理函数,但用户自定义消息必须手工输入,现将vc自定义消息方法步骤记录如下: (1)定义消息 利用#define语句直接定义用户自己的消息(既 ...

  8. 【思维题】TCO14 Round 2C InverseRMQ

    全网好像就只有劼和manchery写了博客的样子……:正解可能是最大流?但是仔细特判也能过 题目描述 RMQ问题即区间最值问题是一个有趣的问题. 在这个问题中,对于一个长度为 n 的排列,query( ...

  9. mysql 备份 常用脚本

    全备: innobackupex --defaults-file=/data/mysql3316/my3316.cnf --user=root --password=mysqlpass /data/b ...

  10. redis学习笔记(3)

    redis学习笔记第三部分 --redis持久化介绍,事务,主从复制 三,redis的持久化 RDB(Redis DataBase)AOF(Append Only File) RDB:在指定的时间间隔 ...