Spring Mvc的基本使用搭建

Spring MVC

spring Mvc的核心是servlet,是基於spring的框架,在它的基礎上加了很多web的對象,和sssh中truts2的作用是一樣的

第一步:導入依賴

<!--springMVC的依賴-->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>5.1.5.RELEASE</version>
</dependency>

第二步:在web.xml中

<!--springMVC的核心servlet-->
<servlet>
  <servlet-name>springmvc</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <!--加載spring的配置文件-->
  <init-param>
    <param-name>contextConfigLocation</param-name>
    <!--springmvc.xml是springMvc的配置文件-->
    <param-value>classpath:springmvc.xml</param-value>
  </init-param>
</servlet>
<servlet-mapping>
  <servlet-name>springmvc</servlet-name>
  <url-pattern>*.action</url-pattern>
</servlet-mapping>

第三步:新建springmvc的配置文件 springmvc.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">

<!--配置註解掃描-->
<context:component-scan base-package="com.ywy.controller">
</context:component-scan>

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

第四步:新建一個控制器測試Controller

//標明這個類是一個控制類
@Controller
public class UserController {
	
	//提供這個方法的外部請求路徑
	@RequestMapping("/TestAll")
	public String TeatAll(){
   	 System.out.println("測試成功");
   	 }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章