SpringMVC框架

springMVC

SpringMVC:前端控制器,映射器,適配器,控制器,試圖解析器

前端控制器

前端控制器在web.xml中配置

  
  <servlet>
  <!-- 命名 -->
    <servlet-name>springmvc</servlet-name>
    <!-- 加載包中的前端控制器 -->
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 讓服務(wù)器已啟動就開始加載文件springMVC.xml,用的是contextConfigLocation這個屬性 -->
    <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>
  <!-- 對應(yīng)上面的命名 -->
    <servlet-name>springmvc</servlet-name>
    <!-- 對文件進行攔截來執(zhí)行上面的程序, "/"代表攔截所有的-->
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  

兩種映射器

    <!-- 映射器 -->                    
   <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>
   <!-- 映射器2 -->
   <bean class=" org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
            <!-- 這里的值要和控制器中的id相對應(yīng) -->
                <prop key="/text1">text</prop>
                <prop key="/text1">text</prop>
            </props>
        </property>
   </bean>


兩種適配器

   <!-- 適配器  要實現(xiàn)Controller接口-->
   <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>
   <!-- 適配器2 要實現(xiàn) HttpRequestHandler接口 -->
   <bean class=" org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter"></bean>

控制器

   <!-- 控制器 -->
   <bean class="com.hemi.controller.MyController"  name="/text" id="text"></bean>
public class MyController implements org.springframework.web.servlet.mvc.Controller{

    @Override
    public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception {      
        String username = req.getParameter("username");
        String password = req.getParameter("password");
//      req.setAttribute("username", username);
//      req.setAttribute("password", password);
        ModelAndView view = new ModelAndView();
        if("lisi".equals(username)&&"123".equals(password)){
            view.setViewName("Hello.jsp");
        }
        else{
            view.setViewName("login.jsp");
        }
                
        return view;
    }

}

視圖解析器

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"></bean>

視圖解析器的配置前綴后綴

   <!-- 視圖解析器 -->
   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
   <!-- 前綴 -->
   <property name="prefix" value="/"></property>
   <!-- 后綴 -->
   <property name="suffix" value=".jsp"></property>
   </bean>
    

注解適配器和映射器

注解適配器和映射器要一起使用才有效

     <!-- 掃描包 -->
   <context:component-scan base-package="com.hemi.controller"></context:component-scan>


   <!-- 配置注解 1-->
        <!-- 配置映射器注解 -->
   <bean class=" org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping "></bean>
        <!-- 配置適配器注解 -->
   <bean class=" org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean>

    <!--配置注解2-->
    <!-- 終極替換上面的注解 -->
    <mvc:annotation-driven></mvc:annotation-driven>

Controller里使用注解

@Controller
public class TextControler{
    @RequestMapping(show1)
    public ModelAndView show1(){}
}

cotroller里面返回數(shù)據(jù)

ModleAndView類型返回值 返回值用一般用view保存使用 view.addObject方法(域?qū)ο笠部梢裕?/p>

    @RequestMapping("show1")
    public ModelAndView show1(HttpServletRequest req){
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        ModelAndView view = new ModelAndView();
        view.addObject("username", username);
        view.addObject("password", password);       
        view.setViewName("Hello");
        return view;        
    }

String類型返回值返回數(shù)據(jù)可以域?qū)ο?,Modle以及ModleMap來保存數(shù)據(jù)

    @RequestMapping("show2")
    public String show2(Model model,HttpServletRequest req){
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        model.addAttribute("username", username);
        model.addAttribute("password", password);
        return "Hello";     
    }

