springMVC 注解方式实现全程+文件上传

来源:互联网 发布:找数据网站有哪些 编辑:程序博客网 时间:2024/06/10 03:12
springmvc的注解框架的实现吧:

Web.xml文件

[html] view plaincopy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  3. xmlns="http://java.sun.com/xml/ns/javaee"   
  4. xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"   
  5. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  6. http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">  
  7. <!-- 配置控制器 -->  
  8.   <servlet>  
  9.     <servlet-name>dispatcher</servlet-name>     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  10.   </servlet>  
  11.   <!-- 配置spring 配置文件    -->  
  12.   <context-param>  
  13.     <param-name>contextConfigLocation</param-name>  
  14.         <param-value>  
  15.             classpath:config/applicationContext-base.xml,             
  16.             classpath:config/applicationContext*.xml  
  17.         </param-value>  
  18.   </context-param>  
  19.      
  20.   <!-- 配置控制器映射 -->  
  21.   <servlet-mapping>  
  22.     <servlet-name>dispatcher</servlet-name>  
  23.     <url-pattern>*.do</url-pattern>  
  24.   </servlet-mapping>  
  25.     
  26.   <listener>  
  27.     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  28.   </listener>  
  29. </web-app>  

dispatcher-servlet.xml(注意:这个xml文件是springmvc的核心配置文件,实际上是一个applicationContext.xml文件,默认为WEB-INF路径下,若有另外的配置,需要在web.xml文件中配置:另外,该xml文件命名规范为web.xml文件中<servlet-name>dispatcher</servlet-name>配置的名字加上”-servlet.xml”,本例中为dispatcher-servlet.xml)

[html] view plaincopy
  1. <servlet>  
  2.     <servlet-name>dispatcher</servlet-name>     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  3. <init-param>    
  4.             <param-name>contextConfigLocation</param-name>               
  5.             <!--      
  6.               指定XML文件位置     
  7.               <param-value>/WEB-INF/classes/springmvc.xml                
  8.               <param-value>classpath*:springmvc.xml     
  9.              -->    
  10.              <!-- 在classpath路径下去寻找springmvc.xml文件 -->               
  11.              <param-value>classpath:springmvc.xml     
  12.             </param-value>    
  13.         </init-param>    
  14.   </servlet>  

dispatcher-servlet.xml: 

[html] view plaincopy
  1. <?xml version="1.0" encoding="UTF-8"?>     
  2.   <beans xmlns="http://www.springframework.org/schema/beans"       
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  4.        xmlns:p="http://www.springframework.org/schema/p"       
  5.        xmlns:context="http://www.springframework.org/schema/context"   
  6.        xmlns:mvc="http://www.springframework.org/schema/mvc"      
  7.        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd     
  8.        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd     
  9.        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd     
  10.        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd  
  11.        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"  
  12.         default-autowire="byName">     
  13.   
  14.     <!-- SpringMVC相关Bean配置 -->  
  15.       
  16.       
  17.     <bean id="localeResolver" class="org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver">  
  18.     </bean>  
  19.     <!-- 配置视图 -->  
  20.     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"  
  21.         p:prefix="/WEB-INF/view/" p:suffix=".jsp">  
  22.         <property name="viewClass">             
  23.             <value>org.springframework.web.servlet.view.JstlView</value>              
  24.         </property>  
  25.     </bean>  
  26.       
  27.     <context:annotation-config />     
  28.        <!-- 把标记了@Controller注解的类转换为bean -->       
  29.       <context:component-scan base-package="test.controller" />   
  30.     <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->       
  31.       <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />       
  32.           
  33.     <bean id="multipartResolver"       
  34.           class="org.springframework.web.multipart.commons.CommonsMultipartResolver"       
  35.           p:defaultEncoding="utf-8" />       
  36.       
  37.       
  38. </beans>  

定义一个jsp页面:

[html] view plaincopy
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.   
  3.     pageEncoding="UTF-8"%>  
  4.   
  5.    
  6.   
  7. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  8.   
  9. <html>  
  10.   
  11. <head>  
  12.   
  13. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
  14.   
  15. <title>Insert title here</title>  
  16.   
  17. </head>  
  18.   
  19. <body>  
  20.   
  21.     <form action="login.do" method="post">  
  22.   
  23.         <input type="hidden" name="method" value="pageQuery"/>  
  24.   
  25. <input type="hidden" name="pageNo" value="1"/>  
  26.   
  27.         userName:<input type="text" name="userName"/><br>  
  28.   
  29.         password:<input type="password" name="password"/><br>  
  30.   
  31.         <input type="submit" value="submit"/>  
  32.   
  33.     </form>  
  34.   
  35.    
  36.   
  37.    <hr>  
  38.   
  39.     <h1>test file upload</h1>  
  40.   
  41.     <form action="login.do" method="post" enctype="multipart/form-data">  
  42.   
  43.         <input type="hidden" name="method" value="upload"/>  
  44.   
  45.         <input type="file" name="file"/>  
  46.   
  47.         <input type="submit" value="upload"/>  
  48.   
  49.     </form>  
  50.   
  51.       
  52.   
  53. </body>  
  54.   
  55. </html>  

Form表单映射类:Login:

[java] view plaincopy
  1. package test.entity;  
  2.   
  3. public class Login {  
  4.   
  5.     private String userName; //从页面获取的值  
  6.     private String password; //从页面获取的值  
  7.       
  8.     public String getUserName() {  
  9.         return userName;  
  10.     }  
  11.     public void setUserName(String userName) {  
  12.         this.userName = userName;  
  13.     }  
  14.     public String getPassword() {  
  15.         return password;  
  16.     }  
  17.     public void setPassword(String password) {  
  18.         this.password = password;  
  19.     }  
  20.   
  21. }  

