一、SpringMVC
特点:
天生支持注解(web 3.0 标准),配置更灵活
轻量级的mvc框架(jar包小,包少)
完全支持rest 风格(资源等价于服务。不含资源的后置名。仅有网站的路径,采用网站的多级路径携带参数信息
传统风格:
a/b/1.html
a/b/add.action?a=123&b=456
rest
风格:(狭义)
a/b/123/456/add.action
支持模型和视图统一打包ModelAndView
模型数据传输用
request.setAttribute(“user”,user);
视图地址传输用
request.getRequestDisparcher(“main.jsp”).forward(request,response);
将视图和模型打包成
ModelAndView
。默认绑定到
request
作用域
注意:
springMVC
的跳转默认采用转发
功能强大(mvc+拦截器+标签+国际化+校验器)struts有的功能springmvc都有
控制器(既是单例,也是pojo),本质是对servlet的改造。
和
struts2
一样,采用“
前置控制器
+
业务控制器
”的方式。
Struts2
是
filter+action
。
Springmvc
是
Servlet+ controller
。
原理:
(
1
)客户端发出一个
http
请求给
web
服务器,
web
服务器对
http
请求进行解析,如果匹配
DispatcherServlet
的请求映射路径(在
web.xml
中指定),
web
容器(如
tomcat
)将请求转交给
DispatcherServlet.
(
2
)
DispatcherServlet
接收到这个请求之后将根据请求的信息(包括
URL
、
Http
方法、请求报文头和请求参数
Cookie
等)以及
HandlerMapping
的配置找到处理请求的处理器(
Handler
)。
(
3-4
)
DispatcherServlet
根据
HandlerMapping
(就相当于一个目录,每个
@Controller
标记过的类都会在这里做登记)找到对应的
Handler,
将处理权交给
Handler
(
Handler
将具体的处理进行封装),再由具体的
HandlerAdapter
对
Handler
进行具体的调用。
(
5
)
Handler
对数据处理完成以后将返回一个
ModelAndView()
对象给
DispatcherServlet
。
(
6
)
Handler
返回的
ModelAndView
只是一个逻辑视图并不是一个正式的视图,
DispatcherSevlet
通过
ViewResolver
将逻辑视图转化为真正的视图
View
。
(
7
)
Dispatcher
通过
model
解析出
ModelAndView()
中的参数最终展现出完整的
view
并返回给客户端。
二、开发步骤
1、添加能力,自动导入springmvc+spring的库 :spring3.0 web Libraries + spring Web jar包 或者手动导入jar包
F:\JAVA\第三阶段\04SpringMVC\练习\个人任务书\课堂代码\springmvc_1_hello\WebRoot\WEB-INF\lib
2、在web.xml中配置spring 和springmvc 的 和 (前置控制器)
//web.xml
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
springmvc
org.springframework.web.servlet.DispatcherServlet
springmvc
*.html
index.jsp
3、在webRoot下的WEB-INF中添加springmvc-servlet.xml(配置后置控制器及对应的视图关系)
//springmvc-servlet.xml
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
application/json;charset=UTF-8
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
4、编写controller.java文件,使用注解配置请求映射关系。
三、SpringMVC传参
1、ModelAndView,返回模型和视图的打包
//通过modelandview返回模型和视图的打包
@RequestMapping("/showdata")
public ModelAndView showdata(){
Map data = new HashMap();
data.put("str", " i am bai"); //存储字符串
data.put("stu", new Student(1,"白")); //存储字符串
ModelAndView ma = new ModelAndView("showdata", data);
//返回"showdata"页面
return ma;
}
//林工写的
@RequestMapping("/sum")
public ModelAndView sum(int a, int b) {
int c = a + b;
ModelAndView mav = new ModelAndView();
mav.setViewName("result");
//返回"result"页面
mav.addObject("c1", c);
return mav;
}
2、获取请求参数+restful风格
//传递对象的形式
@RequestMapping("/input_stu")
public String showinput_stu(@ModelAttribute("stu") Student stu){
return "show_stu";
}
//使用restful风格传递参数
@RequestMapping(value="/{sid}/{sname}/input_stu_path")
public ModelAndView inputpath_stu(
@PathVariable int sid,
@PathVariable String sname){
Map data = new HashMap();
data.put("stu", new Student(sid,sname));
return new ModelAndView("show_stu",data);
}
//获取request和session等web对象的方式
@RequestMapping("/getRquest")
public String getRequet(HttpServletRequest request,HttpSession session){
request.setAttribute("req", "requestValue");
session.setAttribute("ses", "sessionValue");
session.getServletContext().setAttribute("app", "applicationValue");
return "show_request";
}
//兼容servlet写法
@RequestMapping(value="/*" ,method=RequestMethod.GET)
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException,ServletException{
response.setContentType("text/html; charset=utf-8");
request.setAttribute("req", "requestValue");
request.getRequestDispatcher("WEB-INF/jsp/show_request.jsp").forward(request, response);
}
//重定向
@RequestMapping("/redirectTo")
public String redirect(){
//return "redirect:/index.jsp";
return "redirect:/getRquest.html";
}
//转发到另一个方法 chain
@RequestMapping("/chainTo")
public String chain(){
return "forward:/getRquest.html";
}
//林工写的接收一般表单参数
@RequestMapping("/reg.do")
public String reg(int age, boolean bool, Cat cat, HttpSession session,
HttpServletRequest request, HttpServletResponse response)
throws IOException {
System.out.println(age);
System.out.println(bool);
System.out.println(cat.getName());
System.out.println(cat.getPet().getName());
System.out.println(cat.getHobby().get(0).getClass());
System.out.println(cat.getMap());
System.out.println(session);
System.out.println(request);
response.getWriter().print("aaaaaaaaaaaaaaaaaa");
response.getWriter().flush();
return "success";
}
//使用restful风格传递参数
@RequestMapping("/rest/id/{id}/name/{name}")
public String doit(@PathVariable int id, @PathVariable String name) {
System.out.println(id);
System.out.println(name);
return "success";
}
@RequestMapping(value = "/get", method = RequestMethod.GET)
public String get() {
System.out.println("get");
return "success";
}
@RequestMapping(value = "/post", method = RequestMethod.POST)
public String post() {
System.out.println("post");
return "success";
}
3、SpringMVC校验
注意1、要引入几个jar包 路径:F:\JAVA\第三阶段\03spring\练习\个人任务书\课程代码\09-springmvc-validation\WebRoot\WEB-INF\lib
2、在Springmvc-servlet.xml中要开启 注解
3、前端引入标签来获取
后端代码
//controller中的方法
package com.etc.controller;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import com.etc.vo.User;
@Controller
public class RegController {
@RequestMapping("/reg.do")
public String reg(@Valid User user,
BindingResult result ) {
System.out.println(result.getErrorCount());
if (result.hasErrors()) {
return "fail";
} else {
return "success";
}
}
}
//User的代码
package com.etc.vo;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
public class User {
@Size(min=3 , max=6, message="用户名只能大于{min}小于{max}")
//限制输入名字要大于3小于6
@Pattern(regexp="^[a-zA-Z0-9]+$")
//也可以用正则来加校验
private String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
//校验页面代码
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
My JSP 'index.jsp' starting page
ffd
username:
//错误页面代码
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%@ taglib prefix="s" uri="http://www.springframework.org/tags/form" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
My JSP 'index.jsp' starting page
Struts 校验, validation.xml ,自动完成前端数据的校验
jsr303 , java 的规范,
空检查
@Null 验证对象是否为null
@NotNull 验证对象是否不为null, 无法查检长度为0的字符串
@NotBlank 检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.
@NotEmpty 检查约束元素是否为NULL或者是EMPTY.
Booelan检查
@AssertTrue 验证 Boolean 对象是否为 true
@AssertFalse 验证 Boolean 对象是否为 false
长度检查
@Size(min=, max=) 验证对象(Array,Collection,Map,String)长度是否在给定的范围之内
@Length(min=, max=) Validates that the annotated string is between min and max included.
日期检查
@Past 验证 Date 和 Calendar 对象是否在当前时间之前
@Future 验证 Date 和 Calendar 对象是否在当前时间之后
@Pattern 验证 String 对象是否符合正则表达式的规则
数值检查,建议使用在Stirng,Integer类型,不建议使用在int类型上,因为表单值为“”时无法转换为int,但可以转换为Stirng为"",Integer为null
@Min 验证 Number 和 String 对象是否大等于指定的值
@Max 验证 Number 和 String 对象是否小等于指定的值
@DecimalMax 被标注的值必须不大于约束中指定的最大值. 这个约束的参数是一个通过BigDecimal定义的最大值的字符串表示.小数存在精度
@DecimalMin 被标注的值必须不小于约束中指定的最小值. 这个约束的参数是一个通过BigDecimal定义的最小值的字符串表示.小数存在精度
@Digits 验证 Number 和 String 的构成是否合法
@Digits(integer=,fraction=) 验证字符串是否是符合指定格式的数字,interger指定整数精度,fraction指定小数精度。
@Range(min=, max=) 检查数字是否介于min和max之间.
@Range(min=10000,max=50000,message="range.bean.wage") private BigDecimal wage;
@Valid 递归的对关联对象进行校验, 如果关联对象是个集合或者数组,那么对其中的元素进行递归校验,如果是一个map,则对其中的值部分进行校验.(是否进行递归验证)
@CreditCardNumber信用卡验证
@Email 验证是否是邮件地址,如果为null,不进行验证,算通过验证。
@ScriptAssert(lang= ,script=, alias=)
@URL(protocol=,host=, port=,regexp=, flags=)
4、SpringMVC上传
上传只能用"post"方式
要在springmvc-servlet.xml中配置
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
My JSP 'index.jsp' starting page
package com.etc.controller;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.IOUtils;
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;
@Controller
public class UploadController {
@RequestMapping("/upload.do")
public String upload(@RequestParam MultipartFile file,
HttpServletRequest request) throws IOException {
System.out.println(file);
//获取上传文件信息
String name = file.getName();
String contentType = file.getContentType();
long size = file.getSize();
String oname = file.getOriginalFilename();
System.out.println(name + "," + contenType + "," + size + ","
+ new String(oname.getBytes("ISO-8859-1"), "UTF-8"));
//转码问题
// 文件名 用时间磋,做为文件名
long time = System.currentTimeMillis();
//获取时间戳
// el-api.jar a.b.jar
// charAt subString
String ext = oname.substring(oname.lastIndexOf("."));
//截取文件类型
String newname = time + ext;//拼串名字
// 如果目录不存在要自动创建
String dir = "f:/upload";
//定义一个文件路径
String path = request.getRealPath("/upload/");
System.out.println(path);
dir = path;
new File(dir).mkdirs();
InputStream input = file.getInputStream();// 原始
FileOutputStream output = new FileOutputStream(dir + "/" + newname);
//获取文件流和定义输出流
IOUtils.copy(input, output);
output.close();
//关闭输出流
return "success";
}
}
放在服务器upload文件下的好处:1、上传完立马就可以下载,不用专门写下载工具 2、可以通过浏览器直接访问,访问该路径就是直接下载路径。 注意 web.xml中过滤器的设置
上传多个文件的话,上传的是文件的数组,后台要用数组的方式接收,页面代码和controller代码如下
//controller代码
@RequestMapping("/upload2.do")
public String upload2(@RequestParam MultipartFile[] files,
HttpServletRequest request) throws IOException {
for (MultipartFile file : files) {
System.out.println(file);
String name = file.getName();
String contentType = file.getContentType();
long size = file.getSize();
String oname = file.getOriginalFilename();
System.out.println(name + "," + contentType + "," + size + ","
+ oname);
// 文件名 用时间磋,做为文件名
long time = System.currentTimeMillis();//
// el-api.jar a.b.jar
// charAt subString
String ext = oname.substring(oname.lastIndexOf("."));
System.out.println(ext);
String newname = time + ext;
// 如果目录不存在要自动创建
String dir = "f:/upload";
String path = request.getRealPath("/upload/");
System.out.println(path);
dir = path;
new File(dir).mkdirs();
InputStream input = file.getInputStream();// 原始
FileOutputStream output = new FileOutputStream(dir + "/" + newname);
IOUtils.copy(input, output);
output.close();
}
return "success";
}
//页面代码
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
My JSP 'index.jsp' starting page
5、SpringMVC下载
package com.etc.controller;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class DownloadController {
@RequestMapping("/download.do")
public String download(String filename, HttpServletResponse response)
throws IOException {
response.addHeader("Content-Disposition", "attachment;filename="
+ filename);
String dir = "f:/upload/";
InputStream in = new FileInputStream(dir + filename);
IOUtils.copy(in, response.getOutputStream());
return null;
}
}
<%@page import="java.io.File"%>
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
My JSP 'index.jsp' starting page
<%
File dir = new File("f:/upload");
String [] fs = dir.list();
for(String f:fs){
out.print("
");
}
%>
5、SpringMVC JSON(java script object notation)
1、JOSN是一种数据格式,用来存储数据,和xml功能相似。
注意:1
2添加两个jar包:F:\JAVA\第三阶段\03spring\练习\个人任务书\课程代码\11-springmvc-json\WebRoot\WEB-INF\lib
3、可能有重复的jar包要删除
4、springmvc-servlet.xml中要配置添加对json的支持,代码如下
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
application/json;charset=UTF-8
Controller代码:
package com.etc.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.etc.vo.User;
@org.springframework.stereotype.Controller
public class JsonController {
@RequestMapping("/showJson")
@ResponseBody
public List showJson() {
// ArrayList list = new ArrayList();
// list.add("a");
// list.add("b");
// list.add("c");
// User user = new User();
// user.setUsername("lin");
// user.setPassword("admin");
ArrayList list = new ArrayList();
for (int i = 0; i < 10; i++) {
User user = new User();
user.setUsername("lin" + i);
user.setPassword("pass" + i);
list.add(user);
}
return list;
// springmvc内部 list ->json
}
@RequestMapping("/getJson")
// json -> User
public String getJson(@RequestBody User user) {
System.out.println(user.getUsername() + "," + user.getPassword());
return "success";
}
@RequestMapping("/re")
public String re() {
return "redirect:/showJson";
}
@RequestMapping("/fo")
public String fo(){
return "forward:/showJson";
}
}
页面代码
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
My JSP 'index.jsp' starting page
ajax
getJson页面
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
My JSP 'index.jsp' starting page
ajax