Day70 Spring MVC的響應方式,檢視解析器以及上傳下載和編碼過濾器

神一樣的我發表於2018-05-10

springmvc的響應

Springmvc的響應和作用域使用:
    方式一:用字串響應
        請求轉發:
            單元方法的返回值型別為String型別
            使用 return "forward:/檔案路徑"
        重定向:
            單元方法的返回值型別為String型別
            使用 return "redirect:/檔案路徑"
        注意:
            返回值中的第一個/表示專案根目錄。
    方式二:使用Springmvc的原生物件響應:
        使用View
            請求轉發:
                單元方法的返回值型別為View型別
                View v=new InternalResourceView("/show.jsp");//相當於請求轉發。
            重定向:
                單元方法的返回值型別為View型別
                View v=new RedirectView("/05-springmvc/show.jsp");//重定向,但是/代表伺服器根目錄
        使用ModelAndView:

            請求轉發:
        單元方法的返回值型別為ModelAndView型別
        ModelAndView mv=new ModelAndView("forward:/show.jsp");
            重定向:
        單元方法的返回值型別為ModelAndView型別
                ModelAndView mv=new ModelAndView("redirect:/show.jsp");
    方式三:直接響應
--------------------------------------------------------------------
SpringMVC的作用域使用:
    方式一:使用原生的request物件和session物件
        使用方式不變。
    方式二:在單元方法上宣告Map形參,使用Map進行作用域資料傳遞。
            注意:此種方式相當於使用request,請求轉發。
    方式三:在單元方法宣告Model形參,使用Model例項化物件進行資料傳遞。
            注意:此種方式相當於使用request,請求轉發。
-----------------------------------------------------------------------

Spring MVC響應的例子

原始碼:
@Controller
public class TestCon {
    /**
     * 方式一:使用字串:
     *      請求轉發
     *          單元方法的返回值型別為字串型別
     *          返回值中使用"forward:轉發資源的相對路徑"。
     *          注意:forward可以省略不寫
     *          作用域:
     *              request作用域:和以前一樣,正常使用即可。request物件需要在單元方法上作用形參宣告。
     *              session作用域:和以前一樣,正常使用即可。session物件需要在單元方法上作用形參宣告。
     * 
     *      重定向
     *          單元方法的返回值型別為字串型別
     *          返回值中使用"redirect:轉發資源的相對路徑"。
     * 
     *      相對路徑:
     *          相對的是請求地址路徑,會將請求地址的最後一個字母直接替換為返回值中的路徑,並請求新路徑的資源。
     *      注意:
     *          在請求準發和重定向的路徑中第一個開頭的/表示專案根目錄。
     * @return
     */
    @RequestMapping("demo1/aa")
    public String demo(HttpServletRequest req,HttpSession hs){
        System.out.println("使用字串直接響應----請求轉發");
        req.setAttribute("str", "our teacher`s english is good");
        hs.setAttribute("ss", "Springmvc is easy for me");
        return "forward:/show.jsp";
    }

    @RequestMapping("demo2/bb")
    public String demo2(){
        System.out.println("使用字串直接響應----重定向");
        return "redirect:/show.jsp";
    }

    /**
     * 方式二:
     *      使用springmvc的原生物件:
     *          View
     *          ModelAndView    
     */
    @RequestMapping("view")
    public View demo3(){
        //View v=new InternalResourceView("/show.jsp");//相當於請求轉發。
        View v=new RedirectView("/05-springmvc/show.jsp");//重定向,但是/代表伺服器根目錄
        return v;
    }

    @RequestMapping("mv")
    public ModelAndView demo4(){
        ModelAndView mv=new ModelAndView("forward:/show.jsp");
        mv.addObject("str", "this is modelAndview");
        return mv;
    }
    /**
     * 方式三:直接響應
     * @throws IOException 
     * 
     */
    @RequestMapping("resp")
    public void demo5(HttpServletRequest req,HttpServletResponse resp) throws IOException{
            resp.getWriter().write("today the weather is good,it is able to better study");
    }
    /**
     * Spring mvc 的作用域:
     *  Map方式:
     *      在單元方法上宣告map集合物件
     * 
     *  Model方式:
     *      在單元方法上宣告Model型別的引數
     *  注意:
     *      此兩種方式都相當於使用request
     * 
     */
    @RequestMapping("map")
    public String demoMap(Map<String ,Object> map) throws IOException{
            map.put("str", "this is map");
            return "/show.jsp";
    }
    @RequestMapping("model")
    public String demoModel(Model m) throws IOException{
            m.addAttribute("str", "this is model");
            return "/show.jsp";
    }

}

springmvc的檢視解析器

SpringMVC的檢視解析器:
    問題:
        因為WEB-INF資料夾對瀏覽器是不可見的。所以開發的時候,往往會將
        Jsp檔案和靜態資原始檔存放在WEB-INF資料夾先,對資源進行保護。
        必須使用請求轉發才能訪問。這樣造成單元方法的返回值書寫變得麻煩。
    解決:
        使用自定義檢視解析器
    使用:
        在Springmvc的配置檔案中配置自定義檢視解析器
            <!-- 配置自定義檢視解析器 -->
         <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/page/"></property>
            <property name="suffix" value=".jsp"></property>
              </bean>   
        注意:
            如果使用了自定義檢視解析器,在請求轉發使用forward關鍵觸發預設檢視解析器,來轉發
            單元方法。

springmvc的上傳和下載

