SpringMVC配置,簡單一實例,檔案上傳與下載,ajax請求

來源:互聯網
上載者:User

本文基於SpringMVC採用註解方式,從配置到簡單常用的功能舉例詳解,功能已經在本機測試過,能跑起來。

參考資料:iteye部落格;

                  Spring文檔;

1、匯入相關jar包:

                               spring-core-3.2.0.jar;spring-web-3.2.0.jar;spring-webmvc-3.2.0.jar;common-annotations.jar;commons-fileupload-1.2.2.jar;spring-beans-3.2.0.RELEASE.jar。

2、在web.xml配置DispatcherServlet,攔截匹配的請求;(初始化過程中預設WEB-INF檔案夾下尋找名為[servlet-name]-servlet.xml,也可加入參數classpath指定)

     

 <servlet>          <servlet-name>spring</servlet-name>          <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>          <load-on-startup>1</load-on-startup>      </servlet>      <servlet-mapping>          <servlet-name>spring</servlet-name>  <!-- 這裡在配成spring,下邊也要寫一個名為spring-servlet.xml的檔案,主要用來配置它的controller -->        <url-pattern>*.do</url-pattern>      </servlet-mapping>    <welcome-file-list>    <welcome-file>/userInfo.jsp</welcome-file>  </welcome-file-list>

3、配置[servlet-name]-servlet.xml

   

 <context:annotation-config />          <!-- 把標記了@Controller註解的類轉換為bean -->           <context:component-scan base-package="com.test.Controllers" />       <!-- 啟動Spring MVC的註解功能,完成請求和註解POJO的映射 --><!--           <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />        <bean  id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"               p:prefix="/WEB-INF/view/" p:suffix=".jsp" />            -->       <!-- 配置視圖解析器預設的屬性檔案是classpath下的:views.properties --><bean id="resourceBundleViewResolver"class="org.springframework.web.servlet.view.ResourceBundleViewResolver"><property name="basename" value="views" ></property></bean>       <!-- 通過setViewClass方法,可以指定用於該解析器產生視圖使用的視圖類 --><bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"p:viewClass="org.springframework.web.servlet.view.JstlView"p:prefix="/WEB-INF/" p:suffix=".jsp"/>      <!-- 檔案上傳配置 --><bean id="multipartResolver"               class="org.springframework.web.multipart.commons.CommonsMultipartResolver"               p:defaultEncoding="utf-8">            <property name="maxUploadSize" value="1024000000"/>            <property name="resolveLazily" value="true"/>          </bean>

4、Controller類的編寫

    

@Controller@RequestMapping("/userInfo.do")public class UserController {/**         * 檔案上傳與擷取user對象,這裡沒連資料庫只是將值擷取,檔案上傳目錄下 * @param user  * @param request * @param files 檔案組 * @return * @throws Exception */@RequestMapping(params="method=saveUser")    public ModelAndView  saveUser(User user,HttpServletRequest request,@RequestParam("fileName")MultipartFile[] files ) throws Exception{ModelAndView mav=new ModelAndView();System.out.println(user.getUserName()+"密碼"+user.getUserPwd());mav.addObject("message","成功!");mav.addObject("user",user);//List<MultipartFile>files=mRequest.getFiles("fileName");String uploadpath = request.getSession().getServletContext().getRealPath("/");System.out.println(uploadpath);//System.out.println(files.isEmpty());for (MultipartFile multipartFile : files) { if (multipartFile.isEmpty()) continue; System.out.println(multipartFile.getOriginalFilename());  FileOutputStream fileOS = new FileOutputStream(uploadpath  + multipartFile.getOriginalFilename());            fileOS.write(multipartFile.getBytes());            System.out.println(fileOS);            fileOS.close();}/*FileOutputStream fileOS = new FileOutputStream(uploadpath+file.getOriginalFilename());        fileOS.write(file.getBytes());        System.out.println(fileOS);        fileOS.close();*/mav.setViewName("userView");//設定返回的視圖,具體頁面將會在views.properties裡設定return mav;    }

5、jsp頁面的編寫,採用註解方式,無需配置其他配置,與struts2一樣,將input name屬性與java bean對應,參數自動封裝。

     

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">  </head>  <body>     <form id="addUserInfoForm" action="<%=request.getContextPath()%>/userInfo.do?method=saveUser" method="post" enctype="multipart/form-data">    <input name="userName"  value="${user.userName}"/>      <input name="userPwd" value="${user.userPwd}"/>      <input type="file" name="fileName">      <input type="file" name="fileName">      <input type="submit"  value="提交"/>    </form>   </body></html>

6、配置views.properties(預設在classpath下找)

userView.(class)=org.springframework.web.servlet.view.JstlView

userView.url=/WEB-INF/userInfo.jsp

以上完成了檔案上傳和User資訊的擷取。

二、下面簡單貼出檔案下載代碼

  

/** * 檔案下載 * @param request * @param response * @return 由於只是測試,很多資訊都是手動寫死的,湊合著看。 * @throws Exception */@RequestMapping(params="method=downLoadFile")public ModelAndView downLoadFile(HttpServletRequest request,HttpServletResponse response) throws Exception{BufferedInputStream bis = null;          BufferedOutputStream bos = null;         // String downLoadPath="rr.sql";        String realName="rr.sql"; //設定下載檔案名稱字        String fileName=request.getParameter("fileName");  //擷取完整的檔案名稱        System.out.println(fileName);        long fileLength=new File(fileName).length();         String ctxPath = request.getSession().getServletContext().getRealPath("/");          response.setContentType("application/octet-stream");        response.setHeader("Content-disposition", "attachment; filename="                  + new String(realName.getBytes("utf-8"), "ISO8859-1"));          response.setHeader("Content-Length", String.valueOf(fileLength));        bis = new BufferedInputStream(new FileInputStream(fileName));          bos = new BufferedOutputStream(response.getOutputStream());          byte[] buff = new byte[2048];          int bytesRead;          while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {              bos.write(buff, 0, bytesRead);          }          bis.close();          bos.close();  ModelAndView mav=new ModelAndView();return null;}

    JSP下載頁面

   

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">  </head>  <body>     <form id="addUserInfoForm" action="<%=request.getContextPath()%>/userInfo.do?method=saveUser" method="post" enctype="multipart/form-data">      <a href="<%=request.getContextPath()%>/userInfo.do?method=downLoadFile&fileName=F:\Server\apache-tomcat-6.0.36\webapps\SpringMVC\rr.sql">下載</a>      <input type="submit"  value="提交"/>    </form>   </body></html>

     上面的參數fileName直接寫的,因為沒有連資料庫。

三、ajax請求json資料

      

 步驟一:加入json jar包 樣本:ackson-core-asl-1.7.2.jar ,jackson-mapper-asl-1.7.2.jar

  步驟二:spring的設定檔中加入:<mvc:annotation-driven/>(HttpMessageConverter需開啟)

  步驟三:在返回的對象上加@ResponseBody  將內容或對象作為 HTTP 響應本文返回,並調用適合HttpMessageConverter的Adapter轉換對象,寫入輸出資料流。(開啟這個注釋後AnnotationMethodHandlerAdapter將會初始化以下7個轉換器ByteArrayHttpMessageConverter
StringHttpMessageConverter
ResourceHttpMessageConverter
SourceHttpMessageConverter
XmlAwareFormHttpMessageConverter
Jaxb2RootElementHttpMessageConverter
MappingJacksonHttpMessageConverter---spring預設的json協議由Jackson完成)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.