SpringMVC
SpringMVC
ssm:mybatis+Spring+SpringMVC MVC三层架构
SSM框架:研究官方文档,锻炼自学能力,锻炼笔记能力,锻炼项目能力
什么是MVC
- MVC是模型(model),视图(View),控制器(Controller)的简写,是一种软件设计规范
- 是将业务逻辑,数据,显示分离的方法来组织代码
- MVC主要作用是降低了视图与业务逻辑间的双向耦合
- MVC不是一种设计模式,MVC是一种架构模式
前端 数据传输 实体类
实体类:用户名,密码,。。。
前端:用户名 mim
回顾Servlet
- 新建一个maven工程当作父工程,导入pom依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp/jsp-api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
新建maven模块,右键添加add framework support ,webapp
导入servlet和jsp依赖
编写一个servlet类,用来处理用户请求
package com.company;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取前端参数
String method = req.getParameter("method");
if (method.equals("add")){
req.getSession().setAttribute("msg","执行了add方法");
}
if(method.equals("delete")){
req.getSession().setAttribute("msg","执行了delete方法");
}
//调用业务层
//视图转发或者重定向
req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}
}
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">
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.company.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>15</session-timeout><!--分钟-->
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
配置tomcat
localhost:8080/user?method=add
localhost:8080/user?method=delete
启动测试
MVC框架做的事情
- 将url映射到java类或java类的方法
- 封装用户提交的数据
- 处理请求--调用相关的业务处理--封装响应数据
- 将响应的数据进行渲染,jsp/html等表示层数据
初识SpringMVC
什么是SpringMVC,
SpringMVC是SpringFramework的一部分,是基于Java实现MVC的轻量级Web框架
Spring MVC的特点:
-
轻量级,简单易学
-
高效,基于请求响应的MVC框架
-
与Spring兼容性好,无缝结合
-
约定优于配置
-
功能强大:RESTful,数据验证,格式化,本地化,主题等
-
简洁灵活
中心控制器
Spring的web框架围绕DispatcherServlet【调度Servlet】设计,DispatcherServlet的作用是将请求分发到不同的处理器
DispatcherServlet是一个实际的Servlet(继承自HttpServlet基类)
HelloSpringMVC
-
新建一个Module,添加web的支持
-
确定导入了SpringMVC的依赖
-
配置web.xml,注册DispatcherServlet
-
<?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"> <!--注册DispatcherServlet--> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--关联一个springmvc的配置文件:【servlet-name】-servlet.xml--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-servlet.xml</param-value> </init-param> <!--启动级别--> <load-on-startup>1</load-on-startup> </servlet> <!--/匹配所有的请求,不包括.jsp /*匹配所有的请求,包括.jsp --> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
Spring配置文件,springmvc-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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">
<!--添加处理器映射器-->
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<!--添加处理器适配器-->
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
<!--添加视图解析器-->
<!--添加视图解析器-->
<!--视图解析器:DispatcherServlet给他的ModelAndView
1.获取了ModelAndView的数据
2.解析ModelAndView的视图名字
3.拼接视图名字,找到对应的视图
4.将数据渲染到视图上
-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
编写我们要操作业务Controller,要么实现Controller接口,要么增加注解,需要返回一个ModelAndView,装数据,封视图
package com.company;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloController implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
//ModelAndView 模型和视图
ModelAndView mv = new ModelAndView();
//封装对象,放在ModelAndView中,Model
mv.addObject("msg","HelloSpringMVC");
//封装要跳转的视图,放在ModelAndView中
mv.setViewName("hello");//:/WEB-INF/jsp/hello.jsp
return mv;
}
}
将自己的类交给SpringIoC容器,注册bean
<!--Handler-->
<bean id="/hello" class="com.company.HelloController"/>
写要跳转的jsp页面,显示ModuleAndView存放的数据,以及我们的正常页面
出错404
在project structure里 artifacts里 模块下添加lib目录,往lib目录添加所有依赖库,应用即可
SpringMVC执行原理
简要分析执行流程
-
DispatcherServlet表示前置控制器,是整个SpringMVC的控制中心,用户发出请求,DispatcherServlet接收请求并拦截请求
- 我们假设请求的url为:http://localhost:8080/SpringMVC/hello
- 如上url拆分为三部分:
- http://localhost:8080服务器域名
- SpringMVC部署在服务器上的web站点
- hello表示控制器
- 通过分析,如上url表示为:请求位于服务器localhost:8080上的SpringMVC站点的hello控制器
-
HandlerMapping为处理器映射,DispatcherServlet调用
HandlerMapping,HandlerMapping根据请求url查找Handler
-
HandlerExecution表示具体的Handler,其主要作用是根据url查找控制器,如上url被查找控制器为hello
-
HandlerExecution将解析后的信息传递给DispatcherServlet,如解析控制器映射等
-
HandlerAdapter表示处理器适配器,其按照特性的规则去执行Handler
-
Handler让具体的Controller执行
-
Controller将具体的执行信息返回给HandlerAdapter,如ModleAndView
-
HandlerAdapter将视图逻辑名或模型传递给DiapatcherServlet
-
DispatcherServlet调用视图解析器(ViewResolver)来解析HandlerAdapter传递的逻辑视图名
-
视图解析器将解析的逻辑视图名传给DispatcherServlet
-
DispatcherServlet根据视图解析器解析的驶入结果,调用具体的shit最终视图呈现给用户
使用注解开发SpringMVC
防止出错,pom文件记得添加下面
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
新建maven项目,引入add frameworksupport webapp
pom文件添加依赖,以及build
project Structure 中artifacts 添加lib目录,添加依赖库
配置web.xml
-
注意web.xml版本问题,要最新版
-
注册DispatcherServlet
-
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"> <!--注册DispatcherServlet--> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--关联一个springmvc的配置文件:【servlet-name】-servlet.xml--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-servlet.xml</param-value> </init-param> <!--启动级别--> <load-on-startup>1</load-on-startup> </servlet> <!--/匹配所有的请求,不包括.jsp /*匹配所有的请求,包括.jsp --> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
-
关联SpringMVC的配置文件
-
启动级别为1
-
映射路径为/【不要用/*会404】
添加SpringMVC配置文件
- 让IoC的注解生效
- 静态资源过滤
- MVC的注解驱动
- 配置视图解析器
在resource目录下添加springmvc-servlet.xml配置文件,配置的形式与Spring容器配置基本类似,为了支持基于注解的IoC,设置了自动扫描包的功能,具体配置信息如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--自动扫描包,让指定的包下的注解生效,由IoC容器统一管理-->
<context:component-scan base-package="com.company.controller"/>
<!--让Spring MVC不处理静态资源-->
<mvc:default-servlet-handler/>
<!--支持mvc注解驱动
在Spring中一般采用@RequestMapping注解来完成映射关系
要想使@RequestMapping注解生效
必须向上下文中注册DefaultAnnotationHandlerMapping
和一个AnnotationMethodHandlerAdapter实例
这两个实例分别在类级别和方法级别处理
而annotation-driven配置帮助我们自动完成上述两个实例的注入
-->
<mvc:annotation-driven/>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
在视图解析器中我们把所有的视图都存放在/WEB-INF/目录下,这样可以保证视图安全,因为这个目录下的文件,客户端不能直接访问
创建Controller
- 编写一个Java控制类:com.company.controller.HelloController,注意编码规范
package com.company.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/HelloController")//可以不加,更加干净
public class HelloController {
//真实访问地址:项目名:/HelloController/hello
@RequestMapping("/hello")
public String sayHello(Model model){
//向模型中添加属性msg与值,可以在JSP页面中取出并渲染
model.addAttribute("msg","hello,SpringMVC");//封装数据
return "hello";//会被视图解析器处理
}
}
@Controller是为了让SpringIoC容器初始化时被自动扫描到
@RequestMapping是为了映射请求路径,这里因为类与方法上都有映射所以访问时,应该时/HelloController/hello
方法中声明Model类型的参数时为了把Action中的数据带到视图中
方法返回的结果时视图的名称hello,加上配置文件中的前后缀变成WEB-INF/jsp/hello.jsp
创建视图层
配置tomcat测试
使用SpringMVC必须配置的三大件
- 处理器映射器,处理器适配器,视图解析器
- 通常,我们只需要手动配置视图解析器,而处理器映射器和处理器适配器只需要开启注解驱动即可,省去了大段的xml配置
Controller配置总结
控制器Controller
- 控制器负责提供访问应用程序的行为,通常通过接口定义或注解定义两种方法实现
- 控制器负责解析用户的请求并将其转换为一个模型
- 在SpringMVC中一个控制器类可以包含多个方法
- 在SpringMVC中,对于Controller的配置方式由很多种
实现controller接口
-
controller时一个接口,在org.springframework.web.servlet.mvc包下,接口中只有一个方法:
-
//实现该接口的类获得控制器功能 public interface Controller { //处理请求且返回一个模型与视图对象 ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception; }
-
测试
-
新建一个module
-
编写一个Controller类,ControllerTest
-
package com.company.controller; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //只要实现了Controller接口的类,说明这就是一个控制器了 public class ControllerTest implements Controller { @Override public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView mv = new ModelAndView(); mv.addObject("msg","SpringMVC"); mv.setViewName("test"); return mv; } }
-
编写完毕后,去Spring配置文件中注册请求的bean,name对应请求路径,class对应处理请求的类
<bean name="/test" class="com.company.controller.ControllerTest"/>
编写前端test.jsp
配置tomcat运行测试
-
-
使用注解@Controller
-
@Controller注解类型用于声明Spring类的实例是一个控制器,
-
Spring可以使用扫描机制来找到应用程序中所有介于注解的控制器类,为了保证Spring能找到你的控制器,需要在配置文件中什么组件扫描
-
<!--自动扫描包,让指定的包下的注解生效,由IoC容器统一管理--> <context:component-scan base-package="com.company.controller"/>
-
增加一个ControllerTest2类,使用注解实现
-
package com.company.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ControllerTest2 {
//映射访问路径
@RequestMapping("/t2")
public String test(Model model){
//SpringMVC会自动实例化一个model对象用于向视图中传值
model.addAttribute("msg","Spring Annotation");
return "test";//返回视图位置
}
}
运行tomcat测试
RequestMapping
@RequestMapping
@RequestMapping注解用于映射url到控制器类或一个特定的处理程序方法,可用于类或方法上,用于类上,表示类中的所有响应的方法都是以该地址作为父路径
RestFul风格
概念
Restful就是一个资源定位及资源操作的风格。不是标准也不是协议,只是一种风格,基于这个风格设计的软件可以更简洁,更由层次,跟易于实现缓存等机制
功能
- 资源:互联网所有的事物都可以被抽象为资源
- 资源操作:使用POST,DELETE,PUT,GET,使用不同方法对资源进行操作
- 分别对应添加,删除,修改,查询
传统方式操作资源:通过不同的参数来实现不同的效果,方法单一:post,get
使用restful操作资源,可以通过不同的请求方式来实现不同的效果,
测试:
-
新建一个类RestFulController
package com.company.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class RestFulController { @RequestMapping("/add") public String test(int a, int b, Model model){ int res = a + b; model.addAttribute("msg","结果为:"+res); return "test"; } }
访问测试
http://localhost:8080/add?a=1&&b=2
在SpringMVC中可以使用@PathVariable注解,让方法参数的值对应绑定到一个URI模板变量上
package com.company.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class RestFulController {
@RequestMapping("/add/{a}/{b}")
public String test(@PathVariable int a, @PathVariable int b, Model model){
int res = a + b;
model.addAttribute("msg","结果为:"+res);
return "test";
}
}
package com.company.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class RestFulController {
@RequestMapping(name="/add/{a}/{b}",method = RequestMethod.POST)
public String test(@PathVariable int a, @PathVariable int b, Model model){
int res = a + b;
model.addAttribute("msg","结果为:"+res);
return "test";
}
}
可以限定方法,这样其他方法获取不到页面,虽然地址是一样
package com.company.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@Controller
public class RestFulController {
/*@RequestMapping(value="/add/{a}/{b}",method = RequestMethod.POST)*/
@GetMapping("/add/{a}/{b}")
public String test(@PathVariable int a, @PathVariable int b, Model model){
int res = a + b;
model.addAttribute("msg","结果为:"+res);
return "test";
}
}
重定向和转发
ModelAndView
设置ModelAndView对象,根据view的名称,和视图解析器跳到指定的页面
页面:{视图解析器前缀}+viewName+{视图解析器后缀}
ServletAPI
通过设置ServletAPI,不需要视图解析器
- 通过HttpServletResponse进行输出
- 通过HttpServletResponse实现重定向
- 通过HttpServletResponse实现转发
package com.company.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Controller
public class ResultGo {
@RequestMapping("/result/t1")
public void test1(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
rsp.getWriter().println("Hello,Spring by Servlet!");
}
@RequestMapping("/result/t2")
public void test2(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
//重定向
rsp.sendRedirect("/index.jsp");
}
@RequestMapping("/result/t3")
public void test3(HttpServletRequest req, HttpServletResponse rsp) throws Exception {
//转发
req.setAttribute("msg","/result/t3");
req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,rsp);
}
}
SpringMVC
通过SpringMVC来实现转发和重定向-无需视图解析器
测试前,需要将视图解析器注释掉
package com.company.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class SpringTest {
@RequestMapping("/rsm/t1")
public String test1(){
//转发
return "/index.jsp";
}
@RequestMapping("/rsm/t2")
public String test2(){
//转发2
return "forward:/index.jsp";
}
@RequestMapping("/rsm/t3")
public String test3(){
//重定向
return "redirect:/index.jsp";
}
}
SpringMVC:数据处理
处理提交数据
- 提交的域名称和处理方法的参数名一致
- 提交数据:http://localhost:8080/hello?name=ming
package com.company.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class Hello {
@RequestMapping("/hello")
public String hello(String name){
System.out.println(name);
return "hello";
}
}
后台输出ming
- 提交的域名称和处理方法的参数名不一致
- 提交数据:http://localhost:8080/hello?username=ming
- 处理方法
package com.company.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class Hello {
@RequestMapping("/hello")
public String hello(@RequestParam("username") String name){
System.out.println(name);
return "hello";
}
}
-
提交的是一个对象
-
要求提交的表单域和对象的属性名一致,参数使用对象即可
-
package com.company.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class User { private int id; private String name; private int age; }
-
处理方法:
package com.company.controller; import com.company.pojo.User; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class Hello { @RequestMapping("/hello") public String hello(User user){ System.out.println(user); return "hello"; } }
-
说明:如果使用对象的话,前端传递的参数名和对象名必须一致,否则就是null
-
数据在前端显示
-
利用ModelAndView
-
利用Model model
-
model.addAttribute("msg",name);//接收的是参数 model.addAttribute("msg",User);//接收的是对象
-
ModelMap map
乱码问题
测试步骤:
-
可以在首页编写一个提交的表单
-
<form action="/tt" method="get"> <input type="text" name="name"> <input type="submit"> </form>
-
后台编写对应的处理类
package com.company.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class Encoding {
@RequestMapping("/tt")
public String test(Model model,String name){
model.addAttribute("msg",name);
return "test";
}
}
-
输入中文测试,发现乱码
-
解决方法:
-
自定义过滤器
-
package com.company.filter; import javax.servlet.*; import java.io.IOException; public class EncodingFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { servletRequest.setCharacterEncoding("utf-8"); servletResponse.setCharacterEncoding("utf-8"); } @Override public void destroy() { } }
-
记得在web.xml注册
-
<filter> <filter-name>filter</filter-name> <filter-class>com.company.filter.EncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
-
或者配置SpringMVC的乱码过滤器
-
<filter> <filter-name>encoding</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
Json
前后端分离时代:
后端部署后端,提供接口,提供数据
json,
前端独立部署,负责渲染后端的数据,
Json(JavaScript Object Notation,JS对象标记)是一种轻量级的数据交换格式,目前使用特别广泛
采用完全独立于编程语言的文本格式来存储和表示数据
简洁和清晰的层次结构使得JSON成为理想的数据交换语言
易于人阅读和编写,同时也易于机器解析和生成,并有效的提升网络传输效率
- 对象表示为键值对,数据由逗号隔开
- 花括号保存对象
- 方括号保存数组
JSON键值对是用来保存JavaScript对象的一种方式,和JavaScript对象的写法也大同小异,键值对组合中的键名写在前面并用双括号“”包裹,使用冒号:分隔,然后紧接着值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript">
//编写一个javaScript对象
var user = {
name:"ming",
age:3,
sex:"男"
}
//将js对象转换为Json对象
var json = JSON.stringify(user)
console.log(json)
console.log(user)
//将JSON对象转换为JavaScript对象
var ob = JSON.parse(json)
console.log(ob)
</script>
</head>
<body>
</body>
</html>
Jackson使用
Controller返回Json数据
Jackson应该是目前比较好的json解析工具
工具还有阿里巴巴的fastjson
这里使用Jackson,使用它需要导入的jar包
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.3</version>
</dependency>
配置SpringMVC环境
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">
<!--注册DispatcherServlet-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--关联一个springmvc的配置文件:【servlet-name】-servlet.xml-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<!--启动级别-->
<load-on-startup>1</load-on-startup>
</servlet>
<!--/匹配所有的请求,不包括.jsp
/*匹配所有的请求,包括.jsp
-->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Spring配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--自动扫描包,让指定的包下的注解生效,由IoC容器统一管理-->
<context:component-scan base-package="com.company.controller"/>
<!--让Spring MVC不处理静态资源-->
<mvc:default-servlet-handler/>
<!--支持mvc注解驱动
在Spring中一般采用@RequestMapping注解来完成映射关系
要想使@RequestMapping注解生效
必须向上下文中注册DefaultAnnotationHandlerMapping
和一个AnnotationMethodHandlerAdapter实例
这两个实例分别在类级别和方法级别处理
而annotation-driven配置帮助我们自动完成上述两个实例的注入
-->
<mvc:annotation-driven/>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
<!-- <bean name="/test" class="com.company.controller.ControllerTest"/>-->
</beans>
编写一个User的实体类,然后我们去编写我们的测试Controller
package com.company.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private int age;
private String sex;
}
- 这里我们需要两个新东西,一个是@ReponseBody,一个是ObjectMapper对象,我们看下具体的用法
- 不用jackson
package com.company.controller;
import com.company.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class UserController {
@RequestMapping("/j1")
@ResponseBody//它就不会走视图解析器,会直接返回一个字符串
public String json1(){
//创建一个对象
User user = new User("ming",3,"男");
return user.toString();
}
}
- 利用jackson
package com.company.controller;
import com.company.pojo.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class UserController {
@RequestMapping("/j1")
@ResponseBody//它就不会走视图解析器,会直接返回一个字符串
public String json1() throws JsonProcessingException {
//jackson ObjectMapper
ObjectMapper mapper = new ObjectMapper();
//创建一个对象
User user = new User("ming",3,"男");
String s = mapper.writeValueAsString(user);
return s;
}
}
- 发现出现了乱码问题,需要设置一下编码格式为utf-8,以及它的返回类型
- 通过@RequestMapping的produces属性来实现,修改代码
package com.company.controller;
import com.company.pojo.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class UserController {
@RequestMapping(value = "/j1",produces = "application/json;charset=utf-8")
@ResponseBody//它就不会走视图解析器,会直接返回一个字符串
public String json1() throws JsonProcessingException {
//jackson ObjectMapper
ObjectMapper mapper = new ObjectMapper();
//创建一个对象
User user = new User("ming",3,"男");
String s = mapper.writeValueAsString(user);
return s;
}
}
乱码问题解决
乱码优化
- 统一解决
- 在Springmvc的配置文件上添加一端消息StringHttpMessageConverter转换配置
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
@Controller 换成@RestController,@ResponseBody就不用写,也只返回字符串
测试集合类
package com.company.controller;
import com.company.pojo.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
@RestController
public class UserController {
@RequestMapping("/j1")
public String json1() throws JsonProcessingException {
//jackson ObjectMapper
ObjectMapper mapper = new ObjectMapper();
//创建一个对象
User user = new User("ming",3,"男");
String s = mapper.writeValueAsString(user);
return s;
}
@RequestMapping("/j2")
public String json2() throws JsonProcessingException {
List<User> list = new ArrayList<>();
//jackson ObjectMapper
ObjectMapper mapper = new ObjectMapper();
//创建一个对象
User user = new User("ming",3,"男");
User user1 = new User("ming",3,"男");
User user2 = new User("ming",3,"男");
User user3 = new User("ming",3,"男");
User user4 = new User("ming",3,"男");
User user5 = new User("ming",3,"男");
list.add(user);
list.add(user1);
list.add(user2);
list.add(user3);
list.add(user4);
list.add(user5);
String s = mapper.writeValueAsString(list);
return s;
}
}
fastjson
fastjson.jar是阿里开发的一款专门用于Java开发的包,可以方便的实现json对象,与javabean对象的转换,实现javabean对象与json字符串的转换,实现json对象与json字符串的转换,
fastjson的pom依赖
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.74</version>
</dependency>
JSONObject代表json对象
JSONArray代表json对象组
JSON代表JSONObject与JSONArray的转化
@RequestMapping("/j4")
public String json4() throws JsonProcessingException {
List<User> list = new ArrayList<>();
//创建一个对象
User user = new User("ming",3,"男");
User user1 = new User("ming",3,"男");
User user2 = new User("ming",3,"男");
User user3 = new User("ming",3,"男");
User user4 = new User("ming",3,"男");
User user5 = new User("ming",3,"男");
list.add(user);
list.add(user1);
list.add(user2);
list.add(user3);
list.add(user4);
list.add(user5);
System.out.println("*******Java对象转JSON字符串******");
String str1 = JSON.toJSONString(list);
System.out.println("JSON.toJSONString(list)==>"+str1);
String str2 = JSON.toJSONString(user);
System.out.println("JSON.toJSONString(user)==>"+str2);
System.out.println("*******Json字符串转Java对象******");
User juser = JSON.parseObject(str2,User.class);
System.out.println("JSON.parseObject(str2,User.class)==>"+juser);
JSONObject job = (JSONObject) JSON.toJSON(user);
System.out.println("(JSONObject) JSON.toJSON(user)==>"+job);
return "f";
}
ssm整合Mybatis层
数据库环境
创建一个存放书籍数据的数据库表
CREATE DATABASE `ssmbuild`;
use `ssmbuild`;
drop table if exists `books`;
create table `books`(
`bookID` INT(10) NOT NULL AUTO_INCREMENT COMMENT '书id',
`bookName` VARCHAR(100) NOT NULL COMMENT '书名',
`bookCounts` INT(11) NOT NULL COMMENT '数量',
`detail` VARCHAR(200) NOT NULL COMMENT '描述',
key `bookID`(`bookID`)
)ENGINE=INNODB DEFAULT CHARSET =utf8;
INSERT INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`) values
(1,'Java',1,'从入门到放弃'),
(2,'Mysql',10,'从删库到跑路'),
(3,'Linux',15,'从进门到进牢');
基本环境搭建
-
依赖
-
数据库连接池
-
<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 --> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.5</version> </dependency>
-
junit,数据库驱动,连接池,servlet,jsp,mybatis,mybatis-spring,spring
-
静态资源导出问题
<?xml version="1.0" 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.0</modelVersion>
<groupId>org.company</groupId>
<artifactId>ssmbuild</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<!--数据库连接池:c3p0:dbcp-->
<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<!--mybatis-spring-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<!--servlet:jsp-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp/jsp-api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.74</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
Ajax初体验
异步无刷新
伪造ajax,iframe
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>体验页面无刷新</title>
<script>
function go(){
//所有的值变量,提前获取
var url = document.getElementById("url").value;
document.getElementById("iframe1").src=url;
}
</script>
</head>
<body>
<div>
<p>请输入地址:</p>
<p>
<input type="text" id="url" value="https://www.baidu.com">
<input type="button" value="提交" onclick=go()>
</p>
</div>
<div>
<iframe id="iframe1" style="width:100%;height: 500px"></iframe>
</div>
</body>
</html>
新建modul,引入web支持,新建lib,导入包
web.xm配置
<?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">
<!--注册DispatcherServlet-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--关联一个springmvc的配置文件:【servlet-name】-servlet.xml-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<!--启动级别-->
<load-on-startup>1</load-on-startup>
</servlet>
<!--/匹配所有的请求,不包括.jsp
/*匹配所有的请求,包括.jsp
-->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>encoding</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>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
appliationContext.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--自动扫描包,让指定的包下的注解生效,由IoC容器统一管理-->
<context:component-scan base-package="com.company.controller"/>
<!--让Spring MVC不处理静态资源-->
<mvc:default-servlet-handler/>
<!--支持mvc注解驱动
在Spring中一般采用@RequestMapping注解来完成映射关系
要想使@RequestMapping注解生效
必须向上下文中注册DefaultAnnotationHandlerMapping
和一个AnnotationMethodHandlerAdapter实例
这两个实例分别在类级别和方法级别处理
而annotation-driven配置帮助我们自动完成上述两个实例的注入
-->
<mvc:annotation-driven/>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
<!-- <bean name="/test" class="com.company.controller.ControllerTest"/>-->
</beans>
jQuery
https://code.jquery.com/jquery-3.5.1.js
下载jquery
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/10/23 0023
Time: 19:40
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.5.1.js"></script>
<script>
function a(){
$.post({
url:"${pageContext.request.contextPath}/a1",
data:{"name":$("#username").val()},
success:function (data){
alert(data);
}
})
}
</script>
</head>
<body>
<%--失去焦点的时候,发起一个请求到后台--%>
用户名:<input type="text" id="username" onblur="a()">
</body>
</html>
控制器
package com.company.controller;
import com.company.pojo.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@RestController
public class AjaxController {
@RequestMapping("/test")
public String test(){
return "ss";
}
@RequestMapping("/a1")
public void a1(String name, HttpServletResponse response) throws IOException {
System.out.println("a:param==>"+name);
if("ming".equals(name)){
response.getWriter().print("true");
}else{
response.getWriter().print("false");
}
}
@RequestMapping("/a2")
public List<User> a2(){
List<User> list = new ArrayList<>();
//添加数据
list.add(new User("ming",4,"nan"));
list.add(new User("r",4,"女"));
return list;
}
@RequestMapping("/a3")
public String a3(String name,String pwd){
String msg="";
if(name!=null){
if ("admin".equals(name)) {
msg="ok";
}else{
msg="false";
}
}
if(pwd!=null){
if ("123456".equals(pwd)) {
msg="ok";
}else{
msg="false";
}
}
return msg;
}
}
异步加载数据
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/10/23 0023
Time: 20:38
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.5.1.js"></script>
<script>
$(function(){
$("#btn").click(function (){
$.post("${pageContext.request.contextPath}/a2",function (data){
console.log(data);
var html = "<>";
for(let i=0;i<data.length;i++){
html+="<tr>"+
"<td>"+data[i].name+"</td>"+
"<td>"+data[i].age+"</td>"+
"<td>"+data[i].sex+"</td>"+
"</tr>"
}
$("#content").html(html);
})
})
});
</script>
</head>
<body>
<input type="button" value="加载数据" id="btn">
<table>
<tr>
<td>姓名</td>
<td>年龄</td>
<td>性别</td>
</tr>
<tbody id="content">
<%--数据:后台--%>
</tbody>
</table>
</body>
</html>
@RequestMapping("/a2")
public List<User> a2(){
List<User> list = new ArrayList<>();
//添加数据
list.add(new User("ming",4,"nan"));
list.add(new User("r",4,"女"));
return list;
}
Ajax验证用户名登录
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/10/23 0023
Time: 20:55
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.5.1.js"></script>
<script>
function a1(){
$.post({
url:"${pageContext.request.contextPath}/a3",
data:{"name":$("#name").val()},
success:function (data){
if(data.toString()=="ok"){
$("#userInfo").css("color","green");
}
else{
$("#userInfo").css("color","red");
}
$("#userInfo").html(data);
}
})
}
function a2(){
$.post({
url:"${pageContext.request.contextPath}/a3",
data:{"pwd":$("#pwd").val()},
success:function (data){
if(data.toString()=="ok"){
$("#pwdInfo").css("color","green");
}
else{
$("#pwdInfo").css("color","red");
}
$("#pwdInfo").html(data);
}
})
}
</script>
</head>
<body>
<p>
用户名:<input type="text" id="name" onblur="a1()">
<span id="userInfo"></span>
</p>
<p>
密码:<input type="text" id="pwd" onblur="a2()">
<span id="pwdInfo"></span>
</p>
</body>
</html>
@RequestMapping("/a3")
public String a3(String name,String pwd){
String msg="";
if(name!=null){
if ("admin".equals(name)) {
msg="ok";
}else{
msg="false";
}
}
if(pwd!=null){
if ("123456".equals(pwd)) {
msg="ok";
}else{
msg="false";
}
}
return msg;
}
拦截器
想定义拦截器,必须实现HandlerInterceptor接口
新建一个module,添加web支持
配置web.xml,和spring配置文件
编写一个拦截器
package com.company.congfig;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyInterceptor implements HandlerInterceptor {
//return true;执行下一个拦截器,放行
//return false;不执行下一个拦截器
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("=====处理前=========");
return true;
}
//拦截日志
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("=====处理后========");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("=====清理=========");
}
}
在spring配置文件中配置
<!--拦截配置-->
<mvc:interceptors>
<mvc:interceptor>
<!--包括下面所有请求-->
<mvc:mapping path="/**"/>
<bean class="com.company.congfig.MyInterceptor"/>
</mvc:interceptor>
<mvc:interceptor>
<!--包括下面所有请求-->
<mvc:mapping path="/user/**"/>
<bean class="com.company.congfig.LoginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
package com.company.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@RequestMapping("/tt")
public String test(){
System.out.println("TestController==>"+"执行了");
return "ok";
}
}
登录判断验证
package com.company.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping("/user")
public class LoginController {
@RequestMapping("/login")
public String login(HttpSession session,String username, String pwd){
//把用户信息存在session中
session.setAttribute("userLoginInfo",username);
return "main";
}
@RequestMapping("/goLogin")
public String goLogin(HttpSession session,String username, String pwd){
return "login";
}
@RequestMapping("/main")
public String main(HttpSession session,String username, String pwd){
return "main";
}
@RequestMapping("/goOut")
public String goOut(HttpSession session,String username, String pwd){
session.removeAttribute("userLoginInfo");
return "main";
}
}
拦截器
package com.company.congfig;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//判断什么情况下没有登录
HttpSession session = request.getSession();
//登录页面也放行
if(request.getRequestURI().contains("login")){
return true;
}
if(session.getAttribute("userLoginInfo")!=null){
return true;
}
//其他情况不放行
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
return false;
}
}
index
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/10/23 0023
Time: 21:18
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/user/goLogin">登录页面</a>
<a href="${pageContext.request.contextPath}/user/main">首页</a>
</body>
</html>
首页
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/10/23 0023
Time: 21:32
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>首页</h1>
<span>${username}</span>
<p>
<a href="${pageContext.request.contextPath}/user/goOut">注销</a>
</p>
</body>
</html>
登录页面
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/10/23 0023
Time: 21:32
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<%--再web-inf下的所有页面或者资源,只能通过controller或者servlet来访问--%>
<title>登录页面</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/user/login" method="get">
用户名:<input type="text" name="username">
密码:<input type="text" name="pwd">
<input type="submit" value="提交">
</form>
</body>
</html>
文件上传和下载
前端表单要求,为了能上传文件,必须将表单的method设置为post,并将enctype设置为multipart/form-data,只有在这样的情况下,浏览器才会把用户选择的文件以二进制数据发送给服务器
对表单中的enctype属性做详细的说明:
application/x-www=form-urlencoded:默认方式,只处理表单域中的value属性值,采用这种编码方式的表单会将表单域中的值处理成URL编码方式
multipart/form-data:这种编码方式会以二进制流的方式来处理表单数据,这种编码方式会把文件域指定文件的内容也封装到请求参数中,不会对字符编码
text/plain:除了把空格转换为“+”号外,其他字符都不做编码处理,这种方式适用直接通过表单发送邮件
<form action="" enctype="multipart/form-data" method="post">
<input type="file" name="file">
<input type="submit">
</form>
文件上传
导入文件上传的jar包,commons-fileupload,Maven会自动帮我们导入他的依赖包commons-io包
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
配置bean:multipartResolver
<!--文件上传配置-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--请求的编码格式,必须和jsp的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1-->
<property name="defaultEncoding" value="utf-8"/>
<!--上传文件大小上限,单位为字节(10485760)-->
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="40960"/>
</bean>
controller
package com.company.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
@RestController
public class FileController {
//@RequestParam("file") 将name=file控件得到的文件封装成CommonsMultipartFile对象
//批量上传CommonsMultiPart则为数组即可
@RequestMapping("/upload")
public String fileUpload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException{
//获取文件名:file.getOriginalFilename();
String uploadFileName = file.getOriginalFilename();
//如果文件为空,直接回到首页
if("".equals(uploadFileName)){
return "redirect:/index.jsp";
}
System.out.println("上传文件名:"+uploadFileName);
//上传路径保存设置
String path = request.getServletContext().getRealPath("/upload");
//如果路径不存在,创建一个
File realPath = new File(path);
if(!realPath.exists()){
realPath.mkdir();
}
System.out.println("文件上传保存地址:"+realPath);
InputStream is = file.getInputStream();//文件输入流
OutputStream os = new FileOutputStream(new File(realPath,uploadFileName));//文件输入流
//读取写出
int len = 0;
byte[] buffer = new byte[1024];
while((len=is.read(buffer))!=-1){
os.write(buffer,0,len);
os.flush();
}
os.close();
is.close();
return "redirect:/index.jsp";
}
}
第二种方式
@RequestMapping("/upload2")
public String fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException{
//上传路径保存设置
String path = request.getServletContext().getRealPath("/upload");
//如果路径不存在,创建一个
File realPath = new File(path);
if(!realPath.exists()){
realPath.mkdir();
}
System.out.println("文件上传保存地址:"+realPath);
//通过CommonsMultipartFile的方法直接写文件(注意这个时候)
file.transferTo(new File(realPath+"/"+file.getOriginalFilename()));
return "redirect:/index.jsp";
}
文件下载
@RequestMapping("/downLoad")
public String downLoad(HttpServletResponse response, HttpServletRequest request) throws Exception{
//要下载的图片地址
String path = request.getServletContext().getRealPath("/upload");
String fileName = "学生证首页.jpg";
//设置response响应头
response.reset();//设置页面不缓存,清空buffer
response.setCharacterEncoding("UTF-8");//字符编码
response.setContentType("multipart/form-data");//二进制传输数据
response.setHeader("Content-Disposition","attachment;fileName="+ URLEncoder.encode(fileName,"UTF-8"));
File file = new File(path,fileName);
InputStream is = new FileInputStream(file);
OutputStream os = response.getOutputStream();
//读取写出
int len = 0;
byte[] buffer = new byte[1024];
while((len=is.read(buffer))!=-1){
os.write(buffer,0,len);
os.flush();
}
os.close();
is.close();
return null;
}