目录
一,什么是springMVC?
springmvc是spring框架的一种分支。SpringMVC 是类似于 Struts2 的一个 MVC 框架,在实际开发中,==接收浏览器的请求响应,对数据进行处理,然后返回页面进行显示==,但是上手难度却比 Struts2 简单多了。而且由于 Struts2 所暴露出来的安全问题,SpringMVC 已经成为了大多数企业优先选择的框架。
二,简单实例创建运行操作
(1)创建一个web工程
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">
</web-app>
(2)在文件pom.xml中引入springmvc的依赖。
<!--maven可以把该依赖相关的依赖都引入。-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
加入依赖以后一定要记得右上角刷新哦
加入依赖后,可快捷创建spring.xml
(3) 创建控制层。
代码如下:
@Controller
public class HelloController {
@RequestMapping("/hello") //根据请求路径映射响应的方法。
public String hell(){
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~hello五月拾一------------------");
return "hello01.jsp"; //springmvc默认把返回的字符串作为响应的网页帮你进行转发。
}
}
前端创建hell01.jsp,
(4)配置springmvc的配置文件。
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--1.包扫描 扫描我们自己的控制层类所在的包或者父包-->
<context:component-scan base-package="com.kkl.controller"/>
</beans>
(5)引入前端控制器 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>
<servlet>
<servlet-name>springmvc01</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--加载springmvc的配置文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
</servlet>
<!--servlet映射路径
/: 表示所有的控制层路径 以及静态资源
/*: 表示全部 包含jsp网页
-->
<servlet-mapping>
<servlet-name>springmvc01</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
(6)测试
三,多参,视图解析器,静态资源处理
1.多参
创建HelloController02控制层。
@Controller
@RequestMapping("/hello02") //表示该类中所有请求都是以hello02开始
public class HelloController02 {
//@RequestParam: value设置接受的参数名称。required:该参数不是必须 defaultValue:默认值
@RequestMapping("/a")
public String hello03(
@RequestParam(value="ids",required = false,defaultValue ="33") int id, String name){ //方法的参数名必须和请求时携带的参数名相同。springmvc才会给该参数赋值。
System.out.println("id======="+id+";name====="+name);
return "index02";
}
@RequestMapping("/b")
public String hello04(User user){ //把接受的参数封装到该实体类对象中。springmvc。
System.out.println(user);
return "index02";
}
}
比如:表单提交时 注册 添加。
解决: 可以把所有的请求参数封装到一个实体类对象中。
日期类型参数:
2. 静态资源处理
什么是静态资源: 比如: css, js, img,html