詳解SpringMVC的兩種實(shí)現(xiàn)方式
一、方法一:實(shí)現(xiàn)Controller接口
這個(gè)在我的第一個(gè)SpringMVC程序中已經(jīng)學(xué)習(xí)過了,在此不作贅述,現(xiàn)在主要來學(xué)習(xí)第二種方法,使用注解開發(fā);
二、方法二:使用注解開發(fā)
1.導(dǎo)包
2.在web.xml中配置DispatcherServlet
3.建立一個(gè)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注解驅(qū)動(dòng) 能夠幫助我們完成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.建立一個(gè)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"; } }
可以看到,在這個(gè)類中,我們使用到了兩種注解。
第一個(gè)是@Controller,使用這個(gè)注解就說明這個(gè)類是一個(gè)Handler;第二個(gè)是@RequestMapping,看名字就知道這是請求的映射,也就是我們需要請求的路徑,這里是請求.../hello。
可以看見一個(gè)返回String的方法,返回的這個(gè)hello就說明跳轉(zhuǎn)的路徑是視圖解析器中的“前綴”+hello+“后綴”,在這里也就是/WEB-INF/jsp/hello.jsp。
這里我們用一個(gè)model來存儲(chǔ)數(shù)據(jù)。
5.啟動(dòng)tomcat測試
到此這篇關(guān)于SpringMVC的兩種實(shí)現(xiàn)方式的文章就介紹到這了,更多相關(guān)SpringMVC實(shí)現(xiàn)方式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java中關(guān)于泛型、包裝類及ArrayList的詳細(xì)教程
泛型可以在類或方法中預(yù)支地使用未知的類型。這篇文章主要介紹了Java中關(guān)于泛型、包裝類及ArrayList的詳細(xì)教程,需要的朋友可以參考下2021-12-12springboot整合rocketmq實(shí)現(xiàn)分布式事務(wù)
大多數(shù)情況下很多公司是使用消息隊(duì)列的方式實(shí)現(xiàn)分布式事務(wù)。 本篇文章重點(diǎn)講解springboot環(huán)境下整合rocketmq實(shí)現(xiàn)分布式事務(wù),感興趣的可以了解一下2021-05-05Java判斷一個(gè)時(shí)間是否在當(dāng)前時(shí)間區(qū)間代碼示例
這篇文章主要給大家介紹了關(guān)于使用Java判斷一個(gè)時(shí)間是否在當(dāng)前時(shí)間區(qū)間的相關(guān)資料,在日常開發(fā)中我們經(jīng)常會(huì)涉及到時(shí)間的大小比較或者是判斷某個(gè)時(shí)間是否在某個(gè)時(shí)間段內(nèi),需要的朋友可以參考下2023-07-07Spring的事件機(jī)制知識點(diǎn)詳解及實(shí)例分析
在本篇內(nèi)容里小編給大家分享的是一篇關(guān)于Spring的事件機(jī)制知識點(diǎn)詳解及實(shí)例分析,有需要的朋友么可以參考下。2021-12-12