通过idea创建一个springweb项目后要使用mvc首先要在pom.xml导入相关的依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.10</version>
</dependency>
第一步
在web-inf目录下进行第一步配置,先说一下,这个配置文件的模板是在汤姆猫配置文件里面截取的
截取替换原本的web.xml内容后进行相关配置,配置核心映射文件要用到resources文件夹下面的配置文件,下一步配置
<?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">
<!-- 配置spring前置控制器核心-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置参数加载spring核心映射文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
</servlet>
<!-- 映射地址-->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 配置过滤器 -->
<filter>
<filter-name>nmdwsm</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>nmdwsm</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
第二步
在resources下面创建配置文件如springmvc.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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/aop ">
<!--扫描-->
<context:component-scan base-package="com.entor.controller"></context:component-scan>
<!--使用注解驱动装配处理对象-->
<mvc:annotation-driven></mvc:annotation-driven>
<!--对静态文件不做请求拦截处理-->
<mvc:default-servlet-handler ></mvc:default-servlet-handler>
<!--配置资源视图解释器,根据服务器返回的值选择选择不同视图显示器,渲染视图界面并返回-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
第三步
创建一个测试类,来进行请求转发到这个自带的jsp文件
package com.entor.controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
//该类用作请求处理类
@org.springframework.stereotype.Controller
@RequestMapping("/hello")
public class Controller {
// 处理请求地址,如果类上也有相同注解,请求地址需要先拼接类上的地址
// 方法返回逻辑视图名称,通过配置文件的视图解释器,知道对应的视图进行展示
// 根据查找规则,前缀加上视图名称再加上后缀,此方法犯规对应的视图文件是
// /index.jsp
@PostMapping("")
@RequestMapping(value = "index",method = {RequestMethod.GET,RequestMethod.POST})
public String index(){
System.out.println("hellow gay");
return "index";
}
}
上面的第一个注释表示请求的类型和括号里面可以填拦截的访问url,第二个同样是相同的功能,但是可以同时拦截get和post请求
spring进行多个参数的接收,首先创建好一个实体类,之后通过实体类的字段和前台传来的字段进行映射,这里如果学过servlet会很容易理解,map的功能和request.serAttribute的功能差不多,另外前台传来的参数全部是字符串,所以要对时间类型进行相关处理
//客户端传递多个参数可以封装成对象,
@PostMapping("/param4")
public String zz4(User user, Map<String, Object> map) throws UnsupportedEncodingException {
System.out.println("param4");
map.put("user", user);
return "show";
}
//定义处理日期的规则,参数绑定
@InitBinder
public void zz5(WebDataBinder binder){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
CustomDateEditor customDateEditor = new CustomDateEditor(format, true);
// 指定对象和规则
binder.registerCustomEditor(Data.class,customDateEditor);
}
这个是通过绑定的方式对时间对象进行处理,还有可以通过注解的方式对日期对象进行处理,这里通过对象映射获取前台传递来的参数,学过mybatis的都知道,这些框架可以通过set方法吧获取的变量映射到实体类对应的属性中
@JsonFormat(pattern = "yyyy-MM-dd",timezone = "GMT+8")//格式化日期类型格式
private Date birthday;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Timestamp createTime;
文件上传相关,首先是依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
<!--把服务器返回的对象数据转换成json格式字符串-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.3</version>
</dependency>
<!--通用的工具类包-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</version>
</dependency>
<!--强大的工具类包-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.3.9</version>
</dependency>
<!--文件上传依赖包-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
然后是配置文件,在resources中
<!--文件上传解释器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--字符编码格式-->
<property name="defaultEncoding" value="utf-8"/>
<!--上传文件内存最大缓冲区,单位是字节-->
<property name="maxInMemorySize" value="1000000"/>
<!--上传文件最大值,单位是字节-->
<property name="maxUploadSize" value="10000000"/>
</bean>
前台
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>文件上传</title>
</head>
<body>
<form action="uploadFile" method="post" enctype="multipart/form-data">
文件:<input type="file" name="file"><br>
<input type="submit" value="上传"><br>
</form>
<form action="uploadFiles" method="post" enctype="multipart/form-data">
文件1:<input type="file" name="file"><br>
文件2:<input type="file" name="file"><br>
文件3:<input type="file" name="file"><br>
<input type="submit" value="上传"><br>
</form>
</body>
</html>
后台
package com.entor.controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
@RestController
public class UploadController {
@PostMapping(value = "/uploadFile",produces = "application/json;charset=utf-8")
public String uploadFile(MultipartFile file, HttpServletRequest request) throws IOException {
String realPath = request.getServletContext().getRealPath("/upload/");
File f = new File(realPath);
if(!f.exists()){
f.mkdir();
}
String fileName = file.getOriginalFilename();
String contentType = file.getContentType();
long size = file.getSize();
System.out.println("文件名称:"+fileName);
System.out.println("文件类型:"+contentType);
System.out.println("文件大小:"+size);
//文件上传
file.transferTo(new File(realPath,fileName));
return "上传成功";
}
@PostMapping(value = "/uploadFiles",produces = "application/json;charset=utf-8")
public String uploadFiles(MultipartFile[] file, HttpServletRequest request) throws IOException {
String realPath = request.getServletContext().getRealPath("/upload/");
File f = new File(realPath);
if(!f.exists()){
f.mkdir();
}
for(MultipartFile file1:file){
String fileName = file1.getOriginalFilename();
String contentType = file1.getContentType();
long size = file1.getSize();
System.out.println("文件名称:"+fileName);
System.out.println("文件类型:"+contentType);
System.out.println("文件大小:"+size);
//文件上传
file1.transferTo(new File(realPath,fileName));
}
return "上传成功";
}
}
拦截器
package com.entor.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
public class TestInterceptorPro implements HandlerInterceptor {
// 你这瓜保熟吗?在业务处理器处理请求之前被调用。
// 预处理,可以进行编码、安全控制、权限校验等处理,返回true和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("咋地");
Map<String, Object> model = modelAndView.getModel();
System.out.println(model.get("msg"));
model.put("msg2","postHandle");
modelAndView.setViewName("nmdwsm");
}
//萨日朗
//在DispatcherServlet完全处理完请求后被调用
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("跑路");
}
}
测试
package com.entor.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class TestSequence {
@RequestMapping(value = "/handle", method = {RequestMethod.POST, RequestMethod.GET})
public String index(Model model){
model.addAttribute("msg","nmdwsm");
return "index";
}
}
前台
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2021/9/26 0026
Time: 上午 11: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>
${msg}<br>
${msg2}<br>
</body>
</html>
多个拦截器的执行顺序
划重点,无参配置,
package com.entor.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableWebMvc//相当于<mvc:annotation-driven></mvc:annotation-driven>
@ComponentScan(basePackages = "com.entor.controller")
public class SpringMvcConfig implements WebMvcConfigurer {
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
internalResourceViewResolver.setPrefix("/");
internalResourceViewResolver.setSuffix(".jsp");
registry.viewResolver(internalResourceViewResolver);
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
}
}
配置web.xml的无参类
package com.entor.config;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
//web.xml配置类
public class WebConfig implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
//加载springmvc配置类
context.register(SpringMvcConfig.class);
//配置内置参数
DispatcherServlet servlet = new DispatcherServlet(context);
ServletRegistration.Dynamic springmvc = servletContext.addServlet("springmvc", servlet);
//配置url
springmvc.addMapping("/");
}
}