SpringMVC

SpringMVC

SpringMVC流程圖示

SpringMVC 是一種基于 Java 的實現(xiàn) MVC 設(shè)計模型的請求驅(qū)動類型的輕量級 Web 框架(完善的注解體系是特色)


2021-04-14_112325.jpg
2021-04-14_094713.jpg

特有行為要自己描述,其他由Spring框架封裝好,藍(lán)色框就是Spring容器

SpringMVC快速入門

需求:客戶端發(fā)起請求,服務(wù)器端接收請求,執(zhí)行邏輯并進(jìn)行視圖跳轉(zhuǎn)

  • 步驟

1.導(dǎo)入SpringMVC相關(guān)坐標(biāo)

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.0.5.RELEASE</version>
</dependency>

2.配置SpringMVC核心控制器DispatherServlet

web.xml中配置
<!--配置SpringMVC的前端控制器-->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--加載spring-mvc.xml文件-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

3.創(chuàng)建Controller類和視圖頁面
4.使用注解配置Controller類中業(yè)務(wù)方法的映射地址

UserController類
@Controller
public class UserController {
    @RequestMapping("/quick")//請求映射
    public String save(){
        System.out.println("Controller save running....");
        return "success.jsp";//寫跳轉(zhuǎn)視圖的名字
    }
}
-------------------------------------------------
再在webapp下創(chuàng)建需要跳轉(zhuǎn)到的頁面 success.jsp

5.配置SpringMVC核心文件spring-mvc.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: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/context
       http://www.springframework.org/schema/context/spring-context.xsd">
     <!--先添加3行Context命名空間-->
     <!--Controller的組件掃描-->
    <context:component-scan base-package="com.itheima.controller"/>
</beans>

6.客戶端發(fā)起請求測試


2021-04-14_111947.jpg

工件部署失敗解決方法
https://blog.csdn.net/new_buff_007/article/details/89476581

SpringMVC組件解析

SpringMVC執(zhí)行流程

2021-04-14_112824.jpg

SpringMVC中@RequestMapping
用于建立請求URL和處理請求方法之間的對應(yīng)關(guān)系

  • 位置:
    1.類上,請求URL 的第一級訪問目錄。此處不寫的話,就相當(dāng)于應(yīng)用的根目錄
    2.方法上,請求 URL 的第二級訪問目錄,與類上的使用@ReqquestMapping標(biāo)注的一級目錄一起組成訪問虛擬路徑
@Controller
@RequestMapping("/xxx")
public class UserController {
    //此時請求地址:http://localhost:8080/user/quick
    @RequestMapping("/quick")//請求映射
    public String save(){
        System.out.println("Controller save running....");
        return "/success.jsp";//寫跳轉(zhuǎn)視圖的名字
        // 加/代表在user下找資源,否則在8080下找資源
    }
}
  • 屬性:
    value:用于指定請求的URL。它和path屬性的作用是一樣的
    method:用于指定請求的方式
    params:用于指定限制請求參數(shù)的條件。它支持簡單的表達(dá)式。要求請求參數(shù)的key和value必須和配置的一模一樣
@RequestMapping(value="/quick",method = RequestMethod.POST,params = {"username"})
訪問方式:locahost:8080/user/quick?username

只能以Post方法請求,也由get等其他方法
params = {"username"},表示請求參數(shù)必須有accountName
params = {"moeny!100"},表示請求參數(shù)中money不能是100

SpringMVC注解解析組件掃描

<!--方式1-->
<context:component-scan base-package="com.itheima.controller"/>
<!--方式2-->
<context:component-scan base-package="com.itheima">
    <context:include-filter type="annotation" 
              expression="org.springframework.stereotype.Controller"/>
    <!--include-filter代表包含此注釋,exclude-filter代表不包含此注釋-->
</context:component-scan>

spring-mvc.xml配置解析

<!--配置內(nèi)部資源視圖解析器-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--/jsp/xxx.jsp-->
        <property name="prefix" value="/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
 </bean>
在spring-mvc.xml進(jìn)行此配置,作用于返回視圖時
之后return "xxx" 時,實際是return "/jsp/xxx.jsp"

SpringMVC數(shù)據(jù)響應(yīng)方式

方式1:頁面跳轉(zhuǎn)

直接返回字符串
此種方式會將返回的字符串與視圖解析器的前后綴拼接后跳轉(zhuǎn)

return "index";
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
此時轉(zhuǎn)發(fā)資源地址/WEB-INF/views/index.jsp

轉(zhuǎn)發(fā):forward:/WEB-INF/views/index.jsp(WEB-INF文件夾不能被顯示訪問)
重定向:redirect:/index.jsp
通過ModelAndView對象返回

