用springmvc实现文件的上传,并且显示出文档中出现英文单词的次数
**
-
*第一步:先创建一个maven工程。
-
第二步:完成需要的配置
[ ] 1 .配置applition-mvc.xml文件
<!--1.开启MVC注解 -->
<mvc:annotation-driven/>
<!--2.放行静态资源配置 -->
<mvc:default-servlet-handler/>
<!--3.配置视图解析器 内部资源视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/"/>
<property name="suffix" value=".html"/>
</bean>
<!--4.配置文件上传视图解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1048576"/>
<property name="defaultEncoding" value="utf-8"/>
</bean>
</beans>
3. [ ] 2 .配置application.xml文件
<!-- 开启包扫描 --> <context:component-scan base-package="com.jt"></context:component-scan>
- 3. 编辑web.xml文件
<!-- 配置spring mvc前端控制器 --> <servlet> <servlet-name>frontController</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <!-- 通过此参数的配置加载spring配置文件,然后初始化资源 --> <param-name>contextConfigLocation</param-name> <param-value>classpath:application.xml</param-value> </init-param> <!--让tomcat启动则加载此servlet对象,数值越小优先级越高 --> <load-on-startup>1</load-on-startup> </servlet> <!-- 配置Spring MVC前端控制器映射 --> <servlet-mapping> <servlet-name>frontController</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
- [ ] 4.pom文件
<dependencies> <!-- springMvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.9.RELEASE</version> </dependency> <!-- java对象转换json的工具类 --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.5</version> </dependency> <!-- 文件上传组件 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.9.RELEASE</version> </dependency> </dependencies>
3.创建需要的包和类
4.前端的代码
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page trimDirectiveWhitespaces="true" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>文件上传和单词数的显示</title>
</head>
<body>
<form id="file" action="/file" method="POST" enctype="multipart/form-data">
<p >上传文件:<input type="file" name="myfile"/></ p>
<input type="submit" value="上传"/>
<input type="reset" value="取消上传"/ >
</form>
<c:forEach items="${map}" varStatus="status" var="word" >
${word.key}:${word.value}
</c:forEach>
</body>
</html>
5 。控制层的代码
package com.jt.controller;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonObjectFormatVisitor;
import com.jt.service.FileService;
import com.jt.vo.SysResult;
@Controller
@RequestMapping("/")
public class FileController {
@Autowired
private FileService fileService;
@RequestMapping("index")
public String index(){
return "index.html";
}
//文件上传
@RequestMapping("/file")
@ResponseBody
public SysResult fileupload(MultipartFile myfile,ModelMap modelMap){
System.out.println("哈哈哈哈");
try {
String result=fileService.upload(myfile);
if(result=="201"){
return SysResult.build(201,"上传失败");
}else{
Map map = fileService.readwords(result);
modelMap.addAttribute("map",map); //将集合传到前端
}
} catch (Exception e) {
e.printStackTrace();
}
return SysResult.build(201,"上传失败");
}
}
6 业务层代码
package com.jt.service;
import java.util.Map;
import org.springframework.web.multipart.MultipartFile;
public interface FileService {
String upload(MultipartFile myfile);
Map readwords(String result);
}
7业务层的实现代码
package com.jt.service;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
@Service
public class FileServiceImpl implements FileService{
@Override
public String upload(MultipartFile myfile) {
//1.获取文件名称
String fileName = myfile.getOriginalFilename();
//将字符全部小写
fileName = fileName.toLowerCase();
String localPath = "D:/jt-upload/";
//实现分文件存储
try {
String dateDir = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
// D:/jt-upload/2019/01/29
String localPathDir = localPath +dateDir;
//判断文件加是否存在
File fileDir = new File(localPath);
if(!fileDir.exists()){
//创建文件夹
fileDir.mkdirs();
}
//实现文件夹上传
myfile.transferTo(new File(localPathDir));
String filePath = localPathDir+fileName;
return "filePath";
} catch (Exception e) {
e.printStackTrace();
}
return "201";
}
@Override
public Map readwords(String result) {
File file = new File(result);
try {
//定义一个流对象
BufferedReader read = new BufferedReader(new FileReader(file));
String line = null;
//定义map来保存单词和单词出现的次数
Map<String,Integer> map = new HashMap<>();
//读取文件
try {
while((line=read.readLine())!=null){ //判断文件是否为空
line.toLowerCase();
String reg1 = "\\s+";
String reg2 = "\\w+";
//将读取的文本进行分割
String [] str = line.split(reg1);
//遍历数组
for(String s:str){
//判断集合中是否有该单词,
if(s.matches(reg2)){
if(!map.containsKey(str)){ //将没有出现过的单词添加到集合中
map.put(s, 1);
}else {
map.put(s, map.get(s)+1); //该单词出现过,就在原数量上加1
}
}
}
return map;
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
8 .SysResult代码 ,工具类
package com.jt.vo;
import java.io.Serializable;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
@JsonIgnoreProperties(ignoreUnknown=true)
public class SysResult implements Serializable{
private static final long serialVersionUID = 1L;
// 定义jackson对象
private static final ObjectMapper MAPPER = new ObjectMapper();
// 响应业务状态
/*
* 200 成功
* 201 错误
* 400 参数错误
*/
private Integer status;
// 响应消息
private String msg;
// 响应中的数据
private Object data;
public static SysResult build(Integer status, String msg, Object data) {
return new SysResult(status, msg, data);
}
public static SysResult oK(Object data) {
return new SysResult(data);
}
public static SysResult oK() {
return new SysResult(null);
}
public SysResult() {
}
public static SysResult build(Integer status, String msg) {
return new SysResult(status, msg, null);
}
public SysResult(Integer status, String msg, Object data) {
this.status = status;
this.msg = msg;
this.data = data;
}
public SysResult(Object data) {
this.status = 200;
this.msg = "OK";
this.data = data;
}
public Boolean isOk() {
return this.status == 200;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
}