詳解SpringMVC的兩種實現(xiàn)方式
一、方法一:實現(xiàn)Controller接口
這個在我的第一個SpringMVC程序中已經(jīng)學習過了,在此不作贅述,現(xiàn)在主要來學習第二種方法,使用注解開發(fā);
二、方法二:使用注解開發(fā)
1.導包
2.在web.xml中配置DispatcherServlet
3.建立一個Spring配置文件springmvc-servlet.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" xmlns:mvc="http://www.springframework.org/schema/mvc" 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.jms.controller"/> <!--讓springMVC不處理靜態(tài)資源--> <mvc:default-servlet-handler/> <!-- 支持MVC注解驅動 能夠幫助我們完成BeanNameUrlHandlerMapping和SimpleControllerHandlerAdapter注入 --> <mvc:annotation-driven/> <!--視圖解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver"> <!--前綴--> <property name="prefix" value="/WEB-INF/jsp/"/> <!--后綴--> <property name="suffix" value=".jsp"/> </bean> </beans>
4.建立一個HelloController類
package com.jms.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class HelloController { @RequestMapping("/hello") public String hello(Model model) { model.addAttribute("message", "歡迎來到SpringMVC"); return "hello"; } }
可以看到,在這個類中,我們使用到了兩種注解。
第一個是@Controller,使用這個注解就說明這個類是一個Handler;第二個是@RequestMapping,看名字就知道這是請求的映射,也就是我們需要請求的路徑,這里是請求.../hello。
可以看見一個返回String的方法,返回的這個hello就說明跳轉的路徑是視圖解析器中的“前綴”+hello+“后綴”,在這里也就是/WEB-INF/jsp/hello.jsp。
這里我們用一個model來存儲數(shù)據(jù)。
5.啟動tomcat測試
到此這篇關于SpringMVC的兩種實現(xiàn)方式的文章就介紹到這了,更多相關SpringMVC實現(xiàn)方式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
springboot整合rocketmq實現(xiàn)分布式事務
大多數(shù)情況下很多公司是使用消息隊列的方式實現(xiàn)分布式事務。 本篇文章重點講解springboot環(huán)境下整合rocketmq實現(xiàn)分布式事務,感興趣的可以了解一下2021-05-05