spring-mvc入門配置
阿新 • • 發佈:2020-12-30
建controller.java
package com.gao.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
//會去找這個檔案裡的東西
//@RequestMapping("/HelloController")
public class HelloController {
//真實訪問地址 : 專案名/HelloController/hello
@RequestMapping("/hello")
public String sayHello(Model model){
//向模型中新增屬性msg與值,可以在JSP頁面中取出並渲染
model.addAttribute("msg","hello,SpringMVC");
//這個return 就是跳轉到hello.jst web-inf/jsp/hello.jsp
return "hello" ;
}
}
建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
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 自動掃描包,讓指定包下的註解生效,由IOC容器統一管理 -->
<context:component-scan base-package="com.gao.controller"/>
<!-- 讓Spring MVC不處理靜態資源 -->
<mvc:default-servlet-handler />
<!--
支援mvc註解驅動
在spring中一般採用@RequestMapping註解來完成對映關係
要想使@RequestMapping註解生效
必須向上下文中註冊DefaultAnnotationHandlerMapping
和一個AnnotationMethodHandlerAdapter例項
這兩個例項分別在類級別和方法級別處理。
而annotation-driven配置幫助我們自動完成上述兩個例項的注入。
-->
<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>
建web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--1.註冊Servlet-->
<servlet>
<servlet-name>springMvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--通過初始化引數指定SpringMVC配置檔案的位置,進行關聯-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<!--啟動級別-1-->
<load-on-startup>1</load-on-startup>
</servlet>
<!--/ 匹配所有的請求;(不包括.jsp)-->
<!--/* 匹配所有的請求;(包括.jsp)-->
<servlet-mapping>
<servlet-name>springMvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
在WEB-INF裡建包 放入xxx.jst 簡單入門