1.spring-mvc数据绑定与表单标签库
1. WEB-INF下页面跳转
容器启动后,如何默认显示web-inf目录下的系统首页。
2. @ModelAttribute来注解非请求处理方法
用途:预加载数据,会在每个RequestMapping方法执行之前调用。 特点:无需返回视图,返回类型void (就是只要你请求了中央控制器此方法就会运行一次) 示例:
@ModelAttribute的其他用法: 1)方法参数中的@ModelAttribute, 示例:
public String startCuration(@ModelAttribute("sourcingTaskVo") SourcingTaskVo sourcingTaskVo){
.....
}
使用@ModelAttribute指定pojo回显到页面在request中的key, 即:按照上面的示例代码,可以在页面上通过“sourcingTaskVo”来获取sourcingTaskVo对象。同时,页面上以form表单或url方式传达的参数会以名称对应的方式设置的sourcingTaskVo对象中。
2)方法上的@ModelAttribute,示例:
@ModelAttribute(value = "curationQriteriaVo")
public CurationQriteriaVo initPage(){
CurationQriteriaVo curationQriteriaVo = new CurationQriteriaVo();
curationQriteriaVo.setQriteriaVos(sourcingStartService.getCurationQriteriaData());
return curationQriteriaVo;
}
该方法在当前Controller中的每个请求处理方法前调用一次,且返回值会被放入以curationQriteriaVo为key的对象中,在页面上可以通过curationQriteriaVo获取到存储的对象。
3. 表单标签
导入spring给我们提供的form标签
<%@ taglib prefix="fm" uri="http://www.springframework.org/tags/form" %>
Spring表单标签 Spring提供的轻量级标签库 可在JSP页面中渲染HTML元素的标签 用法 必须在JSP页面的开头处声明taglib指令
引入标签声明之后就可使用Spring表单标签
Spring常用表单标签
fm:form/ | 渲染表单元素 |
---|---|
fm:input/ | 输入框组件标签 |
fm:password/ | 密码框组件标签 |
fm:hidden/ | 隐藏框组件标签 |
fm:textarea/ | 多行输入框组件标签 |
fm:radiobutton/ | 单选框组件标签 |
fm:checkbox/ | 复选框组件标签 |
fm:select/ | 下拉列表组件标签 |
fm:error/ | 显示表单数据校验所对应的错误信息 |
fm:input/标签
属性描述
path | 属性路径,表示表单对象属性,如userName、userCode等 |
---|---|
cssClass | 表单组件对应的CSS样式类名 |
cssErrorClass | 当提交表单后报错(服务端错误),采用的CSS样式类 |
cssStyle | 表单组件对应的CSS样式 |
htmlEscape | 绑定的表单属性值是否要对HTML特殊字符进行转换,默认为true |
注意: 使用表单时增加或 时 需要保存一个空对象转发到此界面
<!-- action 提交地址 ,method 提交方式 , modelAttribute 需要显示的默认值 如果时空必须传入空对象否则报错 -->
<body>
<fm:form action="endtBook" method="post" modelAttribute="books">
<fm:errors path="userCode"></fm:errors> <br/>
用户编码:<fm:input path="userCode"/> <br/>
<fm:errors path="userName"></fm:errors> <br/>
用户名称:<fm:input path="userName"/> <br/>
<fm:errors path="userPassword"></fm:errors> <br/>
用户密码:<fm:password path="userPassword"/><br/>
用户生日:<fm:input path="birthday" Class="Wdate" readonly="readonly" οnclick="WdatePicker();" class="Wdate"/> <br/>
用户地址:<fm:input path="address"/> <br/>
联系电话:<fm:input path="phone"/><br/>
用户角色:
<fm:radiobutton path="userRole" value="1"/>系统管理员
<fm:radiobutton path="userRole" value="2"/>经理
<fm:radiobutton path="userRole" value="3"/>普通用户
<br/>
<input type="submit" value="保存"/>
</fm:form>
</body>
2.spring配置国际化中英文切换
1.1 介绍
国际化(internationalization), 简称国际化。一个产品支持国际化是指产品在无需做大的改变就能够适应不同的语言和地区的能力。i18n是指是一种让软件在开发阶段就支持多种语言的技术。
1.2 java.util.Locale
该类对象表示了特定的地理,政治和文化地区。重要成员:一个语言代号(ISO 639标准定义),一个国家或者区域的可选项(ISO 3169标准定义)。示例:zh_CN, zh为语言代号, CN为国家代号。在操作 Date, Calendar等表示日期/时间的对象时,经常会用到;因为不同的区域,时间表示方式都不同。
1.3 ResourceBundle
该类的作用是读取资源文件,解决国际化问题。在定义资源文件时请注意资源文件的命名规则: xxx语言代码国家代码.properties,如:i18n_zh_CN.properties。
1)简单消息 首先在国际化资源文件中加入配置: 中文: name=露丝 英文: name=rose 在使用国际化配置文件时使用key来获取值,示例如下:
2)复合消息 中文: message=你好{0},我是{1} 英文: message=hello {0}, I am {1} 注意:{}是英文字符 使用示例:
输出结果:
1.4 spring项目中的国际化
1)提供中英两种资源文件 i18n_en_US.properties i18n_zh_CN.properties
2)配置国际化资源文件(在spring配置文件中添加,例如(最好放在spring核心文件)spring-mvc.xml)
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>i18n</value>
</list>
</property>
<!-- 不要忘了加上字符编码方式 -->
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
注: bean 的id必须为messageSource,属性名称必须为basenames 可在开发阶段使用ReloadableResourceBundleMessageSource它能自动重新加载资源文件
3)配置语言区域解析器
<!--指定语言区域解析器,由它来确定使用哪个语言--><bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean>
注:解析器类型
AcceptHeaderLocaleResolver(基于操作系统) Spring采用的默认区域解析器AcceptHeaderLocaleResolver。它通过检验HTTP请求的accept-language头部来解析区域。这个头部是由用户的web浏览器根据底层操作系统的区域设置进行设定。请注意,这个区域解析器无法改变用户的区域,因为它无法修改用户操作系统的区域设置。
SessionLocaleResolver(基于会话) 它通过检验用户会话中预置的属性来解析区域。如果该会话属性不存在,它会根据accept-language HTTP头部确定默认区域
CookieLocaleResolver(基于Cookie) defaultLocale:默认的语言区域 cookieName:设置cookieName名称 cookieMaxAge:设置cookieName有效时间,单位秒 cookiePath:设置cookie可见的地址,默认是“/”即对网站所有地址都是可见的,如果设为其它地址,则只有该地址或其后的地址才可见
4)配置国际化操作拦截器 配置只spring-mvc
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
</mvc:interceptors>
5)页面通过标签输出内容导入t标签
<%@ taglib prefix="t" uri="http://www.springframework.org/tags" %>
<!--使用t标签输出内容,title为国际化资源文件中定义的key-->
<t:message code="title"/>
1)国际化资源文件
在中文资源文件中增加定义如下:i18n_zh_CN.properties
language=英语
如果当前显示的是中文,则点击切换到的应该是英文
在英文资源文件中增加配置如下:i18n_en_US.properties
language=chinese
如果当前显示的是英文,在点击切换到中文。
2)编写一个controller执行切换
package com.zking.mybatis01.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import javax.servlet.http.HttpSession;
import java.util.Locale;
@Controller
public class I18nController {
@RequestMapping("/")
public String index() {
return "index";
}
@RequestMapping("/index")
public String toindex() {
return "index";
}
@RequestMapping("change")
public String change(HttpSession session) {
Locale attribute =(Locale) session.getAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME);
if(Locale.CHINA.equals(attribute) || attribute ==null){
session.setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,Locale.US);
}else{
session.setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,Locale.CHINA);
}
return "redirect: index";
}
}
修改前端界面
<%--
Created by IntelliJ IDEA.
User: lkf
Date: 2022/8/29
Time: 12:56
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="t" uri="http://www.springframework.org/tags" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="change"><t:message code="language"/> </a>
<t:message code="message" />
<a href="logout" >退出</a>
</body>
</html>
注:
切换语言会页面时必须经过spring的中央控制器 不可直接跳转页面不然spring 没有机会给页面切换语言 拦截器会失效
3.文件上传与下载的实现
1.1 导入依赖的架包
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
1.2配置文件上传解析器 到spring核心xml文件中
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 -->
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 文件最大大小(字节) 1024*1024*50=50M-->
<property name="maxUploadSize" value="52428800"></property>
<!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常-->
<property name="resolveLazily" value="true"/>
</bean>
1.3编写控制器
@RequestMapping("/upload")
public String upload(MultipartFile img, HttpServletRequest req, Book bo) throws IOException {
String fname = img.getOriginalFilename();//文件名
//File.separatorChar 根据系统 来获取 是那个斜杠
String toPath = path + File.separatorChar + img.getOriginalFilename();
String realPath = req.getServletContext().getRealPath(toPath);
// realPath 保存位置 请进行更换
File file=new File(realPath);
img.transferTo(file);
return "redirect:bookList";
}
上传提交页面
<%--
Created by IntelliJ IDEA.
User: lkf
Date: 2022/9/1
Time: 19:09
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="<%=request.getContextPath()%>/upload" enctype="multipart/form-data" method="post">
<input type="hidden" name="bid" value="${bid}">
<input type="file" name="img">
<input type="submit" value="上传"/>
</form>
</body>
</html>
2.下载的实现
//点击下载 通过浏览器配置下载位置 下载到指定位置 执行完成后直接跳回原本页面
@RequestMapping("/download")
public ResponseEntity <byte[]> download(String fileid,HttpServletRequest req) throws IOException {
//1.通过传入的fileId,获取到上传图片的详细信息
//填入需要下载文件的地址 此方法不需要跳转页面
File file = new File(fileId);
//2.设置响应头,将获取的文件写入响应流(需求将设置好的响应头传入)
HttpHeaders httpHeaders = new HttpHeaders();
//名称可能是中文 所以需要转换一下
String fname = new String(bookFile.getRealName().getBytes("utf-8"), StandardCharsets.ISO_8859_1);
//附件名称
httpHeaders.setContentDispositionFormData("attachment", fname);
//告诉组件 是一个二进制字符流
httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtil.readAsByteArray(file), httpHeaders, HttpStatus.OK);
}