在success.jsp文件里,有${username},等待ModelAndView或String給其返回值
    @RequestMapping(value="/quick2")//請求映射
    public ModelAndView save2(){
        /*
        Model:模型 作用封裝數(shù)據(jù)
        View:視圖 作用展示數(shù)據(jù)
         */
        ModelAndView modelAndView = new ModelAndView();
        //設(shè)置模型數(shù)據(jù)
        modelAndView.addObject("username","itcast");
        //設(shè)置視圖名稱
        modelAndView.setViewName("success");
        return modelAndView;
    }

    //springmvc對方法上的參數(shù)可以提供相應(yīng)注入
    @RequestMapping(value="/quick3")//請求映射
    public ModelAndView save3(ModelAndView modelAndView){
        modelAndView.addObject("username","itheima");
        modelAndView.setViewName("success");
        return modelAndView;
    }
    
    //Model是SpringMVC提供的對象
    @RequestMapping(value="/quick4")//請求映射
    public String save4(Model model){
        model.addAttribute("username","邵子朋");
        return "success";
    }

    //requests是原生javaweb的對象
    @RequestMapping(value="/quick5")//請求映射
    public String save5(HttpServletRequest request) {
        request.setAttribute("username","Nobility");
        return "success";
    }

方式2:回寫數(shù)據(jù)

直接返回字符串
Web基礎(chǔ)階段:客戶端訪問服務(wù)器端,直接回寫字符串作為響應(yīng)體返回,只需使用
response.getWriter().print("hello world")即可

Controller中回寫字符串

  • 通過SpringMVC框架注入的response對象,使用response.getWriter().print("hello world")回寫數(shù)據(jù),此時不需要視圖跳轉(zhuǎn),業(yè)務(wù)方法返回值為void
 @RequestMapping(value="/quick6")
    public void save6(HttpServletResponse response) throws IOException {
        response.getWriter().print("hello itcast");
        //在網(wǎng)頁上打印hello itcast
    }
  • 將需要回寫的字符串直接返回,但此時需要通過@ResponseBody注解告知SpringMVC框架,方法返回的字符串不是視圖跳轉(zhuǎn)而是直接在http響應(yīng)體中返回(重要)
@RequestMapping(value="/quick7")
    @ResponseBody
    public String save7() throws IOException {
        return "hello itheima";
    }

返回json格式對象,前提是先導(dǎo)入3個依賴

    @RequestMapping(value="/quick8")
    @ResponseBody
    public String save8() throws IOException {
        return "{\"username\":\"zhangsan\",\"age\":18}";//返回json對象
    }

    @RequestMapping(value="/quick9")
    @ResponseBody//因為返回的json仍是串,必須保留
    public String save9() throws IOException {
        User user = new User();
        user.setUsername("list");
        user.setAge(30);
        //導(dǎo)入json包,使用json轉(zhuǎn)換工具,將對象轉(zhuǎn)換為json格式字符串再返回
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(user);
        return json;//優(yōu)化save8輸出json的方式
    }

返回對象或集合

  • 返回對象或集合方式1
@RequestMapping(value="/quick10")
@ResponseBody//組織進(jìn)行跳轉(zhuǎn)
//期望SpringMVC自動將User轉(zhuǎn)換為json格式字符串
public User save10() throws IOException {
        User user = new User();
        user.setUsername("lisi");
        user.setAge(30);
        return user;//優(yōu)化save8輸出json的方式
}
------------------------------------------------------------------------
spring-mvc.xml文件中配置
<!--配置處理器映射器-->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
            </list>
        </property>
</bean>
  • 返回對象或集合方式2
    方式1配置比較麻煩,配置的代碼比較多,因此,可以使用mvc的注解驅(qū)動代替上述配置。
spring-mvc.xml文件中
-------------------------------------------------------------------------
命名空間添加
xmlns:mvc="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
-------------------------------------------------------------------------
配置文件添加
<!--mvc的注解驅(qū)動-->
<mvc:annotation-driven/>

在 SpringMVC 的各個組件中
處理器映射器、處理器適配器、視圖解析器稱為 SpringMVC 的三大組件。
使用<mvc:annotation-driven>自動加載
RequestMappingHandlerMapping(處理映射器)RequestMappingHandlerAdapter(處理適配器)
在Spring-xml.xml配置文件中使用,<mvc:annotation-driven>替代注解處理器和適配器配置。
同時使用<mvc:annotation-driven>默認(rèn)底層就會集成jackson進(jìn)行對象或集合的json格式字符串的轉(zhuǎn)換

?著作權(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)容

  • 夜鶯2517閱讀 128,155評論 1 9
  • 版本:ios 1.2.1 亮點: 1.app角標(biāo)可以實時更新天氣溫度或選擇空氣質(zhì)量,建議處女座就不要選了,不然老想...
    我就是沉沉閱讀 7,451評論 1 6
  • 我是黑夜里大雨紛飛的人啊 1 “又到一年六月,有人笑有人哭,有人歡樂有人憂愁,有人驚喜有人失落,有的覺得收獲滿滿有...
    陌忘宇閱讀 8,835評論 28 54
  • 兔子雖然是枚小碩 但學(xué)校的碩士四人寢不夠 就被分到了博士樓里 兩人一間 在學(xué)校的最西邊 靠山 兔子的室友身體不好 ...
    待業(yè)的兔子閱讀 2,767評論 2 9

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