void類型返回值要用域?qū)ο髞肀4鏀?shù)據(jù)

    @RequestMapping("show3")
    public void show3(HttpServletRequest req,HttpServletResponse resp){
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        req.setAttribute("username", username);
        req.setAttribute("password", password);
        try {
            req.getRequestDispatcher("Hello.jsp").forward(req, resp);
        } catch (ServletException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

參數(shù)綁定

簡單參數(shù)綁定 pojo參數(shù)綁定,自定義類型

簡單參數(shù)綁定:傳入的數(shù)據(jù)和jsp中寫入request中的數(shù)據(jù)參數(shù)相同,如果想用形參則使用注解@RequestParam("username")是取值 String name是取得別名

Pojo參數(shù)綁定:定義一個實體類和jsp中放入的數(shù)據(jù)類型相同,然后傳入實體類可以獲得參數(shù)

自定義類型: 創(chuàng)建一個轉(zhuǎn)換類實現(xiàn)Converter<String, Date>接口 重寫里面的方法進行轉(zhuǎn)換,在springMVC.xml中配置將org.springframework.format.support.FormattingConversionServiceFactoryBean類引入里面注入轉(zhuǎn)換類,在注解驅(qū)動的屬性中用conversion-service將配置的類加載驅(qū)動中,在實體類需要轉(zhuǎn)換類型的字段(日期)上面添加 @DateTimeFormat(pattern="yyyy-MM-dd")

自定義轉(zhuǎn)換類:

public class DateConvert implements Converter<String, Date>{

    @Override
    public Date convert(String source) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return format.parse(source);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

}

springMVC中配置

    <mvc:annotation-driven conversion-service="conversionService">          
    </mvc:annotation-driven>
        
    <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <list>
                <bean class="com.hemi.controller.convert.DateConvert"></bean>
            </list>         
        </property>
        
    </bean>

User實體類中配置

 private String username;
 private String password;
 @DateTimeFormat(pattern="yyyy-MM-dd")
 private Date date;

控制器:

    @RequestMapping("show4")
    public String show4(Model model,User user){
        model.addAttribute("user", user);
        return "Hello";     
    }
}

參數(shù)綁定-數(shù)組,包裝數(shù)據(jù)類型 list集合

login.jsp:

    <form action="show5" method="post">
        用戶名:<input type="text" name="username"><br> 
        密碼:<input type="password" name="password"> <br>
        日期<input type="text" name="date"><br>
        <!--傳遞list集合中裝的是多個地址對象-->
        <input type="text" placeholder="請輸入地址" name="add[0].addres"><br> 
        <input type="text" placeholder="請輸入編碼" name="add[0].code"><br> 
        <input type="text" placeholder="請輸入地址" name="add[1].addres"><br> 
        <input type="text" placeholder="請輸入編碼" name="add[1].code"><br> 
        <!--傳遞單個地址的實體對象-->
        <input type="text" placeholder="請輸入地址" name="add.addres"><br> 
        <input type="text" placeholder="請輸入編碼" name="add.code"><br> 
        <!--傳遞一個數(shù)組-->
        <input type="checkbox" name="hobby" value="basketball">籃球<br>
        <input type="checkbox" name="hobby" value="football">籃球<br>
        <input type="checkbox" name="hobby" value="tennis">網(wǎng)球
        <input type="submit" value="登錄">
    </form>

user類:

 private String username;
 private String password;
 @DateTimeFormat(pattern="yyyy-MM-dd")
 private Date date;
 private List<Address> add;
 private String[] hobby;

控制器:

    @RequestMapping("show5")
    public String show5(Model model,User user){
        model.addAttribute("user", user);
        return "Hello";     
    }

全局異常處理開發(fā):

1、自定義異常類
2、自定義異常處理器實現(xiàn) HandlerExceptionResolver接口
3、在springmvc配置文件中配置全局異??刂破?/p>

自定義異常類:

public class CustomException extends Exception{
    private String msg;
        
    public CustomException(String msg) {
        super(msg);
        this.msg = msg;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
    
    
    
}

自定義異常處理器:

public class ExceptionHandler implements HandlerExceptionResolver{

    @Override
    public ModelAndView resolveException(HttpServletRequest req, HttpServletResponse resp, Object object,
            Exception ex) {
        CustomException customException=null;
        if (ex instanceof CustomException) {
            customException=(CustomException)ex;
        }else{
            customException=new CustomException("未知錯誤");
        }
        ModelAndView view = new ModelAndView();
        view.addObject("error", customException);
        view.setViewName("error");
        return view;
    }

}

springMVC的配置

<!-- 定義全局異常 -->
    <bean class="com.hemi.exception.handler.ExceptionHandler"></bean>

靜態(tài)資源的釋放

在配置文件中進行配置

    <!-- 靜態(tài)資源釋放-->
    <mvc:resources location="/image/" mapping="/image/*.*"></mvc:resources>

文件上傳的步驟

1、編寫配置文件

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

2、編寫控制器
上傳單個文件:

    public String upload(MultipartFile file,HttpServletRequest req) throws IllegalStateException, IOException{
        if(file==null){
            return "uploadFile";            
        }
        //取出文件名
        String filename = file.getOriginalFilename();
        //根據(jù)文件的虛擬入境找到真實入境
        String path = req.getServletContext().getRealPath("/temp");
          File file2 = new File(path);
          if (!file2.exists()) {
            //創(chuàng)建目錄
            file2.mkdirs();
        }
          //將傳入的文件按照真實入境和文件名寫出來
        file.transferTo(new File(file2,filename));
        return "success";       
    }

批量上傳文件

    @RequestMapping("/upload1")
    public String upload1(MultipartFile[] file,HttpServletRequest req) throws IllegalStateException, IOException{
        if (file.length==0) {
            return "uploadFile";
        }
        for (MultipartFile multipartFile : file) {
            String filename = multipartFile.getOriginalFilename();
            String realPath = req.getServletContext().getRealPath("/team");
            File file2 = new File(realPath);
            if (!file2.exists()) {
                file2.mkdirs();
            }
            multipartFile.transferTo(new File(file2,filename));         
        }
        return "success";
    }

3、編寫前端表單頁面
注意:把form表單的默認的enctype 類型改成 enctype="multipart/form-data"

    <form action="upload" method="post" enctype="multipart/form-data">
    請上傳文件:<input type="file" name="file">
        <br>
        <input type="submit" value="upload">
    </form> 
    <hr>
    <form action="upload1" method="post" enctype="multipart/form-data">
    請上傳文件:<input type="file" name="file">
        <br>
        請上傳文件:<input type="file" name="file">
        <br>
        <input type="submit" value="upload1">
    </form> 
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,609評論 19 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 47,275評論 6 342
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,139評論 25 708
  • 今天和白莞聊天,我說特別想寫個故事。我寫這個故事不是為了治愈這些年來自己心上的傷痛,有些東西就是想寫而已,理由什么...
    深藍不會寫小說閱讀 422評論 0 2
  • 身邊壽命比較長的老人并不多,見過最長的,是我外婆的父親,活了100多歲,然后在某天悄無聲息地離開了人世。 中國人的...
    哈皮小森閱讀 631評論 0 1

友情鏈接更多精彩內(nèi)容