SpringMVC基本環境搭建(配置檔案模板模板)

常家壯發表於2020-10-17

導包:

 <build>
      <plugins>
          <!-- 設定編譯版本為1.8 -->
          <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-compiler-plugin</artifactId>
              <version>3.1</version>
              <configuration>
                  <source>1.8</source>
                  <target>1.8</target>
                  <encoding>UTF-8</encoding>
              </configuration>
          </plugin>
      </plugins>
  </build>
      <!-- 匯入依賴-->  
  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.1.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>

建立一個 spring-mvc.xml 檔案

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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.itheima.controller"/>
    
    <!-- 配置檢視解析器(可寫可不寫)-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
		
</beans>

web.xml 中配置:

<!--MVC配置-->
	<servlet>
		<servlet-name>springMvc</servlet-name>
<!--配置前端控制器-->
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring-mvc.xml</param-value>
		</init-param>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>springMvc</servlet-name>
		<!--/* 代表所有的請求都會進入到前端控制器中,包含jsp
		/  代表所有的請求都會進入到前端控制器中,不包含jsp
		*.itcast   代表以 .itcast結尾的請求都會進入到前端控制器中-->
		<url-pattern>/</url-pattern>
	</servlet-mapping>

相關文章