SpringMVC的使用(二)

restful風格

  1. 需要指定前端控制器的url-mapping 爲 /

  2. 配置靜態資源文件的處理 <mvc:default-servlet-handler />

  3. 在地址欄參數的位置使用佔位符 {佔位符key} 在參數接收的位置使用@PathVariable(佔位符key)

後臺返回值

  1. 跳轉頁面 轉發或者重定向 一定指向頁面 傳遞數據使用request容器
    a.返回ModelAndView viewName設置成跳轉頁面的字符串 傳遞數據 addObject(key,value)
    b.直接返回String 就是跳轉頁面的字符串 傳遞數據request.setAttribute(key,value)

  2. ajax只獲取數據 沒有頁面跳轉 response.getWriter().print()
    a.必須要加 @ResponseBody 指定我們響應 類似 response.getWriter().print()
    b.springMVC支持原本的傳遞JSON字符串的方式(springMVC中的HandlerAdapter中可以設置message-converters(轉換器) 指定了fastjson的支持可以直接返回任何對象)

上傳文件和圖片

  1. 文件上傳的路徑
         a.將路徑設置成項目的目錄 (簡單,能直接訪問到圖片 導致項目越來越大 不好維護)
         b.設置虛擬路徑
              圖片訪問目錄 == 圖片的實際目錄
              idea配置虛擬路徑
                 1.使用tomcat自帶的配置文件配置虛擬路徑 在host 標籤中配置一下內容
                    <Context path="/pic" docBase=“e://xxx/” />
                    path代表虛擬路徑 docBase代表實際路徑
                 2.使用idea的部署 來部署虛擬路徑
                    在tomcat配置 deployment中指定實際路徑,在路徑的下面指定虛擬路徑

  2. 文件上傳 fileUpload組件
         a.加入jar包 common-fileupload common-io
         b.將upload組件配置到spring容器中去 見配置文件
         c.編寫文件上傳頁面
             form表單
                 1.設置 enctype=“multipart/form-data”
                 2.設置請求模式爲post
             ajax上傳文件
                 1.獲取表單的formData對象,參數是表單的DOM對象
                 2.調用ajax
                    type:post
                    contentType: false
                    processData: false
                    data:表單的formData對象
         d.後臺控制層使用MultipartFile 來接收上傳的文件(獲取文件的文件名,獲取上傳的實際路徑(properties工具類實現),得到上傳文件的實際目錄)
             MultipartFile.transferTo 複製文件

  3. 多文件上傳
    將MultipartFile設置成數組 後臺循環即可

示例

mvc-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="com.igeek.action"></context:component-scan>
    <!--處理器驅動-->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <!-- 配置Fastjson支持 -->
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json</value>
                    </list>
                </property>
                <property name="features">
                    <!--
                        Fastjson的SerializerFeature序列化屬性:
                            QuoteFieldNames———-輸出key時是否使用雙引號,默認爲true
                            WriteMapNullValue——–是否輸出值爲null的字段,默認爲false
                            WriteNullNumberAsZero—-數值字段如果爲null,輸出爲0,而非null
                            WriteNullListAsEmpty—–List字段如果爲null,輸出爲[],而非null
                            WriteNullStringAsEmpty—字符類型字段如果爲null,輸出爲”“,而非null
                            WriteNullBooleanAsFalse–Boolean字段如果爲null,輸出爲false,而非null
                     -->
                    <list>
                        <value>QuoteFieldNames</value>
                        <value>WriteMapNullValue</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <!--視圖解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--默認是jsp的視圖-->
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <!-- 配置邏輯視圖的前綴 -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <!-- 配置邏輯視圖的後綴 -->
        <property name="suffix" value=".jsp" />
        <!--前綴+視圖字符串+後綴-->
    </bean>


    <!-- 對靜態資源文件的訪問 方案一 (二選一) -->
    <mvc:default-servlet-handler />

    <!--上傳文件組件-->
    <!--id固定multipartResolver-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--設置文件上傳的大小-->
        <property name="maxUploadSize" value="2000000"></property>
    </bean>

</beans>
@Controller
@RequestMapping("/login")
public class LoginAction {
    @RequestMapping("rest/{username}/{age}")
    public ModelAndView getRestFul(@PathVariable("username") String username, @PathVariable("age") String age){
        System.out.println(username + " " + age);
        System.out.println("進入了後臺");
        ModelAndView view = new ModelAndView();
        view.setViewName("login");
        view.addObject("username",username);
        view.addObject("age",age);
        return  view;
    }

    /*ajax獲取後臺數據*/
    @RequestMapping("getName")
    @ResponseBody
    public List<ParBean> getName(){
        ParBean par = new ParBean("xiaowang",10,"A");
        ParBean par1 = new ParBean("xiaozhang",20,"B");
        List<ParBean> list = new ArrayList<>();
        list.add(par);
        list.add(par1);
        return list;
    }

    @RequestMapping("file")
    public String fileUpload(@RequestParam("myFile") MultipartFile myFile,HttpServletRequest request){
        //獲取文件的文件名
        String fileName =myFile.getOriginalFilename();
        System.out.println(fileName);
        //獲取需要上傳到的位置
        String path = PropertiesUtil.getProp("REAL_PATH")+fileName;
        File f = new File(path);
        //文件複製
        try {
            myFile.transferTo(f);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String xuniPath = PropertiesUtil.getProp("XUNI_PATH")+fileName;
        request.setAttribute("pic",xuniPath);
        return "success";
    }
    
    @RequestMapping("file1")
    @ResponseBody
    public String fileUpload1(@RequestParam("myFile") MultipartFile[] allFile){
        if(allFile!=null){
            for (MultipartFile myFile:allFile) {
                //獲取文件的文件名
                String fileName =myFile.getOriginalFilename();
                System.out.println(fileName);
                //獲取需要上傳到的位置
                String path = PropertiesUtil.getProp("REAL_PATH")+fileName;
                File f = new File(path);
                //文件複製
                try {
                    myFile.transferTo(f);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String xuniPath = PropertiesUtil.getProp("XUNI_PATH")+fileName;
            }
        }

        return "";
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章