SpringMVC的上傳:
    匯入jar包
    建立jsp檔案,並設定為上傳模式
    配置Springmvc
    將上傳的檔案存到指定位置

springmvc的配置:
  <!-- 配置上傳資源解析物件 -->
       <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <property name="defaultEncoding" value="utf-8"></property><!--設定解析編碼格式  -->
            <property name="maxInMemorySize" value="150000"></property><!--記憶體大小  -->
            <property name="maxUploadSize" value="1024123123"></property><!--檔案大小  -->
       </bean> 
       <!--配置異常解析器  --><!-- 異常對映解析類:當出現什麼型別異常時,跳轉到指定位置. -->
        <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
            <property name="exceptionMappings">
                <props>
                    <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">sizeLimit</prop>
                </props>
            </property>
        </bean>

jsp:
上傳:
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
    <form action="upload" method="post" enctype="multipart/form-data">
        使用者名稱:<input type="text" name="uname" value=""/> <br />
        年齡:<input type="text" name="age" value=""/><br />
        頭像:<input type="file" name="photo" /><br />
        <input type="submit" value="提交" /><br />
    </form>
</body>
</html>


下載:
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
    <img src="images/1.jpg" width="200px" /><a href="down?filename=1.jpg">下載</a>
</body>
</html>


控制器:

@Controller
public class TestUpload {
    //上傳
    @RequestMapping("upload")
    public String upload(String uname,int age,MultipartFile photo) throws IllegalStateException, IOException{
        //將圖片儲存到指定位置
            //校驗檔案型別
                //獲取檔案字尾名
                String suffixName=photo.getOriginalFilename().substring(photo.getOriginalFilename().lastIndexOf("."));
                //判斷
                if(!(".jpg".equals(suffixName) || ".png".equals(suffixName))){
                    return "error";
                }
            //設定檔案大小
            //檔案重新命名
                String newName=UUID.randomUUID()+""+suffixName;
            //建立儲存路徑
            File f=new File("D:/images");
            if(!f.exists()){
                f.mkdirs();
            }
            File f2=new File(f,newName);
            photo.transferTo(f2);
        //將相關資料儲存到資料庫中(上傳人,真實名,新名,儲存路徑)
            return "success";
    }
    //下載
    @RequestMapping("down")
    public void down(String filename,HttpServletRequest req,HttpServletResponse resp) throws IOException{
        //設定響應頭
            resp.setContentType("application/octet-stream");//表示任意型別
            resp.setHeader("Content-Disposition", "attachment;filename=abcdef.jpg");
        //獲取要下載的圖片的路徑
            String path=req.getServletContext().getRealPath("/images");
            File f=new File(path,filename);
        //獲取輸出流資源
            OutputStream os=resp.getOutputStream();
        //輸出圖片資源
            os.write(FileUtils.readFileToByteArray(f));
            os.flush();
            os.close();
    }
}
SpringMVC 和jsp的上傳下載的區別:
  jsp需要程式設計人員手動建立Upload物件解析資料,而Spring MVC 可以直接自動幫助程式設計人員完成解析並且返回封裝好的檔案物件。

springmvc的編碼過濾器

