springMVC功能
目录
说明
- 上传(mvc自带的接口MultipartFile);
- 校验(hibernate 校验,三个包),jboss-logging-3.1.4.GA.jar、hibernate-validator
5.1.0.Final.jar、validation-api-1.0.0.GA.jar,一个资源文件; - JSTL标签,jstl.jar,还要在页面开启;
- 国际化;
- 注解,转发,重定向,下载;
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">
<display-name>springMVC</display-name>
<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:springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
注解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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--开启注解映射器和适配器-->
<mvc:annotation-driven></mvc:annotation-driven>
<!--注解Handler,指定扫描的包全称 -->
<context:component-scan base-package="com"></context:component-scan>
<!--配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 返回视图页面的前缀 -->
<property name="prefix" value="/WEB-INF/view/"></property>
<!-- 返回页面的后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 国际化 -->
<bean name="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value><!-- 文件路径 --></value>
<value><!-- 文件路径 --></value>
<value><!-- 文件路径 --></value>
</list>
</property>
</bean>
<bean name="messageSource" class="org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver">
</bean>
<!-- 上传文件 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 最大值 -->
<property name="maxUploadSize" value="20000000"/>
</bean>
</beans>
配置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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 配置Handler ,访问路径:/login.do -->
<bean name="/login.do" class="com.myHandler">
</bean>
<!--配置视图解析器 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 返回视图页面的前缀 -->
<property name="prefix" value="/WEB-INF/view/"></property>
<!-- 返回页面的后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
springmvc控制器Handler
代码片
.
package com;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.websocket.server.PathParam;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
//使用@Controller注解一个Handler类,接收请求,类似struts 2 的action类
@Controller
public class myHandler {
//在运行请求之前会先执行,@ModelAttribute,
//带参数,框架自动将实例添加到model中
@ModelAttribute
public User init(
@PathParam(value = "name") String name,
@PathParam(value = "pass") String pass){
User user=new User();
user.setName(name);
user.setPass(pass);
return user;
}
//不带参数,要有Model model参数,要显示的添加实例到model中
@ModelAttribute
public void init(Model model,
@PathParam(value = "name") String name,
@PathParam(value = "pass") String pass){
User user=new User();
user.setName(name);
user.setPass(pass);
model.addAttribute(user);
}
//@RequestMapping注解一个页面访问URL
@RequestMapping("/login.do")
//@Valid开启校验
public ModelAndView hello(@Valid User user){
System.out.println(user.getName()+"/"+user.getPass());
ModelAndView modelView = new ModelAndView();//视图对象
//模拟数据库操作,类似于 request.setAttribute()
if(user.getName().equals("123")&&user.getPass().equals("123")){
//添加属性,在视图中可以用EL访问
modelView.addObject("name",user.getName());
//配置返回的视图名,由于我们在springmvc.xml中配置了前缀和后缀,这里直接写视图名就好
modelView.setViewName("index");
//modelView.setViewName("/WEB-INF/view/index.jsp");
}else{
modelView.setViewName("../../hello");
}
//返回视图
return modelView;
}
//@RequestMapping注解一个页面访问URL:rexx.do/1?name=xiaoming
@RequestMapping("/rexx.do/{id}")
public String rexx(
Model model, //返回页面的对象
User user, //表单实例化的对象
RedirectAttributes redirectAttributes, //转发
@PathVariable long id, //提交页面序号,显示写在在请求url中
@PathParam(value = "name") String s){//将页面属性值name赋值给s变量
System.out.println(user.getName()+"/"+user.getPass());
//模拟数据库操作,类似于 request.setAttribute()
if(user.getName().equals("123")&&user.getPass().equals("123")){
model.addAttribute("name",user.getName());
//设置flash参数
redirectAttributes.addFlashAttribute("name",user.getName());
//带上redirect或者forward就不会走视图解析器,到控制器
return "redirect:/login.do";//重定向
return "forward:/login.do";//转发
}else{
}
//走视图解析器
return "../../hello";
}
//上传文件
@RequestMapping("/Upload.do")
public String Upload(HttpServletRequest request,Image image) {//内置了servlet对象
//MultipartFile是springmvc的上传文件类型
List<MultipartFile> images = image.getImage();
if(images!=null&&images.size()!=0){
// 遍历表单输入项对象集合
for (MultipartFile image1 : images) {
//获得文件名
String name = image1.getOriginalFilename();
//创建路径
File namefile = new File(
request.getServletContext().getRealPath("image"),name);
try {
//保存文件
image1.transferTo(namefile);
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
}
}
}
return "view";
}
/*
*采用spring提供的上传文件的方法
*/
@RequestMapping("springUpload")
public String springUpload(HttpServletRequest request) throws IllegalStateException, IOException
{
long startTime=System.currentTimeMillis();
//将当前上下文初始化给 CommonsMutipartResolver (多部分解析器)
CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
request.getSession().getServletContext());
//检查form中是否有enctype="multipart/form-data"
if(multipartResolver.isMultipart(request))
{
//将request变成多部分request
MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
//获取multiRequest 中所有的文件名
Iterator iter=multiRequest.getFileNames();
while(iter.hasNext())
{
//一次遍历所有文件
MultipartFile file=multiRequest.getFile(iter.next().toString());
if(file!=null)
{
String path="E:/springUpload"+file.getOriginalFilename();
//上传
file.transferTo(new File(path));
}
}
}
long endTime=System.currentTimeMillis();
System.out.println("方法三的运行时间:"+String.valueOf(endTime-startTime)+"ms");
return "/success";
}
}
校验实体类User
代码片
.
package com;
import javax.validation.constraints.AssertFalse;
import javax.validation.constraints.AssertTrue;
import javax.validation.constraints.DecimalMax;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.Digits;
import javax.validation.constraints.Future;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Null;
import javax.validation.constraints.Past;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
public class User {
//校验
@Pattern(regexp="\\d{3}")//属性值要符合正则表达式
@Size(min=2,max=10)//最大最小长度
@NotNull//不能为空
@Null//必须为空
@Max(100)//整数,值的最大值
@Min(10)//整整,值的最小值
@DecimalMax("10.5")//BigDecimal类型,值最大值
@DecimalMin("0.5")//BigDecimal类型,值最小值
@Digits(integer=5,fraction=2)//BigDecimal类型,最大整数部分5,最大小数部分5
@AssertFalse//boolean类型,值为false
@AssertTrue//boolean类型,值为true
@Future//未来的时间
@Past//过去的时间
//还要在控制器中的实体对象参数前加上@Valid
//要写messages.properties文件,为每一个验证返回一个错误消息
private String name;
private String pass;
public User(){
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
}
上传文件实体类
代码片
.
package com;
import java.util.List;
import org.springframework.web.multipart.MultipartFile;
public class Image {
List<MultipartFile> images;
public List<MultipartFile> getImage() {
return images;
}
public void setImage(List<MultipartFile> images) {
this.images = images;
}
}
页面使用JSTL标签库c
代码片
.
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<!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>jstl标签</title>
</head>
<body>
<!-- if -->
<c:if test="${true}">
这是真
</c:if>
<!-- switch-case -->
<c:choose>
<c:when test="${user.name='张三'}">
这是张三
<!-- 开启国际化,引用资源文件值 -->
<spring:message code="key名"/>
</c:when>
<c:when test="${user.name='李四'}">
这是李四
</c:when>
</c:choose>
<!-- 遍历 for 集合 -->
<c:forEach items="users" var="u">
${u.name} ${u.pass}
</c:forEach>
<!-- 遍历 for 范围1到10 -->
<c:forEach var="x" begin="1" end="10">
<c:out value="${x}"></c:out>
</c:forEach>
<!-- 遍历 for 字符串,以逗号为分隔符 -->
<c:forTokens var="item" items="sss,ddd,ccc,ddd" delims=",">
${item}
</c:forTokens>
<!-- 格式化行为 -->
<!-- 函数 -->
</body>
</html>
总结
1. 上传使用springmvc自带接口,操作简单
2. 标准化就是可以方便的引用外部资源文件的key值
**引用包是最大的困难(一步一步来)**