spring mvc 搭建步驟 使用maven 環(huán)境
- 新建maven project 跛梗,名字為test
- 打開pom.xml 文件碍遍,添加springmvc jar包
如圖:點(diǎn)擊add渺尘,輸入springmvc 搜索,選擇spring-webmvc
Paste_Image.png
搜索結(jié)果為0的解決辦法:
window/show view/找到maven respositor,顯示旗芬,
選擇Global Respositories/central/
右鍵點(diǎn)擊update Index瘤睹,等待更新完成升敲。
Paste_Image.png
- 在web.xml中加入 springmvc 攔截器
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
- 新建文件spring-servlet.xml在WEB-INF下面
<?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:tx="http://www.springframework.org/schema/tx" 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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 配置掃描的包 -->
<context:component-scan base-package="com.springdemo.*" />
<!-- 注冊(cè)HandlerMapper、HandlerAdapter兩個(gè)映射類 -->
<mvc:annotation-driven />
<!-- 訪問靜態(tài)資源 -->
<mvc:default-servlet-handler />
<!-- 視圖解析器 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
- 在 src/main/resources
下面新建類DemoController 包名為:com.springdemo.controller
(包名與spring-servlet.xml中配置相同轰传,放置control層代碼)
package com.springdemo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class DemoController {
@RequestMapping("/index")
public String index(){
return "demo";
}
}
- 新建jsp頁面,在WEB-INF下新建文件夾 view 获茬,在里面新建名字為demo.jsp的文件
內(nèi)容為:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>首頁</title>
</head>
<body>
<h1>This is SpringMVC Demo</h1>
</body>
</html>
- 此時(shí):
這樣發(fā)布在tomcat下面港庄,class文件沒有,需要修改src/main/resources里面 Exclude中锦茁,點(diǎn)擊remove攘轩,使其變?yōu)閚one,重新發(fā)布就有文件了
Paste_Image.png
訪問項(xiàng)目路徑:
http://127.0.0.1:8080/test/index 出現(xiàn)頁面,則表示成功