个人笔记,如有错误,恳请批评指正。
spring-mvc.xml文件添加如下内容:
<!--文件上传使用, 配置multipartResolver,id名为约定好的 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><!-- 配置文件(每次上传的所有文件总大小)大小,单位为b, 1024000表示1000kb --> <property name="maxUploadSize" value="1024000" /> </bean>web.xml文件添加如下内容:
<filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-v alue>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>如果上边的方式设置后,仍然有乱码,请尝试修改tomcat安装目录下的apache-tomcat安装目录/conf/server.xml文件,修改Connector元素内容,添加URIEncoding=”UTF-8” ,修改后内容 如下:
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="UTF-8"/>PropertiesFactoryBean:用来注入properties类型的配置文件信息
<!--PropertiesFactoryBean对properties文件可用 ,可以用来注入properties配置文件的信息 --> <bean id="uploadProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="location" value="classpath:xxxxx.properties"></property> </bean>继续使用上一章节代码,并导入文件上传需要的jar包:commons-fileupload-1.2.2.jar, commons-io-2.0.1.jar
StudentAction.java
@Controller@RequestMapping("/student")public class StudentAction { public StudentAction(){ System.out.println("---StudentAction构造方法被调用---"); } @RequestMapping("/save") public String save(Student student) { System.out.println("save方法已注入student对象:"+student); MultipartFile[] files=student.getFiles(); for(MultipartFile file:files){ if(file.isEmpty()){ System.out.println("文件为空"); }else{ System.out.println("文件不为空!"); System.out.println("格式:" + file.getContentType()); System.out.println("原名:" + file.getOriginalFilename()); System.out.println("大小:" + file.getSize()); System.out.println("表单控件的名称" + file.getName()); try { FileUtils.copyInputStreamToFile(file.getInputStream(), new File("e:/testupload/"+file.getOriginalFilename())); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } System.out.println("---调用业务逻辑进行业务处理---"); //直接使用字符串,返回视图,进行结果展现等 return "forward:/jsp/main.jsp"; }}添加文件处理器CommonsMultipartResolver配置
<?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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd "> <mvc:annotation-driven></mvc:annotation-driven> <context:component-scan base-package="*"/> <!--文件上传使用, 配置multipartResolver,id名称为约定好的 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 配置文件(每次上传的所有文件总大小)大小,单位为b, 1024000表示1000kb --> <property name="maxUploadSize" value="1024000" /> </bean></beans>main.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><html> <head> <title>main.jsp</title> </head> <body> /jsp/main.jsp页面 student: ${requestScope.student} </body></html> 在项目目录下新建upload文件夹
修改StudentAction.java。
@Controller@RequestMapping("/student")public class StudentAction { public StudentAction(){ System.out.println("---StudentAction构造方法被调用---"); } @Resource ServletContext application; @RequestMapping("/save") public String save(Student student) { System.out.println("save方法已注入student对象:"+student); MultipartFile[] files=student.getFiles(); System.out.println("真实路径:"+application.getRealPath("/")); for(MultipartFile file:files){ if(file.isEmpty()){ System.out.println("文件为空"); }else{ System.out.println("文件不为空!"); System.out.println("格式:" + file.getContentType()); System.out.println("原名:" + file.getOriginalFilename()); System.out.println("大小:" + file.getSize()); System.out.println("表单控件的名称" + file.getName()); try { FileUtils.copyInputStreamToFile(file.getInputStream(), new File(application.getRealPath("/")+"upload/"+file.getOriginalFilename())); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } System.out.println("---调用业务逻辑进行业务处理---"); //直接使用字符串,返回视图,进行结果展现等 return "forward:/jsp/main.jsp"; }}其它代码同上一章节,可以在application.getRealPath(“/”)+”upload/”目录下查看到文件。
FileUploadUtil.java
@Component(value="fileUploadUtils") //普通的bean注入public class FileUploadUtils { /* * 注入字符串,#{}为spel语言,其中uploadProperties,是xml配置文件中注入properties文件的bean id, * path为properties文件的其中一个key ,也可以通过下边的set方法注入 */ @Value("#{uploadProperties.path}") private String path; //private String path="e:/testupload"; //path也可以通过set方法注入// @Value("#{uploadProperties.path}") // public void setPath(String path) {// this.path = path;// } private String getExtName(MultipartFile file){ return FilenameUtils.getExtension(file.getOriginalFilename()); } private String createNewName(MultipartFile file){ return UUID.randomUUID().toString()+"."+getExtName(file); } public String uploadFile(MultipartFile file){ try { String newName=createNewName(file); FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path,newName )); return newName; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new RuntimeException(e); } }}主要修改save方法,使用自已的文件上传工具类进行文件上传。
@Controller@RequestMapping(value="/student")public class StudentAction { @Resource private ServletContext application; @Resource private FileUploadUtils fileUploadUtils; public StudentAction(){ System.out.println("---StudentAction构造方法被调用---"); } @RequestMapping(value="/save") public String save(Student student,Map<String, Student> paramMap) { System.out.println("save方法已注入student对象:"+student); MultipartFile[] files=student.getFiles(); for(MultipartFile file:files){ if(file.isEmpty()){ System.out.println("文件为空"); }else{ System.out.println("文件不为空!"); fileUploadUtils.uploadFile(file); } } System.out.println("---调用业务逻辑进行业务处理---"); paramMap.put("student",student); //直接使用字符串,返回视图,进行结果展现等 return "forward:/jsp/main.jsp"; }}配置文件上传后的存放目录
path=e/://testdir//upload//注入配置文件的信息
<!--PropertiesFactoryBean对properties文件可用 ,可以用来注入properties配置文件的信息 --> <bean id="uploadProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="location" value="classpath:upload.properties"></property> </bean>LoginInterceptor.java,需要实现HandlerInterceptor接口
public class LoginInterceptor implements HandlerInterceptor { @Override public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { // TODO Auto-generated method stub System.out.println("---访问请求资源后不管理有没有异常都一定执行此方法---"); } @Override public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { // TODO Auto-generated method stub System.out.println("---访问请求资源后,如果没有异常,将执行此方法---"); } @Override public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception { // TODO Auto-generated method stub System.out.println("---访问请求资源前执行,如果此方法返回false,将不能访问请求资源---"); return true; }}添加拦截器类及拦截器配置信息,如上面。
login.jsp,本页面已模仿了登陆
<%@page import="cn.itcast.entity.Student"%><%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><html> <head> <title>My JSP 'index.jsp' starting page</title> </head> <body> <% session.setAttribute("user", new Student(1001,"zcf","admin",20)); %> <!-- 这里正常应该跳到action再到页面 ,为了演示,这里简略--> <a href="index.jsp">已登陆,返回首页</a> </body></html>使用上面的源码,暂时去掉拦截器的登陆权限处理
新闻热点
疑难解答