(拦截器相关知识)
实验1按照教材15.3小节的内容和案例的实现步骤,完成用户权限登录验证应用案例代码的编写。
(文件上传和下载相关知识)
实验2按照教材16.1.2小节的内容和案例的实现步骤,完成文件上传应用案例代码的编写。
实验3按照教材16.2.1小节的内容和案例的实现步骤,完成文件下载应用案例代码的编写。

实验4 编写客户注册页面信息(客户名称、客户单位、客户职位、客户生日、客户性别、客户联系方式、客户头像)cutomerEdit.jsp,提交客户信息到CustomerController的edit()方法,然后跳转到showCustomer.jsp页面,显示客户的名称及头像。

实验1:

实验2:

实验步骤:

javaee实验总结与心得 javaee实训案例_java


项目结构图:

javaee实验总结与心得 javaee实训案例_spring_02

实验代码:
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
      
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
           <param-name>contextConfigLocation</param-name>
           <param-value>classpath:springMvc-config.xml</param-value>
        </init-param>
        
        <load-on-startup>1</load-on-startup>
        
    </servlet>
    
    <servlet-mapping>
      <servlet-name>dispatcherServlet</servlet-name>
      <url-pattern>/</url-pattern>
    </servlet-mapping>   
 
</web-app>

springMvc-config.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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    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.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
        
        
        <context:component-scan base-package="com.cqust.controller"></context:component-scan>
        
        <mvc:annotation-driven/>   
         
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        	<property name="prefix" value="/WEB-INF/jsp/"></property>
      		<property name="suffix" value=".jsp"></property>  
        </bean>
        
        <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        	<property name="defaultEncoding" value="UTF-8"></property>
        </bean>
         
        
            
        
</beans>

FileUploadController.java

package com.cqust.controller;

import java.util.List;
import java.io.File;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;

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 FileUploadController {
/*
 * 执行文件上传
 * */
	@RequestMapping("/fileUpload")
	public String handleFormUpload (@RequestParam("name") String name,
			@RequestParam("uploadfile") List<MultipartFile> uploadfile,
			HttpServletRequest request ){
		//判断上传文件是否为空
		if(!uploadfile.isEmpty()&&uploadfile.size()>0) {
			//循环输出上传的文件
			for(MultipartFile file:uploadfile) {
				//获取上传文件的原始名称
				String originalFilename=file.getOriginalFilename();
				//设置上传文件的保存地址目录
				String dirPath=request.getServletContext().getRealPath("/upload/");
				File filePath=new File(dirPath);
				//如果文件夹不存在,就先创建目录
				if(!filePath.exists()) {
					filePath.mkdirs();
				}
				//使用UUID重新命名上传的文件名称
				String newFilename=name+"_"+UUID.randomUUID()+"_"+originalFilename;
				try {
					file.transferTo(new File(dirPath+newFilename));
				} catch (Exception e) {
					e.printStackTrace();
					return "error";
				}
			}
			return "success";
		}
		else {
			return "error";
		}
		
	}
}

Upload.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文件上传</title>

<script>
function check(){
	
	var name=document.getElementById("name").value;
	var file=document.getElementById("file").value;
	if(name==""){
		alert("请输入上传人信息");
		return false;
	}
	if(file.length==0||file==""){
		alert("请选择上传文件");
		return false;
	}
	return true;

}

</script>

</head>
<body>
	<form action="${pageContext.request.contextPath }/fileUpload" method="post" enctype="multipart/form-data" onsubmit="return check()">
		上传人:<input id="name" type="text" name="name"/><br/>
		选择文件:<input id="file" type="file"  name="uploadfile" multiple="multiple" /><br/>
				<input  type="submit" value="上传"/>
	</form>
</body>
</html>

error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
error:文件上传失败
</body>
</html>

success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
ok:文件上传成功!

</body>
</html>

运行效果:

javaee实验总结与心得 javaee实训案例_javaee实验总结与心得_03

文件下载:

javaee实验总结与心得 javaee实训案例_java_04

代码:
DownLoad.jsp

<%@page import="java.net.URLEncoder"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>下载页面</title>
</head>
<body>
<a href="${pageContext.request.contextPath }/download?filename=<%=URLEncoder.encode("壁纸.jpg","UTF-8") %>">
中文名称文件下载
</a>
</body>
</html>

FileUploadController.java

package com.cqust.controller;

import java.util.List;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;


@Controller
public class FileUploadController {
/*
 * 执行文件上传
 * */
	@RequestMapping("/fileUpload")
	public String handleFormUpload (@RequestParam("name") String name,
			@RequestParam("uploadfile") List<MultipartFile> uploadfile,
			HttpServletRequest request ){
		//判断上传文件是否为空
		if(!uploadfile.isEmpty()&&uploadfile.size()>0) {
			//循环输出上传的文件
			for(MultipartFile file:uploadfile) {
				//获取上传文件的原始名称
				String originalFilename=file.getOriginalFilename();
				//设置上传文件的保存地址目录
				String dirPath=request.getServletContext().getRealPath("/upload/");
				File filePath=new File(dirPath);
				//如果文件夹不存在,就先创建目录
				if(!filePath.exists()) {
					filePath.mkdirs();
				}
				//使用UUID重新命名上传的文件名称
				String newFilename=name+"_"+UUID.randomUUID()+"_"+originalFilename;
				try {
					file.transferTo(new File(dirPath+newFilename));
				} catch (Exception e) {
					e.printStackTrace();
					return "error";
				}
			}
			return "success";
		}
		else {
			return "error";
		}
		
	}
	
/**
 * 执行文件下载
 * */
	@RequestMapping("/download")
	public ResponseEntity<byte[]> fileDownload(HttpServletRequest request,String filename)throws Exception{
		//指定要下载的文件所在路径
		String path=request.getServletContext().getRealPath("/upload/");
		//创建该文件对象
		File file=new File(path+File.separator+filename);
		//对文件名编码,防止中文乱码
		filename=this.getFilename(request,filename);
		//设置响应头
		HttpHeaders headers=new HttpHeaders();
		//通知浏览器以下载方式打开文件
		headers.setContentDispositionFormData("attachment", filename);
		//定义以流的形式下载返回文件数据
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		//使用String MVC框架的ResponseEntity 对象封装返回下载数据
		
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers,HttpStatus.OK);
		
	}
	/*
	 * 根据浏览器的不同进行编码设置,返回编码后的文件名*
	 */
	public String getFilename(HttpServletRequest request,String filename) throws Exception {
		//IE不同版本User-Agent中出现的关键词
		String[] IEBrowserKeyWords= {"MSIE","Trident","Edge"};
		//获取请求头代理信息
		String userAgent=request.getHeader("User-Agent");
		for(String keyWord:IEBrowserKeyWords) {
			//IE内核浏览器,统一为UTF-8编码显示
			if(userAgent.contains(keyWord)) {
				return URLEncoder.encode(filename, "UTF-8");
			}
		}
		return new String(filename.getBytes("UTF-8"),"ISO-8859-1");
	}
}

运行效果:

javaee实验总结与心得 javaee实训案例_spring_05