spring mvc 搭建步骤 使用maven 环境
- 新建maven project ,名字为test
- 打开pom.xml 文件,添加springmvc jar包
如图:点击add,输入springmvc 搜索,选择spring-webmvc
Paste_Image.png搜索结果为0的解决办法:
window/show view/找到maven respositor,显示,
选择Global Respositories/central/
右键点击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.*" />
<!-- 注册HandlerMapper、HandlerAdapter两个映射类 -->
<mvc:annotation-driven />
<!-- 访问静态资源 -->
<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的文件
内容为:
<%@ 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>
- 此时:
这样发布在tomcat下面,class文件没有,需要修改src/main/resources里面 Exclude中,点击remove,使其变为none,重新发布就有文件了
访问项目路径:
http://127.0.0.1:8080/test/index 出现页面,则表示成功
网友评论