我们的开发架构一般都是基于两种形式,一种是 C/S 架构,也就是客户端/服务器,另一种是 B/S 架构,也就是浏览器服务器。在 JavaEE 开发中,几乎全都是基于 B/S 架构的开发。那么在 B/S 架构中,系统标准的三层架构包括:表现层、业务层、持久层。三层架构在我们的实际开发中使用的非常多,所以我们课程中的案例也都是基于三层架构设计的。
三层架构中,每一层各司其职,接下来我们就说说每层都负责哪些方面:
表现层: 即web层。它负责接收客户端请求,向客户端响应结果,通常客户端使用http协议请求web 层, web 需要接收 http 请求,完成 http 响应。
表现层包括展示层和控制层:控制层负责接收请求,展示层负责结果的展示。
表现层依赖业务层,接收到客户端请求一般会调用业务层进行业务处理,并将处理结果响应给客户端。
表现层的设计一般都使用 MVC 模型。(MVC 是表现层的设计模型,和其他层没有关系)
业务层: 即 service 层。它负责业务逻辑处理,和我们开发项目的需求息息相关。 web 层依赖业务层,但是业务层不依赖 web 层。业务层在业务处理时可能会依赖持久层,如果要对数据持久化需要保证事务一致性。(也就是我们说的,事务应该放到业务层来控制)
持久层: 即 dao 层。负责数据持久化,包括数据层即数据库和数据访问层,数据库是对数据进行持久化的载体,数据访问层是业务层和持久层交互的接口,业务层需要通过数据访问层将数据持久化到数据库中。通俗的讲,持久层就是和数据库交互,对数据库表进行曾删改查的。
MVC 全名是 Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,是一种用于设计创建 Web 应用程序表现层的模式。
MVC 中每个部分各司其职:
Model(模型) : 通常指的就是我们的数据模型,JavaBean的类。作用一般情况下用于封装数据。
View(视图) : 通常指的就是我们的 jsp 或者 html。作用一般就是展示给用户数据的。通常视图是依据模型数据创建的。
Controller(控制器) : 是应用程序中处理用户交互的部分。 作用一般就是处理程序逻辑的(用来接收用户的请求,整个流程的控制器。用来进行数据校验等。)。它相对于前两个不是很好理解,这里举个例子:
我们要保存一个用户的信息,该用户信息中包含了姓名,性别,年龄等等。这时候表单输入要求年龄必须是 1~100 之间的整数。姓名和性别不能为空。并且把数据填充到模型之中。
此时除了 js 的校验之外,服务器端也应该有数据准确性的校验,那么校验就是控制器的该做的。
当校验失败后,由控制器负责把错误页面展示给使用者。
如果校验成功,也是控制器负责把数据填充到模型,并且调用业务层实现完整的业务需求。
SpringMVC 是一种基于 Java 的实现 MVC 设计模型的请求驱动类型的轻量级 Web 框架, 属于 Spring FrameWork 的后续产品,已经融合在 Spring Web Flow 里面。 Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块。使用 Spring 可插入的 MVC 架构,从而在使用 Spring 进行 WEB 开发时,可以选择使用 Spring的 Spring MVC 框架或集成其他 MVC 开发框架,如 Struts1(现在一般不用), Struts2 等。
SpringMVC 已经成为目前最主流的 MVC 框架之一, 并且随着 Spring3.0 的发布, 全面超越 Struts2,成为最优秀的 MVC 框架。它通过一套注解,让一个简单的 Java 类成为处理请求的控制器,而无须实现任何接口。同时它还支持RESTful
编程风格的请求。
1、清晰的角色划分:
2、分工明确,而且扩展点相当灵活,可以很容易扩展,虽然几乎不需要。
3、由于命令对象就是一个 POJO,无需继承框架特定 API,可以使用命令对象直接作为业务对象。
4、和 Spring 其他框架无缝集成,是其它 Web 框架所不具备的。
5、可适配,通过 HandlerAdapter 可以支持任意的类作为处理器。
6、可定制性, HandlerMapping、 ViewResolver 等能够非常简单的定制。
7、功能强大的数据验证、格式化、绑定机制。
8、利用 Spring 提供的 Mock 对象能够非常简单的进行 Web 层单元测试。
9、本地化、主题的解析的支持,使我们更容易进行国际化和主题的切换。
10、强大的 JSP 标签库,使 JSP 编写更容易。
………………还有比如RESTful风格的支持、简单的文件上传、约定大于配置的契约式编程支持、基于注解的零配置支持等等。
共同点:
区别:
开发环境搭建——IDEA为例:
解决控制台中文乱码:-Dfile.encoding=UTF-8
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>top.onefinegroupId>
<artifactId>springmvc_day01_01_startartifactId>
<version>1.0-SNAPSHOTversion>
<packaging>warpackaging>
<name>springmvc_day01_01_start Maven Webappname>
<url>http://www.example.comurl>
<properties>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<maven.compiler.source>1.8maven.compiler.source>
<maven.compiler.target>1.8maven.compiler.target>
<spring.version>5.2.2.RELEASEspring.version>
properties>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.11version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>servlet-apiartifactId>
<version>2.5version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>jsp-apiartifactId>
<version>2.0version>
<scope>providedscope>
dependency>
dependencies>
<build>
<finalName>springmvc_day01_01_startfinalName>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-clean-pluginartifactId>
<version>3.1.0version>
plugin>
<plugin>
<artifactId>maven-resources-pluginartifactId>
<version>3.0.2version>
plugin>
<plugin>
<artifactId>maven-compiler-pluginartifactId>
<version>3.8.0version>
plugin>
<plugin>
<artifactId>maven-surefire-pluginartifactId>
<version>2.22.1version>
plugin>
<plugin>
<artifactId>maven-war-pluginartifactId>
<version>3.2.2version>
plugin>
<plugin>
<artifactId>maven-install-pluginartifactId>
<version>2.5.2version>
plugin>
<plugin>
<artifactId>maven-deploy-pluginartifactId>
<version>2.8.2version>
plugin>
plugins>
pluginManagement>
build>
project>
<web-app>
<display-name>Archetype Created Web Applicationdisplay-name>
<servlet>
<servlet-name>dispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>dispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
web-app>
<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="top.onefine" />
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp" />
bean>
<mvc:annotation-driven />
beans>
<%--
Created by IntelliJ IDEA.
User: ONEFINE
Date: 2020/4/7
Time: 20:42
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>SpringMVC入门title>
head>
<body>
<h2>Hello World!h2>
<a href="hello" >来呀a>
<%--<a href="${ pageContext.request.contextPath }/hello">嗯哼?a>--%>
body>
html>
package top.onefine.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
// 控制器类,用来接收浏览器请求
@Controller // 将类交给IOC容器进行管理,Spring的注解
public class HelloController {
// 接收请求
@RequestMapping(path = "/hello") // 请求映射
public String sayHallo() {
System.out.println("Hello StringMVC");
return "success"; // 会自动跳转到success.jsp
}
}
<%--
Created by IntelliJ IDEA.
User: ONEFINE
Date: 2020/4/7
Time: 21:01
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>成功页面title>
head>
<body>
<h2>SpringMVC入门成功!h2>
body>
html>
1、服务器启动,应用被加载。 读取到 web.xml 中的配置创建 spring 容器并且初始化容器中的对象。从入门案例中可以看到的是: HelloController 和 InternalResourceViewResolver,但是远不止这些。
2、浏览器发送请求,被 DispatherServlet 捕获,该 Servlet 并不处理请求,而是把请求转发出去。转发的路径是根据请求 URL,匹配@RequestMapping 中的内容。
3、匹配到了后,执行对应方法。该方法有一个返回值。
4、根据方法的返回值,借助 InternalResourceViewResolver 找到对应的结果视图。
5、渲染结果视图,响应浏览器。
当启动Tomcat服务器的时候,因为配置了load-on-startup标签,所以会创建DispatcherServlet对象,就会加载springmvc.xml配置文件
开启了注解扫描,那么HelloController对象就会被创建
从index.jsp发送请求,请求会先到达DispatcherServlet核心控制器,根据配置@RequestMapping注解找到执行的具体方法
根据执行方法的返回值,再根据配置的视图解析器,去指定的目录下查找指定名称的JSP文件
Tomcat服务器渲染页面,做出响应
用户请求到达前端控制器,它就相当于 mvc 模式中的 c, dispatcherServlet 是整个流程控制的中心,由它调用其它组件处理用户的请求, dispatcherServlet 的存在降低了组件之间的耦合性。
HandlerMapping 负责根据用户请求找到 Handler 即处理器, SpringMVC 提供了不同的映射器实现不同的映射方式,例如:配置文件方式,实现接口方式,注解方式等。
它就是我们开发中要编写的具体业务控制器。由 DispatcherServlet 把用户请求转发到 Handler。由Handler 对具体的用户请求进行处理。
通过 HandlerAdapter 对处理器进行执行,这是适配器模式的应用,通过扩展适配器可以对更多类型的处理器进行执行。
View Resolver 负责将处理结果生成 View 视图, View Resolver 首先根据逻辑视图名解析成物理视图名即具体的页面地址,再生成 View 视图对象,最后对 View 进行渲染将处理结果通过页面展示给用户。
SpringMVC 框架提供了很多的 View 视图类型的支持,包括: jstlView、 freemarkerView、 pdfView等。我们最常用的视图就是 jsp。
一般情况下需要通过页面标签或页面模版技术将模型数据通过页面展示给用户,需要由程序员根据业务需求开发具体的页面。
说明在 SpringMVC 的各个组件中,处理器映射器、处理器适配器、视图解析器称为 SpringMVC 的三大组件。
使用
自动加载 RequestMappingHandlerMapping(处理映射器)和RequestMappingHandlerAdapter(处理适配器 ),可用在SpringMVC.xml 配置文件中使用
替代注解处理器和适配器的配置。它就相当于在 xml 中配置了:
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" />
<bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter" />
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />
<bean class="org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver" />
<bean class="org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver" />
<bean class="org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver" />
注意:一般开发中,我们都需要写上此标签(虽然从入门案例中看,我们不写也行,随着课程的深入,该标签还有具体的使用场景)。
明确:我们只需要编写处理具体业务的控制器以及视图。
源码:
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestMapping {
}
作用: 用于建立请求 URL 和处理请求方法之间的对应关系。
出现位置: RequestMapping注解可以作用在方法和类上。
/
开头。它出现的目的是为了使我们的 URL 可以按照模块化管理,例如:账户模块:
/account/add
/account/update
/account/delete
…
订单模块:
/order/add
/order/update
/order/delete
黄色的部分就是把 RequsetMappding 写在类上,使我们的 URL 更加精细。
细节:
/
表示应用的根目录开始${ pageContext.request.contextPath }
也可以省略不写,但是路径上不能写 /
属性:
value/path
:value用于指定请求的 URL。 它和 path
属性的作用是一样的。// value可省略不写method
:用于指定方法的请求方式,如Get/Post…。params
:用于指定限制请求参数的条件。 它支持简单的表达式。 要求请求参数的 key 和 value 必须和配置的一模一样。例如:
params = {"accountName"}
,表示请求参数必须有 accountName
params = {"moeny!100"}
,表示请求参数中 money 不能是 100。
注意:
以上四个属性只要出现 2 个或以上时,他们的关系是与的关系。
package top.onefine.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
// 控制器类,用来接收浏览器请求
@RequestMapping(path = "user")
@Controller // 将类交给IOC容器进行管理
public class HelloController {
// 接收请求
@RequestMapping(path = "/hello") // 请求映射
public String sayHallo() {
System.out.println("Hello StringMVC");
return "success"; // 会自动跳转到success.jsp
}
@RequestMapping(path = "/testRequestMapping"
// , method = {RequestMethod.POST}
// , params = {"username"} // 请求必须含有参数且名字为username,如http://localhost:8080/user/testRequestMapping?username=onefine
, params = {"username=onefine", "money>1000"} // 请求必须有名字为username的参数且值只能为onefine
, headers = {"Accept"} // 请求头中必须包含Accept
)
public String testRequestMapping() {
System.out.println("RequestMapping注解测试");
return "success";
}
}
我们都知道,表单中请求参数(提交的数据)都是基于 key=value
的。
SpringMVC 绑定请求参数的过程是通过把表单提交请求参数,作为控制器中方法参数进行绑定的。例如:请求参数绑定
中请求参数是username=onefine
和password=123
。
要求:提交表单的name和参数的名称是相同的。
package top.onefine.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* 请求参数绑定
*/
@Controller
@RequestMapping("/param")
public class ParamController {
/**
* 请求参数绑定入门
* @return
*/
@RequestMapping("/testParam")
public String testParam(String username, String password) {
System.out.println("执行了...");
System.out.println("username: " + username);
System.out.println("password: " + password);
return "success";
}
}
基本类型参数: 包括基本类型和 String 类型
POJO 类型参数: 包括实体类(JavaBean),以及关联的实体类
数组和集合类型参数: 包括 List 结构和 Map 等结构的集合(包括数组)
SpringMVC 绑定请求参数是自动实现的,但是要想使用,必须遵循使用要求。
如果是基本类型或者 String 类型:要求我们的参数名称必须和控制器中方法的形参名称保持一致。 (严格区分大小写)
如果是 POJO 类型,或者它的关联对象:要求表单中参数名称和 POJO 类的属性名称保持一致。并且控制器方法的参数类型是 POJO 类型。
如果是集合类型,有两种方式:
第一种:
第二种:
注意:它还可以实现一些数据类型自动转换。 内置转换器全都在:org.springframework.core.convert.support
包下。 有:
java.lang.Boolean -> java.lang.String : ObjectToStringConverter
java.lang.Character -> java.lang.Number : CharacterToNumberFactory
java.lang.Character -> java.lang.String : ObjectToStringConverter
java.lang.Enum -> java.lang.String : EnumToStringConverter
java.lang.Number -> java.lang.Character : NumberToCharacterConverter
java.lang.Number -> java.lang.Number : NumberToNumberConverterFactory
java.lang.Number -> java.lang.String : ObjectToStringConverter
java.lang.String -> java.lang.Boolean : StringToBooleanConverter
java.lang.String -> java.lang.Character : StringToCharacterConverter
java.lang.String -> java.lang.Enum : StringToEnumConverterFactory
java.lang.String -> java.lang.Number : StringToNumberConverterFactory
java.lang.String -> java.util.Locale : StringToLocaleConverter
java.lang.String -> java.util.Properties : StringToPropertiesConverter
java.lang.String -> java.util.UUID : StringToUUIDConverter
java.util.Locale -> java.lang.String : ObjectToStringConverter
java.util.Properties -> java.lang.String : PropertiesToStringConverter
java.util.UUID -> java.lang.String : ObjectToStringConverter
......
如遇特殊类型转换要求,需要我们自己编写自定义类型转换器。(下面介绍)
详上…
对象.属性
例如:address.name这里使用lombok插件,先在maven中引入相关坐标:
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.12version>
<scope>providedscope>
dependency>
src/main/java/top/onefine/domain/Account.java:
package top.onefine.domain;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.io.Serializable;
/**
* javaBean,实体类
*/
@Getter
@Setter
@ToString
public class Account implements Serializable {
private String username;
private String password;
private Double money;
}
src/main/webapp/param.jsp:
<%--
Created by IntelliJ IDEA.
User: ONEFINE
Date: 2020/4/8
Time: 21:14
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>请求参数绑定title>
head>
<body>
<%-- 请求参数绑定 --%>
<%--<a href="param/testParam?username=onefine&password=123">请求参数绑定a>--%>
<form action="param/saveAccount" method="post">
姓名:<input type="text" name="username"><br/>
密码:<input type="password" name="password"><br/>
金额:<input type="text" name="money"><br/>
<input type="submit" value="提交">
form>
body>
html>
src/main/java/top/onefine/controller/ParamController.java:
package top.onefine.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import top.onefine.domain.Account;
/**
* 请求参数绑定
*/
@Controller
@RequestMapping("/param")
public class ParamController {
/**
* 请求参数绑定入门
* @return
*/
@RequestMapping("/testParam")
public String testParam(String username, String password) {
System.out.println("执行了...");
System.out.println("username: " + username);
System.out.println("password: " + password);
return "success";
}
/**
* 请求参数绑定:把数据封装到JavaBean的类中
* @return
*/
@RequestMapping("/saveAccount")
public String saveAccount(Account account) {
System.out.println(account);
return "success";
}
}
src/main/java/top/onefine/domain/User.java:
package top.onefine.domain;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.io.Serializable;
@Setter
@Getter
@ToString
public class User implements Serializable {
private String uname;
private Integer age;
}
src/main/java/top/onefine/domain/Account.java:
package top.onefine.domain;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.io.Serializable;
/**
* javaBean
*/
@Getter
@Setter
@ToString
public class Account implements Serializable {
private String username;
private String password;
private Double money;
private User user;
}
src/main/java/top/onefine/controller/ParamController.java:
package top.onefine.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import top.onefine.domain.Account;
/**
* 请求参数绑定
*/
@Controller
@RequestMapping("/param")
public class ParamController {
/**
* 请求参数绑定入门
* @return
*/
@RequestMapping("/testParam")
public String testParam(String username, String password) {
System.out.println("执行了...");
System.out.println("username: " + username);
System.out.println("password: " + password);
return "success";
}
/**
* 请求参数绑定:把数据封装到JavaBean的类中
* @return
*/
@RequestMapping("/saveAccount")
public String saveAccount(Account account) {
System.out.println(account);
return "success";
}
}
src/main/webapp/param.jsp:
<%--
Created by IntelliJ IDEA.
User: ONEFINE
Date: 2020/4/8
Time: 21:14
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>请求参数绑定title>
head>
<body>
<%-- 请求参数绑定 --%>
<%--<a href="param/testParam?username=onefine&password=123">请求参数绑定a>--%>
<form action="param/saveAccount" method="post">
姓名:<input type="text" name="username"><br/>
密码:<input type="password" name="password"><br/>
金额:<input type="text" name="money"><br/>
用户姓名:<input type="text" name="user.uname"><br/>
用户年龄:<input type="text" name="user.age"><br/>
<input type="submit" value="提交">
form>
body>
html>
src/main/webapp/WEB-INF/web.xml中配置:
<web-app>
<display-name>Archetype Created Web Applicationdisplay-name>
<servlet>
<servlet-name>dispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>dispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<filter-name>characterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>characterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
web-app>
更详细的配置:
post 请求方式:
在 web.xml 中配置一个过滤器:
<filter>
<filter-name>CharacterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
<init-param>
<param-name>forceEncodingparam-name>
<param-value>trueparam-value>
init-param>
filter>
<filter-mapping>
<filter-name>CharacterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
在 springmvc 的配置文件中可以配置,静态资源不过滤:
<mvc:resources location="/css/" mapping="/css/**"/>
<mvc:resources location="/images/" mapping="/images/**"/>
<mvc:resources location="/scripts/" mapping="/javascript/**"/>
get 请求方式:
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" redirectPort="8443" useBodyEncodingForURI="true"/>
如果遇到 ajax 请求仍然乱码,请把:useBodyEncodingForURI="true"
改为 URIEncoding="UTF-8"
即可。
src/main/java/top/onefine/domain/Account.java:
package top.onefine.domain;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
/**
* javaBean
*/
@Getter
@Setter
@ToString
public class Account implements Serializable {
private String username;
private String password;
private Double money;
// private User user;
private List<User> list;
private Map<String, User> map;
}
src/main/webapp/param.jsp
<%--
Created by IntelliJ IDEA.
User: ONEFINE
Date: 2020/4/8
Time: 21:14
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>请求参数绑定title>
head>
<body>
<%-- 请求参数绑定 --%>
<%--<a href="param/testParam?username=onefine&password=123">请求参数绑定a>--%>
<%-- 把数据封装Account类中,类中存在list和map集合 --%>
<form action="param/saveAccount" method="post">
姓名:<input type="text" name="username"><br/>
密码:<input type="password" name="password"><br/>
金额:<input type="text" name="money"><br/>
<%-- 封装到user存list --%>
用户姓名:<input type="text" name="list[0].uname"><br/>
用户年龄:<input type="text" name="list[0].age"><br/>
<%-- 封装到user存map --%>
用户姓名:<input type="text" name="map['one'].uname"><br/>
用户年龄:<input type="text" name="map['one'].age"><br/>
<input type="submit" value="提交">
form>
body>
html>
src/main/java/top/onefine/domain/User.java
package top.onefine.domain;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.io.Serializable;
import java.util.Date;
@Setter
@Getter
@ToString
public class User implements Serializable {
private String uname;
private Integer age;
private Date date;
}
src/main/java/top/onefine/controller/ParamController.java
package top.onefine.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import top.onefine.domain.Account;
import top.onefine.domain.User;
/**
* 请求参数绑定
*/
@Controller
@RequestMapping("/param")
public class ParamController {
// ...
// 自定义类型转换器
@RequestMapping("/saveUser")
public String saveUser(User user) {
System.out.println(user);
return "success";
}
}
src/main/webapp/param.jsp
<%--
Created by IntelliJ IDEA.
User: ONEFINE
Date: 2020/4/8
Time: 21:14
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>请求参数绑定title>
head>
<body>
<%-- 请求参数绑定 --%>
<%--<a href="param/testParam?username=onefine&password=123">请求参数绑定a>--%>
<%-- 自定义类型转换器 --%>
<form action="param/saveUser" method="post">
用户姓名:<input type="text" name="uname"><br/>
用户年龄:<input type="text" name="age"><br/>
用户生日:<input type="text" name="date"><br/>
<input type="submit" value="提交">
form>
body>
html>
第一步: 定义一个类,实现 Converter
接口,该接口有两个泛型。S:表示接受的类型, T:表示目标类型
src/main/java/top/onefine/utils/StringToDateConverter.java:
package top.onefine.utils;
import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 自定义转换器:把字符串转换日期
*/
public class StringToDateConverter implements Converter<String, Date> {
/**
*
* @param source 传入进来的字符串
* @return
*/
@Override
public Date convert(String source) {
// if (source == null)
// throw new RuntimeException("请传入数据");
if(StringUtils.isEmpty(source))
throw new NullPointerException("请输入要转换的日期");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
// Date parse = df.parse(source); // 将日期转换成字符串
return df.parse(source);
} catch (ParseException e) {
throw new RuntimeException("数据类型转换异常");
}
}
}
第二步: 在 springmvc.xml
中配置文件中配置类型转换器,并使得自定义类型转换器生效!spring 配置类型转换器的机制是,将自定义的转换器注册到类型转换服务中去。
第三步: 在 annotation-driven 标签中引用配置的类型转换服务
src/main/resources/springmvc.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="top.onefine" />
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp" />
bean>
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="top.onefine.utils.StringToDateConverter" />
set>
property>
bean>
<mvc:annotation-driven conversion-service="conversionService"/>
beans>
重新执行:
ServletAPI
对象作为方法参数SpringMVC 还支持使用原始 ServletAPI 对象作为控制器方法的参数。支持原始 ServletAPI 对象有:
HttpServletRequest
HttpServletResponse
HttpSession
java.security.Principal
Locale
InputStream
OutputStream
Reader
Writer
可以把上述对象,直接写在控制的方法参数中使用。
在控制器中使用原生的ServletAPI对象:只需要在控制器的方法参数定义HttpServletRequest
和HttpServletResponse
对象。
部分示例代码:
jsp 代码:
<a href="param/testServlet">Servlet原生APIa>
控制器中的代码(src/main/java/top/onefine/controller/ParamController.java):
package top.onefine.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import top.onefine.domain.Account;
import top.onefine.domain.User;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* 请求参数绑定
*/
@Controller
@RequestMapping("/param")
public class ParamController {
// 原生API获取
@RequestMapping("/testServlet")
public String testServlet(HttpServletRequest request, HttpServletResponse response) {
// 操作request和response
// 举例说明
System.out.println(request);
System.out.println(response);
HttpSession session = request.getSession();
System.out.println(session);
ServletContext servletContext = session.getServletContext();
System.out.println(servletContext);
return "success";
}
}
执行结果:
作用:
属性:
value
: 请求参数中的名称。required
:请求参数中是否必须提供此参数。 默认值: true,表示必须提供,如果不提供将报错。详末尾…
作用:
key=value&key=value...
结构的数据。(异步时有用!)属性:
required
:是否必须有请求体。默认值是:true。当取值为 true 时,get 请求方式会报错。如果取值为 false, get 请求得到是 null。详末尾…
作用:
/delete/{id}
, 这个{id}
就是 url 占位符。属性:
value
: 用于指定 url 中占位符名称。required
:是否必须提供占位符。什么是 rest: REST(英文: Representational State Transfer,简称 REST)描述了一个架构样式的网络系统,比如 web 应用程序。它首次出现在 2000 年 Roy Fielding 的博士论文中,他是 HTTP 规范的主要编写者之一。在目前主流的三种 Web 服务交互方案中, REST 相比于 SOAP(Simple Object Access protocol,简单对象访问协议)以及 XML-RPC 更加简单明了,无论是对 URL 的处理还是对 Payload 的编码, REST 都倾向于用更加简单轻量的方法设计和实现。值得注意的是 REST 并没有一个明确的标准,而更像是一种设计的风格。它本身并没有什么实用性,其核心价值在于如何设计出符合 REST 风格的网络接口。
restful 的优点 它结构清晰、符合标准、易于理解、 扩展方便,所以正得到越来越多网站的采用。
restful 的特性:
restful 的示例:
/account/1 HTTP GET : 得到 id = 1 的 account
/account/1 HTTP DELETE: 删除 id = 1 的 account
/account/1 HTTP PUT: 更新 id = 1 的 account
/account HTTP POST: 新增 account
图解:
详末尾…
作用:
由于浏览器 form 表单只支持 GET 与 POST 请求,而 DELETE、 PUT 等 method 并不支持, Spring3.0 添加了一个过滤器,可以将浏览器请求改为指定的请求方式,发送给我们的控制器方法,使得支持 GET、 POST、 PUT与 DELETE 请求。
使用方法:
post
请求。_method
请求参数,该参数的取值就是我们需要的请求方式。jsp 中示例代码:
<form action="springmvc/testRestPOST" method="post">
用户名称: <input type="text" name="username"><br/>
<input type="submit" value="保存">
form>
<hr/>
<form action="springmvc/testRestPUT/1" method="post">
用户名称: <input type="text" name="username"><br/>
<input type="hidden" name="_method" value="PUT">
<input type="submit" value="更新">
form>
<hr/>
<form action="springmvc/testRestDELETE/1" method="post">
<input type="hidden" name="_method" value="DELETE">
<input type="submit" value="删除">
form>
<hr/>
<form action="springmvc/testRestGET/1" method="post">
<input type="hidden" name="_method" value="GET">
<input type="submit" value="查询">
form>
控制器中示例代码:
/**
* post 请求:保存
* @param username
* @return
*/
@RequestMapping(value="/testRestPOST",method=RequestMethod.POST)
public String testRestfulURLPOST(User user){
System.out.println("rest post"+user);
return "success";
}
/**
* put 请求:更新
* @param username
* @return
*/
@RequestMapping(value="/testRestPUT/{id}",method=RequestMethod.PUT)
public String testRestfulURLPUT(@PathVariable("id")Integer id,User user){
System.out.println("rest put "+id+","+user);
return "success";
}
/**
* post 请求:删除
* @param username
* @return
*/
@RequestMapping(value="/testRestDELETE/{id}",method=RequestMethod.DELETE)
public String testRestfulURLDELETE(@PathVariable("id")Integer id){
System.out.println("rest delete "+id);
return "success";
}
/**
* post 请求:查询
* @param username
* @return
*/
@RequestMapping(value="/testRestGET/{id}",method=RequestMethod.GET)
public String testRestfulURLGET(@PathVariable("id")Integer id){
System.out.println("rest get "+id);
return "success";
}
WebService
有更好的方式,这里作为了解即可!
作用:
属性:
注:在实际开发中一般不怎么用。
详末尾…
作用:
属性:
value
:指定 cookie 的名称。required
:是否必须有此 cookie。详末尾…
作用:
属性:
value
:用于获取数据的 key。 key 可以是 POJO 的属性名称,也可以是 map 结构的 key。应用场景:
详末尾…
作用:
属性:
value
:用于指定存入的属性名称type
:用于指定存入的数据类型。src/main/webapp/WEB-INF/pages/success.jsp:
<%--
Created by IntelliJ IDEA.
User: ONEFINE
Date: 2020/4/7
Time: 21:01
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>成功页面title>
head>
<body>
<h2>SpringMVC入门成功!h2>
${ requestScope.name }<%--注意:设置不忽略el表达式:isELIgnored="false"--%>
<%-- ${ requestScope.name }可以简写${ name }--%>
<hr/>
${ sessionScope }
body>
html>
详末尾…
src/main/webapp/anno.jsp:
<%--
Created by IntelliJ IDEA.
User: lenovo
Date: 2020/4/9
Time: 9:44
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>常用注解title>
head>
<body>
<%-- 常用注解 --%>
<a href="anno/testRequestParam?username=onefine">RequestParama><br/>
<p>RequestBodyp>
<form action="anno/testRequestBody" method="post">
用户姓名:<input type="text" name="uname"><br/>
用户年龄:<input type="text" name="age"><br/>
<input type="submit" value="提交">
form><br/>
<a href="anno/testPathVaribale/963">PathVaribalea><br/>
<a href="anno/testRequestHeader">RequestHeadera><br/>
<a href="anno/testCookieValue">CookieValuea><br/>
<p>ModelAttributep>
<form action="anno/testModelAttribute" method="post">
用户姓名:<input type="text" name="uname"><br/>
用户年龄:<input type="text" name="age"><br/>
<input type="submit" value="提交">
form><br/>
<a href="anno/testSessionAttribute">SessionAttributea><br/>
<a href="anno/getSessionAttribute">从session中获取值a><br/>
<a href="anno/delSessionAttribute">从session中获取值a><br/>
body>
html>
src/main/java/top/onefine/controller/AnnoController.java:
package top.onefine.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import top.onefine.domain.User;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;
/**
* 演示常用注解
*/
@Controller
@RequestMapping("/anno")
@SessionAttributes(value = "name") // 把name=onefine存入到session域中(当然request域中原本就有)
// @SessionAttributes(value ={"username","password"},types={Integer.class}) // 存储多个值的情况
// @SessionAttributes(value= {"username","password","age"},types={String.class, Integer.class}) // 把数据存入到session域对象中
public class AnnoController {
@RequestMapping("/testRequestParam")
public String testRequestParam(@RequestParam(value = "username", required = true) String name) {
System.out.println(name);
return "success";
}
@RequestMapping("/testRequestBody")
public String testRequestBody(@RequestBody String body) {
// 获取到请求体的内容
System.out.println(body); // uname=one+%E6%B1%AA&age=18
return "success";
}
@RequestMapping("/testPathVaribale/{sid}")
public String testPathVaribale(@PathVariable(name="sid") String id) {
System.out.println(id);
return "success";
}
// 演示HiddentHttpMethodFilter,只接受PUT请求
// @RequestMapping(value = "/testPathVaribale/{sid}", method = RequestMethod.PUT)
// public String testPathVaribale(@PathVariable(name="sid") String id) {
// System.out.println(id);
// return "success";
// }
@RequestMapping("/testRequestHeader")
public String testRequestHeader(@RequestHeader(value = "Accept") String header) {
// Accept为例
System.out.println(header); // text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
return "success";
}
@RequestMapping("/testCookieValue")
public String testCookieValue(@CookieValue(value = "JSESSIONID") String cookieValue) {
// 假设有一个叫JSESSIONID的session,以此为例
System.out.println(cookieValue); // 1004AA7B7C41F3112383C5EF2828D5C6
return "success";
}
/*
* 应用场景示例 1: ModelAttribute 修饰方法带返回值——注解在方法上
*/
// @RequestMapping("/testModelAttribute")
// public String testModelAttribute(User user) {
// System.out.println("ModelAttribute注解在方法上修饰的情形...");
// System.out.println(user); // User(uname=one 汪, age=18, date=Thu Apr 09 11:03:06 CST 2020)
// return "success";
// }
//
// // 该方法会先执行
// @ModelAttribute
// public User showUser(String uname) {
// System.out.println("showUser方法执行了...");
//
// // 模拟通过用户名查询数据库
// User user = new User();
// user.setUname(uname);
// user.setAge(20); // 数据库查询结果
// user.setDate(new Date()); // 数据库查询结果
// return user;
// }
/*
应用场景示例 2: ModelAttribute 修饰方法不带返回值——注解在参数上
*/
@RequestMapping("/testModelAttribute")
public String testModelAttribute(@ModelAttribute(value = "onefine") User user) {
System.out.println("ModelAttribute注解在参数上修饰的情形...");
System.out.println(user); // User(uname=one 汪, age=18, date=Thu Apr 09 11:03:06 CST 2020)
return "success";
}
// 该方法会先执行
@ModelAttribute
public void showUser(String uname, Map<String, User> map) {
System.out.println("showUser方法执行了...");
// 模拟通过用户名查询数据库
User user = new User();
user.setUname(uname);
user.setAge(20); // 数据库查询结果
user.setDate(new Date()); // 数据库查询结果
map.put("onefine", user);
}
@RequestMapping("/testSessionAttribute")
public String testSessionAttribute(Model model) {
// 也可以使用servletapi的方式(HttpServletRequest request),但这种方式耦合过高
// 底层会存储到request域对象中
model.addAttribute("name", "oenfine"); // success中通过${ requestScope }取到值;注意设置不忽略el表达式:isELIgnored="false"
return "success";
}
// 从session中获取值
@RequestMapping("/getSessionAttribute")
public String getSessionAttribute(ModelMap modelMap) {
Object name = modelMap.get("name");
System.out.println((String) name); // 从session中获取值
return "success";
}
// 从session中移除值
@RequestMapping("/delSessionAttribute")
public String delSessionAttribute(SessionStatus status) {
status.setComplete(); // 清除session
System.out.println("清除session");
return "success";
}
}