springMVC_day01_概念_入门_@RequestMapping注解_参数封装与绑定_编码过滤器
1. mybatis: 持久层轻量级开源框架二、三层架构和MVC设计模式
crud , 一对一映射,一对多,多对多,延迟加载(懒加载:lazy),缓存(一级缓存:sqlSession级别,二级缓
存:SqlSessionFactory级别(应用级别)):xml和注解实现
2. spring: 表现在业务层,解耦和事务管理
两大核心:IOC:控制反转,包含了依赖注入和依赖查找
AOP: 面向切面编程(面向多个对象编程 )引用:声明式事务管理,日志管理,spring security安全
框架
aop中的重点:声明式事务管理 -- xml ,ann
a、三层架构三、springMVC的概念
web层-- 表现层: 处理用户的请求和相应
技术:servlet
service层:业务层, 编写业务,处理业务逻辑,编写事务
技术:spring
dao层:持久层,数据的增删改查
技术:jdbc -- dbutils -- jdbcTemplate -- mybatis(主流) -- spring data jpa(趋势)
b、mvc设计模式
M:model --模型: pojo类,封装数据 , 广义上说:dao + service + model = 业务模型层
V:view -- 视图: jsp,html,freemarker:展示数据, 广义上讲:只要能展示数据就是视图
C:cotroller --控制层:servlet :处理用户的请求和相应
1. springMVC是spring体系中的一个子项目四、SpringMVC的HelloWorld(重点)1、引入依赖
2. springMVC是开源的轻量级框架
3. springMVC是满足了mvc设计的模式的一个表现层框架
4. 表现层框架大多都满足了MVC设计模式
pom.xml
注意:两个scope限制都要加上
<dependencies>2、spring-mvc.xml配置
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--spring的核心-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<!--springmvc的jar-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<!--两个scope限制都要加上 否则一运行就报错说不是一个servlet tomcat里也有这两个jar包冲突了-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<!--
maven 项目执行分为三个阶段
编译(需要) 测试(需要) 运行(不需要)
provided : 编译器生效,测试生效,运行不生效
servlet-api ,jsp-api:这两个包,需要配置依赖范围为provided ,其他都不需要
-->
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<?xml version="1.0" encoding="UTF-8"?>3、web.xml
<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 http://www.springframework.org/schema/context/spring-context.xsd">
<!--开启注解 扫描包-->
<context:component-scan base-package="cn.ahpu"></context:component-scan>
<!--内部资源视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--配置前缀-->
<property name="prefix" value="/WEB-INF/"></property>
<!--配置后缀-->
<property name="suffix" value=".jsp"></property>
<!--配好后:
return "/WEB-INF/show.jsp";
可以简写为
return "show";
-->
</bean>
</beans>
<!DOCTYPE web-app PUBLIC4、自定义核心控制类
"-//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:前端控制器
springmvc只有一个servlet
-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--servlet中配置局部参数:读取配置文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<!--在启动tomcat时创建servlet对象-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<!--
/ 拦截所有请求:包括http请求,静态资源请求(img,css,js)
/* 拦截请求:不包含静态资源
*.do , *.action : 通配符配置 拦截以do action结尾的请求 思想来源于Struts2
-->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
TestController.java
@Controller5、页面配置
public class TestController {
@RequestMapping("/test")
public String test(){
System.out.println("测试成功!");
return "show";//本来是return "/WEB-INF/show.jsp"; 因为配置了内部资源视图解析器
}
}
index.jsp
注意:isELIgnored=“false” 不忽略el表达式 修改IDEA默认的jsp文件模板
<%@ page isELIgnored="false" contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--isELIgnored="false" 不忽略el表达式--%>
<a href="${pageContext.request.contextPath}/test">请求1</a><%--404--%>
<a href="/test">请求2</a><%--500--%>
</body>
</html>
show.jsp
随意显示一行文本即可
1. @RequestMapping 请求路径映射,该注解可以标记在方法上,也可以标记在类上
标记在类上用来窄化路径
2. 属性
path:指定请求路径,别名value,所以属性名可以省略 (path={"/hello","/hello2"} 指定多个路径 完全没必要)
method: 请求方式:
get: 路径和超链接请求都是默认get请求
post: 必须在表单中实现
params:声明请求路径的规则 -- ==了解==
"name":路径中必须有name
"age>20":路径中必须有age>20
"!name" :路径中不能存在name
eg:实例
TestController.java
@Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping(value="/hello",method = RequestMethod.POST,params = {"name","age>20"})
public String hello(){
System.out.println("测试成功!");
return "show";//本来是return "/WEB-INF/show.jsp"; 因为配置了内部资源视图解析器
}
}
index.jsp
<body>
<%--isELIgnored="false" 不忽略el表达式--%>
<a href="${pageContext.request.contextPath}/test/hello">请求1</a><%--404--%>
<a href="/test/hello">请求2</a><%--500--%>
<hr>
<form action="${pageContext.request.contextPath}/test/hello?age>20" method="post">
<input type="text" name="name"> <%--没属性name会报400错误 ?age>20也是必要的--%>
<input type="submit">
</form>
</body>
1. 表单中提交的name值与方法中的参数(简单类型)名称一致,就可以直接获取到八、编码过滤器(重点) 解决中文乱码post请求
就是直接在controller类的方法内直接写上需要接受的参数即可 ★框架会自动进行类型转换
2. 方法的参数:pojo类型 (也是直接作为方法参数接受)
只要保证表单提交的name值与pojo的属性名一致,就可以封装数据
集合数据的封装 格式见下面代码
3. @RequestParam:请求参数绑定,name与参数名不一致时需要进一步绑定
属性: value, name可以指定页面表单中的name值
requird: 是否必须的 , false ,不必要的(可有可无), true:必须有该参数
defaultValue: 默认值,如果页面传参了,则使用页面传参的值,如果没有指定,则使用默认值
public String testParam2(@RequestParam("username") String name){//username封装到name里
4. 特殊情况:(自定义类型转换器)要转换类型是Date类型
1)自定义类型转换类
/**
* 自定义类型转换器
* 将字符串格式转换为日期格式
* 1. 实现接口 converter<S,T>
* S:源类型 T:目标类型
*/
public class StringToDateConverter implements Converter<String,Date> {
/**
* 类型转换方法
* @param source 源类型
* @return 目标类型
*/
@Override
public Date convert(String source) {
//sdf可以将日期转换为指定格式字符串 也可以将指定格式字符串转换为日期
SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
Date date=null;
try {
date=sdf.parse(source);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
2. 在springmvc.xml文件中配置类型转换工厂
<!--配置类型转换工厂-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<!--框架自己转换不了的类型会到这里来找类转换-->
<bean class="cn.ahpu.converter.StringToDateConverter"></bean>
</set>
</property>
</bean>
3. 在注解驱动中引入类型转换工厂 (还是spring-mvc.xml)
<!--注解驱动: 关联类型转换工厂-->
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
web.xml里配置下springmvc提供的编码处理过滤器即可
<!--编码过滤器-->get请求
<filter>
<filter-name>CharactorEncoding</filter-name>
<!--springmvc框架内置的乱码处理类 配置一下即可-->
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!--配置初始化参数 指定编码格式-->
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharactorEncoding</filter-name>
<!--拦截所有请求:不包含静态资源-->
<url-pattern>/*</url-pattern>
</filter-mapping>
get 请求方式:七八代码demo总理xmlpom.xml
tomacat 对 GET 和 POST 请求处理方式是不同的, GET 请求的编码问题, 要改 tomcat 的 server.xml
配置文件,如下:
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
改为:
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" edirectPort="8443" useBodyEncodingForURI="true"/>
<dependencies>web.xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
</dependency>
</dependencies>
<!DOCTYPE web-app PUBLICspring-mvc.xml
"-//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>CharactorEncoding</filter-name>
<!--springmvc框架内置的乱码处理类 配置一下即可-->
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!--配置初始化参数 指定编码格式 拦截的是post请求-->
<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>
<filter-mapping>
<filter-name>CharactorEncoding</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:spring-mvc.xml</param-value>
</init-param>
<!--配置tomcat启动顺序-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
<?xml version="1.0" encoding="UTF-8"?>domain
<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: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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--扫描包-->
<context:component-scan base-package="cn.ahpu"></context:component-scan>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--配置类型转换工厂-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<!--框架自己转换不了的类型会到这里来找类转换-->
<bean class="cn.ahpu.converter.StringToDateConverter"></bean>
</set>
</property>
</bean>
<!--注解驱动 关联类型转换工厂-->
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
</beans>
Role.java
@Data
public class Role {
private Integer id;
private String roleName;
}
User.java
@Datacontroller
public class User {
private Integer id;
private String username;
private Character sex;
private Integer age;
private List<String> list;
private Role role;
private List<Role> roleList;
private Map<String,Object> map;
//注解pom.xml内加上lombok包
}
UserController.java
@Controllerconverter 特殊类型自己转换
@RequestMapping("/user")
public class UserController {
//1.简单类型参数的获取 直接写成方法参数即可
@RequestMapping(value = "/testParam",method = RequestMethod.POST)
public String testParam(String username,Integer age,Character sex){
//直接在方法内写参数就能接受了 哈哈
System.out.println(username);
System.out.println(age);
System.out.println(sex);
return "show";
}
//2.pojo类型参数封装 前端name值和pojo的属性名一致即可 也能直接写成方法参数
@RequestMapping(value = "/saveUser",method = RequestMethod.POST)
public String saveUser(User user){
//javabean类型参数也可以直接写成方法参数 强
System.out.println(user);
return "show";
}
//3.参数绑定复杂情况 前端name与controller方法参数名不同 需要进一步进行绑定
@RequestMapping(value = "/testParam2",method = RequestMethod.POST)
public String testParam2(@RequestParam(value = "username",required = false,defaultValue = "hza") String name){//username封装到name里
System.out.println(name);
return "show";
}
//4.更特殊 自定义类型转换器
@RequestMapping("/testDate")
public String testDate(Date birthday){
System.out.println(birthday);
return "show";
}
}
StringToDateConverter.java
/**JSP
* @author 寒面银枪
* @create 2020-04-26 14:47
*
* 自定义类型转换器
* 将字符串格式转换为日期格式
* 1. 实现接口 converter<S,T>
* S:源类型 T:目标类型
*/
public class StringToDateConverter implements Converter<String,Date> {
/**
* 类型转换方法
* @param source 源类型
* @return 目标类型
*/
@Override
public Date convert(String source) {
//sdf可以将日期转换为指定格式字符串 也可以将指定格式字符串转换为日期
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Date date=null;
try {
date=sdf.parse(source);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
index.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/4/26
Time: 13:30
To change this template use File | Settings | File Templates.
--%>
<%@ page isELIgnored="false" contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
简单参数:<br>
<form action="${pageContext.request.contextPath}/user/testParam" method="post">
姓名:<input type="text" name="username"><br/>
年龄:<input type="text" name="age"><br/>
性别:<input type="text" name="sex"><br/>
<input type="submit" value="提交">
</form>
<hr>
pojo参数 集合 集合嵌套:<br>
<form action="${pageContext.request.contextPath}/user/saveUser" method="post">
姓名:<input type="text" name="username"><br/>
年龄:<input type="text" name="age"><br/>
性别:<input type="text" name="sex"><br/>
list集合参数: <input type="text" name="list[0]"> <%--原来前端可以指定数组类型参数单个元素的顺序--%>
<input type="text" name="list[1]"><br/>
user内有另一个jaavBean:role 也可以直接写el表达式
id:<input type="text" name="role.id">
rolename:<input type="text" name="role.roleName"><br/>
user内有roleList:<br/>
[0] id:<input type="text" name="roleList[0].id"> rolename:<input type="text" name="roleList[0].roleName"><br>
[1] id:<input type="text" name="roleList[1].id"> rolename:<input type="text" name="roleList[1].roleName"><br>
<%--直接写name=map[key] 数组形式即可--%>
Map集合:<input type="text" name="map[one]"> <input type="text" name="map[two]"><input type="text" name="map[xxx]">
<input type="submit" value="提交">
</form>
<hr>
参数绑定特殊情况 前端name与后端参数名不一致:<br>
<form action="${pageContext.request.contextPath}/user/testParam2" method="post">
<input type="text" name="username"><br>
<input type="submit" value="提交">
</form>
<hr>
更特殊情况:参数类型为日期类型:<br>
<form action="${pageContext.request.contextPath}/user/testDate" method="post">
<input type="date" name="birthday"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
show.jsp
<%@ page isELIgnored="false" contentType="text/html;charset=UTF-8" language="java" %>小结
<html>
<head>
<title>Title</title>
</head>
<body>
跳转成功
</body>
</html>
1. springmvc第一天
springmvc的介绍:实现mvc设计模式的轻量级开源的表现层框架
springmvc的入门
1) 引入依赖
spring-context.jar ,spring-webmvc.jar , servlet-api.jar, jsp-api.jar
2) 配置文件 spring-mvc.xml
扫描包,创建类对象
视图解析器: 前缀和后缀
注解驱动:加载了处理映射器,处理适配器, 可以引入自定义类型转换器
3) web.xml
前端控制器:DispactherServlet:配置一个参数:contextConfiglocation=classpath:spring-mvc.xml
编码过滤器:CharacterEncodingFilter : 配置一个参数:encoding=utf-8
4) 自定义控制器
TestController
类:@Controller, 创建类型对象 @RequestMapping("/path"):映射类的路径
方法: @RequestMapping("/path"):映射方法的路径
5) 页面
@RequestMapping
@RequestParam:
传参:简单类型:参数名必须与表单name一致
pojo类:属性名必须与表单name一致
集合类型
自定义类型转换器
1) 实现了Converter<S,T>接口的实现类
2) 定义类型转换器的工厂: ConversionServiceFactoryBean,注入Set集合
3) 在注解驱动中引如类型转换工厂
编码过滤器
web.xml :
版权声明
本文仅代表作者观点,不代表博信信息网立场。