编写Controller:

[java] view plaincopy
  1. package test.controller;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.text.SimpleDateFormat;  
  6. import java.util.Date;  
  7.   
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10.   
  11. import org.springframework.stereotype.Controller;  
  12. import org.springframework.ui.ModelMap;  
  13. import org.springframework.web.bind.annotation.RequestMapping;  
  14. import org.springframework.web.bind.annotation.RequestMethod;  
  15. import org.springframework.web.bind.annotation.RequestParam;  
  16. import org.springframework.web.multipart.MultipartFile;  
  17. import org.springframework.web.multipart.MultipartHttpServletRequest;  
  18. import test.entity.Login;  
  19.   
  20. import com.zhjy.core.util.Page;  
  21.   
  22. @Controller  
  23. @RequestMapping("/login.do")  
  24. public class CopyOfTestController {  
  25.   
  26.     @RequestMapping  
  27.     public String login(HttpServletRequest request, HttpServletResponse response, Login login) {  
  28.           
  29.         System.out.println(request.getParameter("userName"));  
  30.         System.out.println(login.getUserName());  
  31.         return "success";  
  32.     }  
  33.       
  34.     /** 
  35.      * 参数注入测试 @RequestParam("pageNo") int pageNo 
  36.      * 页面请求需要带参数pageNo 
  37.      * @param pageNo 
  38.      * @param request 
  39.      * @param model 
  40.      * @return 
  41.      * @throws Exception 
  42.      */  
  43.     @RequestMapping(params = "method=pageQuery")  
  44.     public String pageQuery(@RequestParam("pageNo"int pageNo,  
  45.             HttpServletRequest request,ModelMap model) throws Exception{  
  46.         System.out.println(pageNo);  
  47.         String putModel="test put model string";  
  48.         model.put("model", putModel);  
  49.           
  50.         return "/test/success";//页面跳转到WEB-INF/view/test/success.jsp页面  
  51. //注释:WEB-INF/view是配置文件中的前缀,.jsp 是配置文件中的后缀  
  52. //<bean id="viewResolver" //class="org.springframework.web.servlet.view.InternalResourceViewResolver"  
  53. //      p:prefix="/WEB-INF/view/" p:suffix=".jsp">  
  54.   
  55.     }  
  56.       
  57.     /** 
  58.      * 不同请求方式POST GET 
  59.      * @param login 
  60.      * @param request 
  61.      * @param response 
  62.      * @param model 
  63.      * @return 
  64.      */  
  65.     @RequestMapping(method=RequestMethod.POST, params = "method=save")  
  66.     public String login(Login login, HttpServletRequest request,   
  67.             HttpServletResponse response, ModelMap model) {       
  68.         System.out.println(request.getParameter("userName"));  
  69.         System.out.println(login.getUserName());  
  70.         model.addAttribute("user""user");  
  71.         this.getOracleService().test();  
  72.         return "/test/success";  
  73.     }  
  74.       
  75.     /** 
  76.      * 上传文件测试 
  77.      * @param request 
  78.      * @param model 
  79.      * @return 
  80.      */  
  81.     @RequestMapping(method=RequestMethod.POST, params = "method=upload")  
  82.     public String upload(HttpServletRequest request,ModelMap model) {  
  83.           
  84.         MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;     
  85.         SimpleDateFormat dateformat = new SimpleDateFormat("yyyy/MM/dd/HH");     
  86.         /**构建图片保存的目录**/    
  87.         String logoPathDir = "/files"+ dateformat.format(new Date());     
  88.         /**得到图片保存目录的真实路径**/    
  89.         String logoRealPathDir = request.getSession().getServletContext().getRealPath(logoPathDir);     
  90.         /**根据真实路径创建目录**/    
  91.         File logoSaveFile = new File(logoRealPathDir);     
  92.         if(!logoSaveFile.exists())     
  93.             logoSaveFile.mkdirs();           
  94.         /**页面控件的文件流**/    
  95.         MultipartFile multipartFile = multipartRequest.getFile("file");      
  96.         /**获取文件的后缀**/    
  97.         String suffix = multipartFile.getOriginalFilename().substring  
  98.                         (multipartFile.getOriginalFilename().lastIndexOf("."));     
  99. //        /**使用UUID生成文件名称**/    
  100. //        String logImageName = UUID.randomUUID().toString()+ suffix;//构建文件名称     
  101.         String logImageName = multipartFile.getOriginalFilename();  
  102.         /**拼成完整的文件保存路径加文件**/    
  103.         String fileName = logoRealPathDir + File.separator   + logImageName;                
  104.         File file = new File(fileName);          
  105.         
  106.         try {     
  107.             multipartFile.transferTo(file);     
  108.         } catch (IllegalStateException e) {     
  109.             e.printStackTrace();     
  110.         } catch (IOException e) {            
  111.             e.printStackTrace();     
  112.         }     
  113.         model.put("fileName", fileName);  
  114.         return "/test/success";  
  115.           
  116.     }  
  117.       
  118. }  

在WEB-INF/view/test下建立success.jsp页面:

[html] view plaincopy
  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
  2.     pageEncoding="ISO-8859-1"%>  
  3.   
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  5. <html>  
  6. <head>  
  7. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
  8. <title>login success</title>  
  9. </head>  
  10. <body>  
  11. <hr>  
  12. <h1>view/test/success.jsp</h1>  
  13. <h1>login success</h1>  
  14. success<br/>  
  15. userName:${userName }<br/>  
  16. success<br/>  
  17. login.userName :${login.userName }<br/>  
  18. success<br/>  
  19. user:${user }<br/>  
  20. <hr>  
  21. <h1>test file upload</h1>  
  22. fileName:${fileName }   
  23. </body>  
  24. </html> 
原创粉丝点击