目标
- 实现第一个SpringMVC项目
- 实现控制台打印HelloSpringMVC,并且跳转到成功页面
思路
- 搭建好Maven项目结构
- 在webapp里面的index.jsp页面编写超链接标签
- 在resources文件里面存放配置文件spring-mvc.xml
- 编写控制器类,实现超链接跳转的控制事务
项目结构如下:
index.jsp
<a href="user/hello">点击</a><br>
spring-mvc.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">
<!-- 配置spring创建容器时要扫描的包 -->
<context:component-scan base-package="cn.xys"></context:component-scan>
<!-- 配置视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 文件所在的目录-->
<property name="prefix" value="/WEB-INF/pages/"></property>
<!-- 文件的后缀名-->
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 配置spring开启注解mvc的支持-->
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
注意:这里在spring-mvc.xml里面配置的视图解析器可以方便后期的所定义的view路径可以简化
@Controller
@RequestMapping(path = "/user")//将RequestMapping部署到类上
public class HelloController {
@RequestMapping("/hello")
public String sayhello(){
System.out.println("helloSpringMvc");
return "success";
}
}
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!-- 配置编码过滤器-->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!-- 初始化参数-->
<init-param><param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<!--拦截前端页面中的所有请求,并交给CharacterEncodingFilter编码过滤器类来处理-->
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<-- 配置前端控制器-->
<servlet>
<servlet-name>dispatcherServlet</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>
<!-- 启动服务器就可以创建这个DispatcherServlet对象-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
接下来就是演示功能阶段了,配置好项目的Tomcat,并运行
当我们点击的时候控制台会输出HelloSpringMVC,并且页面会跳向成功页面,即(success.jsp页面)
控制台输出为: