個(gè)人筆記,如有錯(cuò)誤,懇請(qǐng)批評(píng)指正。
spring-mvc.xml文件添加如下內(nèi)容:
<!--文件上傳使用, 配置multipartResolver,id名為約定好的 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><!-- 配置文件(每次上傳的所有文件總大小)大小,單位為b, 1024000表示1000kb --> <property name="maxUploadSize" value="1024000" /> </bean>web.xml文件添加如下內(nèi)容:
<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>如果上邊的方式設(shè)置后,仍然有亂碼,請(qǐng)嘗試修改tomcat安裝目錄下的apache-tomcat安裝目錄/conf/server.xml文件,修改Connector元素內(nèi)容,添加URIEncoding=”UTF-8” ,修改后內(nèi)容 如下:
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="UTF-8"/>PropertiesFactoryBean:用來注入properties類型的配置文件信息
<!--PropertiesFactoryBean對(duì)properties文件可用 ,可以用來注入properties配置文件的信息 --> <bean id="uploadProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="location" value="classpath:xxxxx.properties"></property> </bean>繼續(xù)使用上一章節(jié)代碼,并導(dǎo)入文件上傳需要的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構(gòu)造方法被調(diào)用---"); } @RequestMapping("/save") public String save(Student student) { System.out.println("save方法已注入student對(duì)象:"+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("---調(diào)用業(yè)務(wù)邏輯進(jìn)行業(yè)務(wù)處理---"); //直接使用字符串,返回視圖,進(jìn)行結(jié)果展現(xiàn)等 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頁(yè)面 student: ${requestScope.student} </body></html>? 在項(xiàng)目目錄下新建upload文件夾
? 修改StudentAction.java。
@Controller@RequestMapping("/student")public class StudentAction { public StudentAction(){ System.out.println("---StudentAction構(gòu)造方法被調(diào)用---"); } @Resource ServletContext application; @RequestMapping("/save") public String save(Student student) { System.out.println("save方法已注入student對(duì)象:"+student); MultipartFile[] files=student.getFiles(); System.out.println("真實(shí)路徑:"+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("---調(diào)用業(yè)務(wù)邏輯進(jìn)行業(yè)務(wù)處理---"); //直接使用字符串,返回視圖,進(jìn)行結(jié)果展現(xiàn)等 return "forward:/jsp/main.jsp"; }}其它代碼同上一章節(jié),可以在application.getRealPath(“/”)+”upload/”目錄下查看到文件。
FileUploadUtil.java
@Component(value="fileUploadUtils") //普通的bean注入public class FileUploadUtils { /* * 注入字符串,#{}為spel語(yǔ)言,其中uploadProperties,是xml配置文件中注入properties文件的bean id, * path為properties文件的其中一個(gè)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方法,使用自已的文件上傳工具類進(jìn)行文件上傳。
@Controller@RequestMapping(value="/student")public class StudentAction { @Resource private ServletContext application; @Resource private FileUploadUtils fileUploadUtils; public StudentAction(){ System.out.println("---StudentAction構(gòu)造方法被調(diào)用---"); } @RequestMapping(value="/save") public String save(Student student,Map<String, Student> paramMap) { System.out.println("save方法已注入student對(duì)象:"+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("---調(diào)用業(yè)務(wù)邏輯進(jìn)行業(yè)務(wù)處理---"); paramMap.put("student",student); //直接使用字符串,返回視圖,進(jìn)行結(jié)果展現(xiàn)等 return "forward:/jsp/main.jsp"; }}配置文件上傳后的存放目錄
path=e/://testdir//upload//注入配置文件的信息
<!--PropertiesFactoryBean對(duì)properties文件可用 ,可以用來注入properties配置文件的信息 --> <bean id="uploadProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="location" value="classpath:upload.properties"></property> </bean>LoginInterceptor.java,需要實(shí)現(xiàn)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("---訪問請(qǐng)求資源后不管理有沒有異常都一定執(zhí)行此方法---"); } @Override public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { // TODO Auto-generated method stub System.out.println("---訪問請(qǐng)求資源后,如果沒有異常,將執(zhí)行此方法---"); } @Override public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception { // TODO Auto-generated method stub System.out.println("---訪問請(qǐng)求資源前執(zhí)行,如果此方法返回false,將不能訪問請(qǐng)求資源---"); return true; }}添加攔截器類及攔截器配置信息,如上面。
login.jsp,本頁(yè)面已模仿了登陸
<%@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)); %> <!-- 這里正常應(yīng)該跳到action再到頁(yè)面 ,為了演示,這里簡(jiǎn)略--> <a href="index.jsp">已登陸,返回首頁(yè)</a> </body></html>使用上面的源碼,暫時(shí)去掉攔截器的登陸權(quán)限處理
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注