Demo的结构:
-
准备jar包,上面项目结构的jar 包请自行准备;
-
创建resources根目录,在里面创建spring mvc 的配置文件:springmvc.xml
根目录创建方法:resources 目录右键:
-
springmvc.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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--1配置类扫描器-->
<context:component-scan base-package="com.hao.springmvc"/>
<!--2.配置注解驱动,可以使用springmvc的注解-->
<mvc:annotation-driven/>
<!--3.配置视图解析器,解析路径“/”不能丢-->
<bean class="org.springframework.web.servlet.view.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">
<!--配置前端控制器 (分发处理各种请求)-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--配置读取核心配置文件springmvc.xml-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!--代表当前servlet(DispatcherServlet)对象,随tomcat启动,创建servlet对象
1代表优先级,必须式正整数,最小就是1-->
<load-on-startup>1</load-on-startup>
</servlet>
<!--配置servlet映射路径<url-pattern>/</url-pattern>"/"代表拦截所有路径-->
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
- index.jsp 首页
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页</title>
<style>
a{
text-decoration: none;
}
</style>
</head>
<body>
<a href="helloWord/hello?name=chen,pass=123">点击进入SpringMVC入门案例</a>
</body>
</html>
- controller:HelloController.java
package com.hao.springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller //该注解一般针对控制器层
@RequestMapping("helloWord")
public class HelloController {
//此方法可以通过浏览器输入地址直接访问
@RequestMapping(value = "/hello", method = RequestMethod.GET,params = {"name=chen,pass=123"})
public String helloWord(){
System.out.println("OK!欢迎来到SpringMVC");
return "hello";//页面跳转
}
}
- 跳转后的页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>跳转后的页面</title>
</head>
<body>
OK!欢迎来到SpringMVC页面!!!!!!
</body>
</html>