SpiringMVC快速入门以及SpringMVC简介
SpringMVC概述
SpringMVC 是一种基于java的实现MVC设计模型的请求驱动类型的轻量web框架,属于SoringFrameWork的后续产品,已经融合SpringWebFlow中.
SpringMVC已经成为目前最主流的MVC框架之一,并且随着Spring3.0的发布,全面超越Struts2,成为最优秀的MVC框架.他通过一套注解,让一个简单的java类成为处理请求的控制器,而不需要实现任何接口.同时它还支持RESTful编程风格的请求
SpringMVC快速入门
需求:客户端发起请求,服务端接受请求,知性逻辑并进行视图跳转
开发步骤
1.导入SpringMVC相关坐标
2.配置SpringMVC核心控制器DispathcerServlet
3.创建Controller类和视图页面
4.使用注解配置Controller类中业务方法的映射地址
5.配置SpringMVC核心文件spring-mvc.xml
6.客户端发起请求测试
代码实现
1.在pom.xml中导入Spring和SpringMVC的坐标,导入Servlet和jsp的坐标
<!--Spring坐标-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<!--SpringMVC坐标-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId
<version>5.0.5.RELEASE</version>
</dependency>
<!--Servlet坐标-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<!--Jsp坐标-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
</dependency>
2.在web.xml中配置SpringMVC的核心控制器
<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:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
3.创建Controller和业务方法
public class ControllerTest{
public String ControllerMethod(){
System.out.println("ControllerMethod运行了....");
}
}
4.创建视图页面创建index.jsp
<html>
<body>
<h4>Hello SpringMVC!</h4>
</body>
</html>
5.配置注解
@Controller
@RequestMapping
public class UserController {
@RequestMapping("/usercontroller")
public String save(){
System.out.println("usercontroller运行了!!!");
return"index";
}
}
6.创建spring-mvc.xml
<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">
<!--配置注解扫描-->
<context:component-scan base-package="这里填你的总包名"/>
</beans>
7.访问测试地址
//请求地址 http://localhost:8080/usercontroller
控制台打印
页面显示