字元編碼過濾器只能解決POST請求.
解決請求和響應編碼格式
只需要把filter在web.xml中配置出來,就讓這個Filter生效
<!--配置編碼過濾器  -->
 <filter>
 <filter-name>encoding</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>encoding</filter-name>
 <url-pattern>/*</url-pattern>
 </filter-mapping>

web.xml和springmvc最新

web.xml:


<?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">
  <!--配置spring  -->
      <!--配置applicationContext,xml的路徑  -->
  <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
     <!--配置監聽器  -->
  <listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>
  <!--配置SpringMVC 的servlet  -->
  <servlet>
    <servlet-name>servlet123</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--配置Spring MVC 的配置檔案路徑  -->
    <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>servlet123</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
<!-- 配置編碼過濾器 -->
    <filter>
        <filter-name>encoding</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>
    </filter>
    <filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>
springmvc.xml:


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        ">
        <!-- 配置註解掃描 -->
        <context:component-scan base-package="com.bjsxt.controller"></context:component-scan>
        <!-- 配置解析器 -->
        <mvc:annotation-driven></mvc:annotation-driven>
        <!-- 配置靜態資源放行 -->
        <mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
        <mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
        <mvc:resources location="/images/" mapping="/images/**"></mvc:resources>
        <!-- 配置自定義檢視解析器 -->
         <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/page/"></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><!--設定解析編碼格式  -->
            <property name="maxInMemorySize" value="150000"></property><!--記憶體大小  -->
            <property name="maxUploadSize" value="1024123123"></property><!--檔案大小  -->
       </bean> 
       <!--配置異常解析器  -->
        <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
            <property name="exceptionMappings">
                <props>
                    <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">sizeLimit</prop>
                </props>
            </property>

        </bean>     
 </beans>

細節問題

控制器方法HandlerMethod的配置辦法:

響應字串方式:
原生的響應方式應該是使用ModerAndView 去呼叫jsp .例如:
@RequestMapping("mv")
    public ModelAndView demo4(){
        ModelAndView mv=new ModelAndView("forward:/show.jsp");
        mv.addObject("str", "this is modelAndview");
        return mv;
    }

但是Spring簡化了這個流程,把建立ModerAndView的過程交給了DispatcherServlet來處理。
如果需要存資料,底層用的是Map<String,Obejct>.

 dispatcherServlet 接收到字串後,用字串代替位址列的別名。
forward:/show.jsp        /show.jsp絕對路徑
例子:
@RequestMapping("demo1/aa")
    public String demo(HttpServletRequest req,HttpSession hs){
        System.out.println("使用字串直接響應----請求轉發");
        req.setAttribute("str", "our teacher`s english is good");
        hs.setAttribute("ss", "Springmvc is easy for me");
        return "forward:/show.jsp";
    }

檢視解析器:
WEB-INF資料夾:對於瀏覽器是不可見的。但是請求轉發可以訪問。重定向也不可訪問。
如果使用自定義解析器,返回的字串可以直接寫別名,不用寫.jsp

自定義解析器的好處:
編寫程式碼時,設定跳轉檢視時方便.(控制器方法返回值)

例子:
<!-- 自定義檢視解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 字首 -->
<property name="prefix" value="/WEB-INF/page/"></property>
<!-- 字尾 -->
<property name="suffix" value=".jsp"></property>
</bean>

控制器:@RequestMapping("demo1")
    public String demo1(){
        System.out.println("執行demo1");
        return "demo1";
    }
訪問控制器demo1後會跳轉到/WEB-INF/page/demo1.jsp

如果想轉發到其他單元方法,可以在返回值前新增forward:或redirect:讓系統不執行自定義檢視解析器.執行系統預設檢視解析器,例子:
@RequestMapping("demo2")
    public String demo2(){
        System.out.println("執行demo2");
        return "redirect:demo1";
    }



檔案上傳:
上傳圖片到資料庫問題:
1、把檔案存放到伺服器硬碟上,然後把檔案路徑和檔案資訊存放到資料庫中。
2、把檔案直接以二進位制的形式存放到資料庫中,這種效率比較低,一般推薦使用第一種。
現在流行的都是雲端儲存方式,直接在阿里雲或者騰訊雲的伺服器上的硬碟上儲存。
MIME型別:MIME (Multipurpose Internet Mail Extensions) 是描述訊息內容型別的因特網標準。
MIME 訊息能包含文字、影像、音訊、視訊以及其他應用程式專用的資料。
參考網址:http://www.w3school.com.cn/media/media_mimeref.asp
型別/子型別  副檔名
image/jpeg  jpg

//動態獲取專案根目錄
    File path=new File(this.getServletContext().getRealPath("/images"));
適用於上線階段。
os.flush()的問題:
java在使用流時,都會有一個緩衝區,按一種它認為比較高效的方法來發資料:把要發的資料先放到緩衝區,緩衝區放滿以後再一次性發過去,而不是分開一次一次地發.而flush()表示強制將緩衝區中的資料傳送出去,不必等到緩衝區滿.所以如果在用流的時候,沒有用flush()這個方法,很多情況下會出現流的另一邊讀不到資料的問題,特別是在資料特別小的情況下.

jsp上傳下載複習

jsp:
匯入:commons-fileupload-1.3.2.jar
    commons-io-2.5.jar
  <body>
        <h3>歡迎註冊506班級系統</h3>
        <hr />
        <form action="upload" method="post" enctype="multipart/form-data">    
            使用者名稱: <input type="text"  name="uname" value=""/><br />
            年齡: <input type="text" name="age" value=""/><br />
            頭像: <input type="file" name="photo" value="" /><br />
            <input type="submit"  value="提交"/>
        </form>
  </body>

servlet:

public class UploadServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        //設定請求編碼格式
        req.setCharacterEncoding("utf-8");
        //設定響應編碼格式
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //獲取上傳請求資料
            //建立解析工廠類物件
            FileItemFactory  factory=new DiskFileItemFactory();
            //建立上傳流資料解析物件
            ServletFileUpload upload=new ServletFileUpload(factory);
            //設定解析編碼格式
            upload.setHeaderEncoding("utf-8");
            //設定解析資料的限定大小
            upload.setSizeMax(1024*1024*6);
            //設定單個檔案的限定大小
            upload.setFileSizeMax(1024*1024*3);
            //解析資料
            List<FileItem> fileItems=null;
            try {
                 fileItems = upload.parseRequest(req);
            } catch (FileUploadException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //宣告變數記錄上傳的相關資訊
            String uname="";
            String age="";
            String contentType="";
            String realname="";
            String newName="";
            //遍歷解析資料的List集合
            for(FileItem item:fileItems){
//              System.out.println("獲取資源的型別(普通表單項為null):"+item.getContentType());
//              System.out.println("獲取表單項的name屬性值:"+item.getFieldName());
//              System.out.println("獲取上傳的檔名(普通表單項為null)"+item.getName());
//              System.out.println("獲取資源的大小"+item.getSize());
//              System.out.println("獲取資源的字串資料:"+item.getString("utf-8"));
//              System.out.println("普通表單項值為true,上傳表單項為false:"+item.isFormField());
//              System.out.println("----------------------------------");

                //判斷儲存了上傳資源的FileItem物件
                if(!item.isFormField()){
                    //獲取檔案型別
                        contentType=item.getContentType();
                    //上傳檔案重新命名,避免覆蓋
                        //獲取真實檔名
                         realname=item.getName();
                        System.out.println(realname);
                        //獲取檔案的字尾名
                        String suffixName=realname.substring(realname.lastIndexOf("."));
                        //建立新的檔名
                         newName=System.currentTimeMillis()+""+UUID.randomUUID()+""+suffixName;
                    //校驗檔案上傳型別
                        if(!(".jpg".equals(suffixName) || ".png".equals(suffixName))){
                            resp.getWriter().write("檔案型別不不正確,只接受型別.jpg和.png的圖片");
                            return;
                        }
                    //校驗檔案大小
                        Long size=item.getSize();
                        if(size>1024*1024*5){
                            resp.getWriter().write("檔案大小超出限制,大小限制為5KB");
                            return;
                        }
                    //建立儲存目錄
                        //動態獲取專案根目錄
                        File path=new File(this.getServletContext().getRealPath("/images"));//適用於上線階段
                        //File path=new File("D:/images");//適用於開發階段
                    //判斷並建立指定目錄
                    if(!path.exists()){
                        path.mkdirs();
                    }
                    //建立儲存路徑
                    File realpath=new File(path,newName);
                    //將上傳資源儲存到硬碟中
                    try {
                        item.write(realpath);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }   
                }else{
                    //獲取普通表單項資料
                        if("uname".equals(item.getFieldName())){
                             uname=item.getString("utf-8");
                        }else if("age".equals(item.getFieldName())){
                             age=item.getString("utf-8");
                        }
                }

            }
        //呼叫業務層物件將資料儲存到資料庫中
            UploadService us=new UploadServiceImpl();
            //將資料儲存
            int i=us.insertUploadInfoService(uname, age, contentType, realname, newName);
            //判斷
            if(i>0){
                req.getSession().setAttribute("newName", newName);
                //重定向到主頁面
                resp.sendRedirect("main.jsp");
            }

    }
}
--------------------------------------------------------------------------------
下載:
jsp:
<body>
    <h3>檔案上傳成功,6666,上傳的檔案為:</h3>
    <hr />
    <img src="images/${newName}"  width="300px"/><a href="down?uid=3">下載</a>

  </body>

servlet:

public class DownLoadServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        //設定請求編碼格式
        req.setCharacterEncoding("utf-8");
        //設定響應編碼格式
        resp.setCharacterEncoding("utf-8");

        //獲取請求資訊
        String uid=req.getParameter("uid");
        //處理請求資訊
            //根據UID獲取該使用者的上傳資訊
            DownLoadService ds=new DownLoadServiceImpl();
            Upload p=ds.getUploadInfoService(uid);
            //設定響應檔案型別
            resp.setContentType(p.getContenttype());
            //設定響應頭告訴瀏覽器資源需要下載到客戶端的硬碟中
            System.out.println(p.getRealname());
             resp.setHeader("Content-disposition","attachment;filename="+p.getNewname());
            //獲取要下載的資源的路徑
                String path=this.getServletContext().getRealPath("/images");
            //建立File物件獲取絕對路徑
                File f=new File(path,p.getNewname());
            //獲取資源讀取流物件
                InputStream is=new FileInputStream(f);
            //獲取輸出流物件
                OutputStream os= resp.getOutputStream();
            //將圖片下載給瀏覽器
                IOUtils.copy(is, os);
            //關閉流資源
                is.close();
                os.close();
    }
}

上傳下載小例子

1、匯入相關Jar包,注意得有2個上傳下載相關的包
2、一張圖片
src:
springmvc.xml:

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

        <!--配置註解掃描  -->
        <context:component-scan base-package="com.bjsxt.controller"></context:component-scan>
        <!--配置註解驅動器  -->
        <mvc:annotation-driven></mvc:annotation-driven>
        <!--配置靜態資源放行  -->
        <mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
        <mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
        <mvc:resources location="/images/" mapping="/images/**"></mvc:resources>
        <!--配置自定義檢視解析器  -->
        <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/page/"></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><!--設定解析編碼格式  -->
        <property name="maxInMemorySize" value="150000"></property><!--設定所佔記憶體大小  -->
        <property name="maxUploadSize" value="1024123123"></property><!--設定檔案上傳大小  -->
        </bean>

        <!--配置異常解析器  -->
        <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
        <props>
        <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">sizelimit</prop>
        </props>
        </property>

        </bean>
        </beans>

com.bjsxt.controller:
TestUploadDown.java:

package com.bjsxt.controller;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.aspectj.util.FileUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import sun.reflect.misc.FieldUtil;

@Controller
public class TestUploadDown {
    @RequestMapping("upload")
   public String upload(String uname,String uage,MultipartFile photo) throws IllegalStateException, IOException{
        //將檔案儲存到指定的位置
           //校驗檔案型別
               //獲取檔案字尾名
                   String suffixName=photo.getOriginalFilename().substring(photo.getOriginalFilename().lastIndexOf("."));
               //判斷
                    if(!(".png".equals(suffixName)||".jpg".equals(suffixName))){
                        return "error";
                    }
           //設定檔案大小
           //檔案重新命名
                    String newName=UUID.randomUUID()+""+suffixName;
           //建立儲存路徑
                    File f=new File("c:/images");
                    if(!f.exists()){
                        f.mkdirs();
                    }
                    File f2=new File(f,newName);
            //儲存檔案
                    photo.transferTo(f2);
         //將相關檔案資訊儲存到資料庫中
        //請求轉發到新頁面
      return "success";
      }


    //下載
    @RequestMapping("down")
    public void down(String fileName,HttpServletRequest req,HttpServletResponse resp) throws IOException{
        //設定瀏覽器不解析,直接下載
        resp.setHeader("Content-Disposition", "attachment;filename=abcdef.jpg");
        //設定響應頭
        resp.setContentType("application/octet-stream");
        //獲取要下載的圖片路徑
        String path=req.getServletContext().getRealPath("/images");
        File f=new File(path,fileName);
        //獲取輸出流資源
        OutputStream os=resp.getOutputStream();
        //輸出圖片資源
        os.write(FileUtils.readFileToByteArray(f));
        os.flush();
        os.close();
    }
}

WebContent:
images:1.jpg
web.xml:

<?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">
 <!--配置spring  -->
 <!--配置springmvc   -->
 <servlet>
 <servlet-name>springmvc</servlet-name>
 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 <init-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>classpath:springmvc.xml</param-value>
 </init-param>
 <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
 <servlet-name>springmvc</servlet-name>
 <url-pattern>/</url-pattern>
 </servlet-mapping>

 <!--配置編碼過濾器  -->
 <filter>
 <filter-name>encoding</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>
 </filter>
 <filter-mapping>
 <filter-name>encoding</filter-name>
 <url-pattern>/*</url-pattern>
 </filter-mapping>
</web-app>

upload.jsp:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
  <form action="upload" method="post" enctype="multipart/form-data">
  使用者名稱<input type="text" name="uname" value=""/><br />
 年齡 <input type="text"  name="uage" value=""/><br />
  頭像 <input type="file"  name="photo"/><br />
  <input type="submit" value="提交" /><br />
  </form>
</body>
</html>

down.jsp:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
   <img src="image/1.jpg"  width="200px"/> <a href="down?fileName=1.jpg">點選下載</a>
</body>
</html>

WEB-INF:
page:
success.jsp:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
upload success!
</body>
</html>

error.jsp:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
upload error!
</body>
</html>

sizelimit.jsp:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
upload too big!
</body>
</html>

原始碼:
連結:https://pan.baidu.com/s/12ARPig96QtnaosVVrgxNWQ 密碼:mwdl

小案例

需求分析:
這裡寫圖片描述
這裡寫圖片描述
這裡寫圖片描述
這裡寫圖片描述
資料庫設計:
t_user:

CREATE TABLE `t_user` (
  `uid` int(10) NOT NULL AUTO_INCREMENT,
  `uname` varchar(100) NOT NULL,
  `upwd` varchar(100) NOT NULL,
  PRIMARY KEY (`uid`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

email:

CREATE TABLE `email` (
  `eid` int(10) NOT NULL AUTO_INCREMENT,
  `rid` int(10) NOT NULL,
  `sid` int(10) NOT NULL,
  `title` varchar(100) NOT NULL,
  `content` varchar(1000) NOT NULL,
  `filename` varchar(100) NOT NULL,
  `date` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`eid`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;

1、匯入相關jar包
aopalliance.jar
asm-3.3.1.jar
aspectjweaver.jar
cglib-2.2.2.jar
commons-fileupload-1.3.1.jar
commons-io-2.2.jar
commons-logging-1.1.1.jar
commons-logging-1.1.3.jar
jackson-annotations-2.4.0.jar
jackson-core-2.4.1.jar
jackson-databind-2.4.1.jar
javassist-3.17.1-GA.jar
jstl-1.2.jar
log4j-1.2.17.jar
log4j-api-2.0-rc1.jar
log4j-core-2.0-rc1.jar
mybatis-3.2.7.jar
mybatis-spring-1.2.3.jar
mysql-connector-java-5.1.30.jar
slf4j-api-1.7.5.jar
slf4j-log4j12-1.7.5.jar
spring-aop-4.1.6.RELEASE.jar
spring-aspects-4.1.6.RELEASE.jar
spring-beans-4.1.6.RELEASE.jar
spring-context-4.1.6.RELEASE.jar
spring-core-4.1.6.RELEASE.jar
spring-expression-4.1.6.RELEASE.jar
spring-jdbc-4.1.6.RELEASE.jar
spring-tx-4.1.6.RELEASE.jar
spring-web-4.1.6.RELEASE.jar
spring-webmvc-4.1.6.RELEASE.jar
standard-1.1.2.jar

檔案目錄:
src:
applicationContext.xml:

<?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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        "
        default-autowire="byName"
        >

        <!--配置註解掃描  -->
        <context:component-scan base-package="com.bjsxt.serviceImpl,com.bjsxt.pojo"></context:component-scan>
        <!--配置代理模式為cglib  -->
        <aop:aspectj-autoproxy proxy-target-class="true" ></aop:aspectj-autoproxy>
        <!--配置資料來源檔案掃描  -->
        <context:property-placeholder location="classpath:db.properties"/>
        <!--配置資料來源  -->
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
        </bean>
        <!--配置工廠  -->
        <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean"></bean>
        <!--配置mapper包掃描  -->
       <bean id="mapper" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
       <property name="basePackage" value="com.bjsxt.mapper"></property>
       <property name="sqlSessionFactoryBeanName" value="factory"></property>
       </bean>
       <!--配置事務  -->
         <!--配置事務Bean  -->
         <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"></bean>
         <!--配置事務管理辦法  -->
         <tx:advice id="advice" transaction-manager="transactionManager">
         <tx:attributes>
         <tx:method name="ins*"/>
         <tx:method name="del*"/>
         <tx:method name="up*"/>
         <tx:method name="sel*" read-only="true"/>
         </tx:attributes>
         </tx:advice>
         <!--配置相關事件  -->
         <aop:config>
         <aop:pointcut expression="execution(* com.bjsxt.serviceImpl.*.*(..))" id="my"/>
         <aop:advisor advice-ref="advice" pointcut-ref="my"/>
         </aop:config>
         <!--配置切面  -->
            <!--配置切點bean  -->
            <!--配置通知bean  -->
            <!--織入形成切面  -->
         <!--配置其他bean  -->
        </beans>

springmvc.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
        <!--配置註解掃描  -->
        <context:component-scan base-package="com.bjsxt.controller"></context:component-scan>
        <!--配置mvc註解驅動  -->
        <mvc:annotation-driven></mvc:annotation-driven>
        <!--配置靜態資源方式  -->
        <mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
        <mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
        <mvc:resources location="/images/" mapping="/images/**"></mvc:resources>

        <!--配置自定義檢視解析器  -->
        <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/email/"></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>
        <property name="maxInMemorySize" value="150000"></property>
        <property name="maxUploadSize" value="1024123123"></property>
        </bean>
        <!--配置異常解析器  -->
        <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
        <props>
        <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">sizeLimit</prop>
        </props>
        </property>
        </bean>
        </beans>

db.properties:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=root

log4j.properties:


log4j.rootCategory=info,LOGFILE



log4j.logger.com.bjsxt.mapper=debug, CONSOLE
log4j.logger.com.bjsxt.advice=debug, CONSOLE
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=- %c-%d-%m%n


log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=C:/BiZhi/axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=- %c-%d-%m%n

com.bjsxt.controller:
EmailController.java:

package com.bjsxt.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import com.bjsxt.pojo.Email;
import com.bjsxt.pojo.User;
import com.bjsxt.service.EmailService;

@Controller
public class EmailController {
    //宣告業務層物件
    @Resource
    private EmailService emailServiceImpl;
    //登入檢測
    @RequestMapping("login")
    public String login(String uname,String upwd,HttpServletRequest req){
        //呼叫業務層物件
        User user = emailServiceImpl.checkUserInfo(uname, upwd);
        if(user!=null){
            req.getSession().setAttribute("user", user);
            return "redirect:main";
        }else{
            req.setAttribute("str", "賬號或密碼錯誤,請重新輸入");
            return "forward:/login.jsp";
        }
    }
    //主頁面顯示
    @RequestMapping("main")
    public String main(HttpServletRequest req){
        //獲取當前使用者ID
        int uid=((User)req.getSession().getAttribute("user")).getUid();
        //調取業務層處理資料
        List<Email> lm=emailServiceImpl.selEmailInfo(uid);
        //返回響應頁面
        req.setAttribute("lm", lm);
        return "main";
    }
    //公共轉發方法
    @RequestMapping("{path}")
    public String restful(@PathVariable String path){
        return path;
    }

    //傳送郵件
    @RequestMapping("s")
    public String send(int rid,String title,String content,MultipartFile photo,HttpServletRequest req) throws IllegalStateException, IOException{
        //儲存圖片
           //判斷檔案型別
            //獲取檔案字尾名
             String suffixName=photo.getOriginalFilename().substring(photo.getOriginalFilename().lastIndexOf("."));
             //判斷檔案型別
             if(!(".jpg".equals(suffixName)||".png".equals(suffixName))){
                 return "error";
             }
           //檔案重新命名
             String newName=UUID.randomUUID()+suffixName;
           //建立儲存路徑
             File f=new File(req.getServletContext().getRealPath("/images"),newName);
             photo.transferTo(f);
        //儲存圖片資訊到資料庫
            //獲取當前使用者ID
             int uid=((User)req.getSession().getAttribute("user")).getUid();
             //處理資料
            int i=  emailServiceImpl.insertEmail(rid, uid, title, content, newName);
            if(i>0){
                //將檔名存到作用域中
                req.setAttribute("newName", newName);
                //返回結果
                return "success";
            }
        return "error";
    }

}

com.bjsxt.mapper:
EmailMapper.java

package com.bjsxt.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Select;

import com.bjsxt.pojo.Email;
import com.bjsxt.pojo.User;

public interface EmailMapper {
    //驗證使用者名稱密碼
    User checkUserInfo(String uname,String upwd);

    //根據ID獲取email資訊
    List<Email> selEmailInfo(int rid);

    //插入傳送信件資訊
    int insertEmail(int rid,int sid,String title,String content,String filename);
}

EmailMapper.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

  <mapper namespace="com.bjsxt.mapper.EmailMapper">
  <!--根據賬號密碼查詢使用者資訊  -->
  <select id="checkUserInfo" resultType="com.bjsxt.pojo.User">
  select * from t_user where uname=#{0} and upwd=#{1}
  </select>
  <!--根據賬戶ID查詢郵件資訊  -->
  <resultMap type="com.bjsxt.pojo.Email" id="rm">
  <id column="eid" property="eid"/>
  <result column="rid" property="rid"/>
  <result column="sid" property="sid"/>
  <result column="title" property="title"/>
  <result column="content" property="content"/>
  <result column="filename" property="filename"/>
  <result column="date" property="date"/>
  <association property="user" javaType="com.bjsxt.pojo.User">
  <id column="uid" property="uid"/>
  <result column="uname" property="uname"/>
  <result column="upwd" property="upwd"/>
  </association>
  </resultMap>
  <select id="selEmailInfo" resultMap="rm">
    select * from email e
    join t_user t
    on e.sid=t.uid
    where rid=#{0}
  </select>
  <!--插入信件資訊  -->
  <insert id="insertEmail">
  insert into email values(default,#{0},#{1},#{2},#{3},#{4},now())
  </insert>
  </mapper>

com.bjsxt.pojo:
User.java:

package com.bjsxt.pojo;

public class User {
  private int uid;
  private String uname;
  private String upwd;
public User() {
    super();
    // TODO Auto-generated constructor stub
}
public User(int uid, String uname, String upwd) {
    super();
    this.uid = uid;
    this.uname = uname;
    this.upwd = upwd;
}
public int getUid() {
    return uid;
}
public void setUid(int uid) {
    this.uid = uid;
}
public String getUname() {
    return uname;
}
public void setUname(String uname) {
    this.uname = uname;
}
public String getUpwd() {
    return upwd;
}
public void setUpwd(String upwd) {
    this.upwd = upwd;
}
@Override
public String toString() {
    return "User [uid=" + uid + ", uname=" + uname + ", upwd=" + upwd + "]";
}
@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + uid;
    result = prime * result + ((uname == null) ? 0 : uname.hashCode());
    result = prime * result + ((upwd == null) ? 0 : upwd.hashCode());
    return result;
}
@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    User other = (User) obj;
    if (uid != other.uid)
        return false;
    if (uname == null) {
        if (other.uname != null)
            return false;
    } else if (!uname.equals(other.uname))
        return false;
    if (upwd == null) {
        if (other.upwd != null)
            return false;
    } else if (!upwd.equals(other.upwd))
        return false;
    return true;
}

}

Email.java:

package com.bjsxt.pojo;

public class Email {
  private int eid;
  private int rid;
  private int sid;
  private String title;
  private String content;
  private String filename;
  private String date;
  private User user;
public Email() {
    super();
    // TODO Auto-generated constructor stub
}
public Email(int eid, int rid, int sid, String title, String content, String filename, String date, User user) {
    super();
    this.eid = eid;
    this.rid = rid;
    this.sid = sid;
    this.title = title;
    this.content = content;
    this.filename = filename;
    this.date = date;
    this.user = user;
}
public int getEid() {
    return eid;
}
public void setEid(int eid) {
    this.eid = eid;
}
public int getRid() {
    return rid;
}
public void setRid(int rid) {
    this.rid = rid;
}
public int getSid() {
    return sid;
}
public void setSid(int sid) {
    this.sid = sid;
}
public String getTitle() {
    return title;
}
public void setTitle(String title) {
    this.title = title;
}
public String getContent() {
    return content;
}
public void setContent(String content) {
    this.content = content;
}
public String getFilename() {
    return filename;
}
public void setFilename(String filename) {
    this.filename = filename;
}
public String getDate() {
    return date;
}
public void setDate(String date) {
    this.date = date;
}
public User getUser() {
    return user;
}
public void setUser(User user) {
    this.user = user;
}
@Override
public String toString() {
    return "Email [eid=" + eid + ", rid=" + rid + ", sid=" + sid + ", title=" + title + ", content=" + content
            + ", filename=" + filename + ", date=" + date + ", user=" + user + "]";
}
@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((content == null) ? 0 : content.hashCode());
    result = prime * result + ((date == null) ? 0 : date.hashCode());
    result = prime * result + eid;
    result = prime * result + ((filename == null) ? 0 : filename.hashCode());
    result = prime * result + rid;
    result = prime * result + sid;
    result = prime * result + ((title == null) ? 0 : title.hashCode());
    result = prime * result + ((user == null) ? 0 : user.hashCode());
    return result;
}
@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Email other = (Email) obj;
    if (content == null) {
        if (other.content != null)
            return false;
    } else if (!content.equals(other.content))
        return false;
    if (date == null) {
        if (other.date != null)
            return false;
    } else if (!date.equals(other.date))
        return false;
    if (eid != other.eid)
        return false;
    if (filename == null) {
        if (other.filename != null)
            return false;
    } else if (!filename.equals(other.filename))
        return false;
    if (rid != other.rid)
        return false;
    if (sid != other.sid)
        return false;
    if (title == null) {
        if (other.title != null)
            return false;
    } else if (!title.equals(other.title))
        return false;
    if (user == null) {
        if (other.user != null)
            return false;
    } else if (!user.equals(other.user))
        return false;
    return true;
}

}

com.bjsxt.service:
EmailService.java:

package com.bjsxt.service;

import java.util.List;

import com.bjsxt.pojo.Email;
import com.bjsxt.pojo.User;

public interface EmailService {
   //驗證使用者名稱和密碼
    User checkUserInfo(String uname,String upwd);
    //根據ID獲取郵件資訊
    List<Email> selEmailInfo(int rid);

    //插入傳送信件資訊
    int insertEmail(int rid,int sid,String title,String content,String filename);
}

com.bjsxt.serviceImpl:
EmailServiceImpl.java:

package com.bjsxt.serviceImpl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.bjsxt.mapper.EmailMapper;
import com.bjsxt.pojo.Email;
import com.bjsxt.pojo.User;
import com.bjsxt.service.EmailService;
@Service
public class EmailServiceImpl implements EmailService{
    //宣告mapper介面物件
    @Resource
    private EmailMapper emailMapper;
   //驗證使用者名稱和密碼
    @Override
    public User checkUserInfo(String uname, String upwd) {
        return emailMapper.checkUserInfo(uname, upwd);
    }
    //根據ID獲取郵件資訊
    @Override
    public List<Email> selEmailInfo(int rid) {
        return emailMapper.selEmailInfo(rid);
    }

    @Override
    public int insertEmail(int rid, int sid, String title, String content, String filename) {
        return emailMapper.insertEmail(rid, sid, title, content, filename);
    }

}

WebContent:
login.jsp:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>登入頁面</title>
</head>
<body>
<form action="login" method="get">
  使用者名稱 <input type="text"  name="uname" value=""/><br />
  密碼 <input type="password" name="upwd" value="" /><br />
  <input type="submit" value="登入"/></form>
 <span> ${str}</span>
</body>
</html>

images資料夾
WEB-INF:
web.xml:

<?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">
  <!--配置Spring  -->
  <!--配置applicationContext,xml的路徑  -->
  <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <!--配置監聽器  -->
  <listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>
  <!--配置SpringMVC 的servlet  -->
  <servlet>
    <servlet-name>servlet123</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--配置Spring MVC 的配置檔案路徑  -->
    <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>servlet123</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <!--配置編碼過濾器  -->
  <filter>
  <filter-name>encoding</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>
  </filter>
  <filter-mapping>
  <filter-name>encoding</filter-name>
  <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

email:
error.jsp:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
error  upload!
</body>
</html>

main.jsp:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<a href="send">傳送郵件</a>
<table cellpadding="0" cellspacing="0" border=" solid 1px">
    <tr height="30px">
        <td width="200px">標題</td>
        <td width="200px">時間</td>
        <td width="200px">傳送人</td>
    </tr>
    <c:forEach items="${lm}" var="e">
    <tr>
        <td>${e.title}</td>
        <td>${e.date}</td>
        <td>${e.user.uname}</td>
    </tr>
    </c:forEach>

</table>
</body>
</html>

send.jsp;

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<form action="s" method="post" enctype="multipart/form-data">
收件人: <input type="text" name="rid"/><br />
主題: <input type="text" name="title" /><br />
正文: <textarea name="content" id="" cols="30" rows="10"></textarea><br />
附件: <input type="file" name="photo" /><br />
    <input type="submit" value="提交" /><br />
</form>
</body>
</html>

sizeLimit.jsp:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
 上傳檔案超出限制。
</body>
</html>

success.jsp:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
success  upload!
<a href="main">點選跳轉</a> 主頁面
上傳檔案為 <img src="images/${newName}" alt="" />
</body>
</html>

原始碼:
連結:https://pan.baidu.com/s/1eq5PoUs_NzCXdUUzYMGdUA 密碼:w2yb

小案例總結

技能點1:
  Mysql資料庫   :timestamp  時間戳      
    顯示日期加時間
  java  pojo 類  用String date存。
 now()  表示當前系統時間,  是日期加時間。
技能點2:

公共跳轉方法:
利用restful:            {page}接收的是請求名d'd  Localhost:8080/專案名/請求名

@RequestMapping("{page}")
public String goPage(@PathVariable String page){
    return page;
}      
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/page/"></property>
    <property name="suffix" value=".jsp"></property>
</bean>  

作業知識點整理:
    1、使用restful宣告公共單元方法,主要是用來進行頁面的請求轉發的。
    @RequestMapping("{path}")
    public String getJsp(@PathVariable String path){
        System.out.println("1111");
        return path;
    }
    2、靜態資源儲存到WEB-INF資料夾,則需要在springmvc.xml中的 
          靜態資源放行對映路徑中加上WEB-INF
        <mvc:resources location="/WEB-INF/js/" mapping="/js/**"></mvc:resources>
            <mvc:resources location="/WEB-INF/css/" mapping="/css/**"></mvc:resources>
            <mvc:resources location="/WEB-INF/images/" mapping="/images/**"></mvc:resources>

模擬郵箱:
    需求分析:
        功能分析:
            登入功能
            主頁面顯示郵件資訊功能
            傳送郵件功能
        資料庫設計:
            使用者表t_user 
                              使用者ID
                              使用者名稱
                  密碼
            郵件表  email
                郵件ID
                收件人
                發件人
                主題
                正文
                時間
                附件
                   將使用者ID作為  發件人和收件人的ID
        技術分析:
            SpringMVC+spring+mybatis+jsp+js+html+css+jquery+ajax
        功能分析:
            搭建SSM執行環境
            登入功能:
                點選登入傳送請求到伺服器的servlet
                    ----------------------------------------->servlet
                        根據請求地址尋找單元方法
                        呼叫單元方法
                        接受返回值
                        請求轉發或者重定向
                            ----------------------------------->controller
                                建立單元方法
                                宣告形參
                                處理請求
                                    呼叫業務層物件校驗使用者登入資訊
                                成功
                                    將使用者資訊儲存到session中
                                    重定向到main.jsp
                                失敗
                                    請求轉發到登入頁面
                                        -------------------------------->service
                                            建立業務方法
                                            宣告形參
                                            呼叫mapper物件查詢使用者資訊
                                            返回結果
                                                ------------------------------->mapper
                                                        建立mapper.xm檔案
                                                        建立介面


小結

springmvc的響應
springmvc的檢視解析器
springmvc的上傳和下載
springmvc的編碼過濾器
web.xml和springmvc最新
細節問題
jsp上傳下載複習
上傳下載小例子
小案例
小案例總結

相關文章