Video-No.01 李守宏_SpringMVC基礎與應用視頻教程

一、SpringMVC基本配置
1)引入spring Jar包
2)配置web.xm文件,加載SpringMVC配置css

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   xmlns="http://java.sun.com/xml/ns/javaee" 
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
   id="WebApp_ID" 
   version="3.0">
   <display-name>springmvc</display-name>
  
   <welcome-file-list>
     <welcome-file>index.html</welcome-file>
     <welcome-file>index.htm</welcome-file>
     <welcome-file>index.jsp</welcome-file>
     <welcome-file>default.html</welcome-file>
     <welcome-file>default.htm</welcome-file>
     <welcome-file>default.jsp</welcome-file>
   </welcome-file-list>
  
   <!-- Spring MVC配置 -->
   <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 能夠自定義springMVC-servlet.xml(默認名稱)配置文件的位置和名稱,默認爲WEB-INF目錄下,名稱爲[<servlet-name>]-servlet.xml,如spring-servlet.xml -->
    <init-param>
     <param-name>contextConfigLocation</param-name>
     <param-value>/classpath:config/spring-servlet.xml</param-value>
    </init-param>
    <!-- 啓動的時候加載servlet -->
    <load-on-startup>1</load-on-startup>
   </servlet>
  
   <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
   </servlet-mapping>
   
   <!-- 配置編碼格式 -->
   <filter>
  <filter-name>SetCharacterEncoding</filter-name>
  <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  <init-param>
   <param-name>encoding</param-name>
   <param-value>UTF-8</param-value>
  </init-param>
  <init-param>
   <param-name>forceEncoding</param-name>
   <param-value>true</param-value><!-- 強制進行轉碼 -->
  </init-param>
 </filter>
 
 <filter-mapping>
  <filter-name>SetCharacterEncoding</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
  
   <!-- Spring配置 -->
   <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
   </listener>
  
   <!-- 指定Spring Bean的配置文件所在目錄。默認配置在WEB-INF目錄下 -->
   <context-param>
     <param-name>contextConfigLocation</param-name>
     <param-value>classpath:config/applicationContext.xml</param-value>
   </context-param>
  
</web-app>

3)配置spring-servlet.xml文件,加載springmvc相關配置html

<?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:aop="http://www.springframework.org/schema/aop"
 xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:jpa="http://www.springframework.org/schema/data/jpa"
 xmlns:security="http://www.springframework.org/schema/security"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="
  http://www.springframework.org/schema/aop 
  http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
  http://www.springframework.org/schema/security 
  http://www.springframework.org/schema/security/spring-security-3.2.xsd
  http://www.springframework.org/schema/beans 
  http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  http://www.springframework.org/schema/data/jpa 
  http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
  http://www.springframework.org/schema/tx 
  http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
  http://www.springframework.org/schema/context 
  http://www.springframework.org/schema/context/spring-context-4.0.xsd
  http://www.springframework.org/schema/mvc
  http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
 
 <!-- 啓用springmvc註解 -->
 <mvc:annotation-driven />
 
 <!-- 設置使用註解的類所在的jar包 -->
    <context:component-scan base-package="com.shma.springmvc.controller" />
    
    <!-- 靜態資源的訪問 -->
 <mvc:resources location="/resources/img/" mapping="/resources/img/**"/>  
    <mvc:resources location="/resources/js/" mapping="/resources/js/**"/>
    <mvc:resources location="/resources/css/" mapping="/resources/css/**"/>
    
    <!-- 配置視圖對轉向頁面的路徑解析,prefix:前綴, suffix:後綴 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
     <property name="prefix" value="/WEB-INF/views/"></property>
     <property name="suffix" value=".jsp"></property>
    </bean>
    
    <!-- 上傳文件的解析器 -->  
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <property name="defaultEncoding" value="utf-8"/>  
        <property name="maxUploadSize" value="10485760000"/>  
        <property name="maxInMemorySize" value="40960"/>  
    </bean>
</beans>

二、http請求中的中文亂碼問題處理
1)客戶端JS代碼,將字符串進行url編碼前端

 var username = encodeURI($("#username").val());
 var password = encodeURI($("#password").val());

2)服務器端,用URLDecoder.decode進行解碼java

String username = URLDecoder.decode(user.getUsername(), "UTF-8");
String password = URLDecoder.decode(user.getPassword(), "UTF-8");

三、SpringMVC註解含義web

  • @Controller:控制器spring

  • @RequestMapping(value="user", method=RequestMethod.POST):設置請求的路徑和方法json

  • @ResponseBody:設置返回格式爲jsonspring-mvc

  • @RequestParam("username") String userName:請求參數設置服務器

四、SpringMVC上傳文件
    Spring經過對Servlet API的HttpServletRequest接口進行擴展,使其可以很好地處理文件上傳。擴展後的接口名爲org.springframework.web.multipart.MultipartHttpServletRequestmvc

interface MultipartHttpServletRequest extends HttpServletRequest {
    public MultipartFile getFile(String name);
    public Map getFileMap();
    public Iterator getFileNames();
}

1)引入:Commons-FileupLoad.jar和Commons-IO.jar包

2)配置文件解析器

<!-- 上傳文件配置 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="defaultEncoding" value="utf-8" />
    <property name="maxUploadSize" value="10485760000" />
    <property name="maxInMemorySize" value="40960" />
</bean>

3)前端頁面

<form action="../file/upload.do" method="post" enctype="multipart/form-data">
    <input name="file" type="file" />
    <input type="submit" value="提交" />
</form>

4)後臺代碼
a)自定義讀取文件流方法

@RequestMapping(value="upload", method=RequestMethod.POST)
public String upload(@RequestParam("file") CommonsMultipartFile file,
     HttpServletRequest req) {
 String fileName = file.getOriginalFilename();
 System.out.println("您上傳的文件名稱爲:" + fileName);
 if(!StringUtils.isEmpty(fileName)) {
  File nFile = new File("D:/file/" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + fileName);
  if(!nFile.exists()) {
   FileOutputStream fos = null;
      InputStream in = null;
      try {
        nFile.createNewFile();
        fos = new FileOutputStream(nFile);
        in = file.getInputStream();
        int b = -1;
        while((b = in.read()) != -1) {
          fos.write(b);
        }
        fos.flush();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } finally {
        try {
          in.close();
          fos.close();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
    
      }
    }
  
 }
 return "success";
}

b)springmvc自帶的上傳文件方法(推薦使用)

@RequestMapping(value="uploadfile", method=RequestMethod.POST)
public String uploadForSpringMVC(HttpServletResponse resp,
     HttpServletRequest req) {
 
 CommonsMultipartResolver multReslover = new CommonsMultipartResolver(req.getServletContext());
 
  if(multReslover.isMultipart(req)) {
    MultipartHttpServletRequest multServletReq = (MultipartHttpServletRequest)req;
    Iterator<String> files = multServletReq.getFileNames();
    while(files.hasNext()) {
      try {
        MultipartFile multiFile = multServletReq.getFile(files.next());
       File nFile = new File("D:/file/" + new SimpleDateFormat("yyyyMMddHHssmm").format(new Date()) + "_" + multiFile.getOriginalFilename());
        if(!nFile.exists()) {
          nFile.createNewFile();
        }
    
        multiFile.transferTo(nFile);
      } catch(IOException e) {
        e.printStackTrace();
      }
    }
  }
 
  return "success";
}
相關文章
相關標籤/搜索