1. 程式人生 > >SpringMVC01-->SpringMVC框架環境搭建(註解方式)

SpringMVC01-->SpringMVC框架環境搭建(註解方式)

掃描 ota images 導入 ram pri context resources 幫助

1.導入jar包

技術分享圖片

2.在web.xml中配置前端控制器DispatcherServlet

  2.1 如果不配置<init-param>,則默認找/WEB-INF/<servlet-name>-servlet.xml.配置<init-param>是為了改變默認加載的配置文件名稱和路徑

  

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <!-- 配置前端控制器 --> <servlet> <servlet-name>jqk</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</
servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <
servlet-mapping> <servlet-name>jqk</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>

3.在src下新建springmvc.xml

  3.1 引入xmlns:mvc命名空間(可以在spring幫助文檔的/spring-framework-4.1.6.RELEASE-dist/spring-framework-4.1.6.RELEASE/docs/spring-framework-reference/htmlsingle中搜索)

  

<?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:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 掃描註解 -->
<context:component-scan
base-package="com.bjsxt.controller"></context:component-scan>
<!-- 註解驅動 -->
<!--
org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandler
Mapping -->
<!--
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerA
dapter -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 靜態資源 -->
<mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
<mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
<mvc:resources location="/images/"
mapping="/images/**"></mvc:resources>
</beans>

4.編寫控制器類

  

@Controller
public class DemoController {
@RequestMapping("demo")
public String demo(){
System.out.println("執行 demo");
return "main.jsp";
}
@RequestMapping("demo2")
public String demo2(){
System.out.println("demo2");
return "main1.jsp";
}
}

SpringMVC01-->SpringMVC框架環境搭建(註解方式)