SSM整合
学习文档:https://blog.csdn.net/zengwei1973/article/details/105424888
实训项目:https://gitee.com/xinyu-yudian/online-retailers
ssm整合-mybatis
0.创建数据库
1.建立项目结构,在子项目中导入依赖包
<properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> <spring.version>5.3.1</spring.version> </properties> <dependencies> <!--spring依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!--servlet依赖--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!--mybatis依赖--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.7</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.6</version> </dependency> <!--数据源依赖--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.15</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <!--数据库驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.16</version> </dependency> <!--pagehelper分页依赖--> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.2.0</version> </dependency> <!--单元测试--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!--log4j日志--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.3</version> </dependency> <!--jstl依赖--> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!--thymeleaf依赖--> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> <version>3.0.12.RELEASE</version> </dependency> <!--lombok实体注解依赖--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.20</version> </dependency> <!--json相关依赖--> <!--谷歌gson--> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.8</version> </dependency> <!--阿里的--> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>2.0.19</version> </dependency> <!--全局json jackson --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.5</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.5</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.9.5</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.module</groupId> <artifactId>jackson-module-jaxb-annotations</artifactId> <version>2.9.5</version> </dependency> <!--文件上传--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <!--jwt--> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> </dependencies> <build> <finalName>rear-end</finalName> <resources> <resource> <directory>src/main/java</directory> <!--所在的目录--> <includes> <!--包括目录下的.properties,.xml 文件都会被扫描到--> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.*</include> </includes> </resource> </resources> </build>
2.创建配置文件
a. mybatis核心配置文件:mybatis.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <plugins> <!--分页插件--> <plugin interceptor="com.github.pagehelper.PageInterceptor"> <property name="param1" value="value1"/> </plugin> </plugins> </configuration>
b.关联数据库 ---创建database.properties
jdbc.driver=com.mysql.jdbc.Driver
#Mysql8.0以上,增加一个时区的配置,url &serverTimezone=Asia/shanghai
jdbc.url=jdbc:mysql://localhost:3306/数据库连接名?useSSL=false&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456
c. spring 的核心配置文件:spring.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:aop="http://www.springframework.org/schema/aop" 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/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd "> <!--开启注解扫描--> <context:component-scan base-package="com.xinyu"/> <!--生成切面对象--> <aop:aspectj-autoproxy/> <!--连接数据库--> <!--1.导入外部文件--> <context:property-placeholder location="classpath*:mysql.properties"/> <!--2.配置数据源--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> <property name="url" value="${jdbc.url}"/> <property name="testWhileIdle" value="true"/> </bean> <!-- 配置SqlSessionFactory对象 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 注入数据库连接池 --> <property name="dataSource" ref="dataSource"/> <!-- 配置MyBaties全局配置文件:mybatis.xml --> <property name="configLocation" value="classpath:mybatis.xml"/> </bean> <!-- 配置扫描Dao接口包,动态实现Dao接口注入到spring容器中 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 注入sqlSessionFactory --> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> <!-- mapper --> <property name="basePackage" value="com.xinyu.mapper"/> </bean> <bean id="user" class="com.xinyu.entity.User"/> </beans>
d.springmvc核心控制文件
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" 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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--配置注解扫描--> <context:component-scan base-package="com.xinyu"/> <!--加载mvc驱动:自动注册映射器与适配器--> <mvc:annotation-driven /> <!--不过滤静态资源--> <mvc:default-servlet-handler/> <!--静态资源映射--> <!-- <mvc:resources mapping="/js/**" location="/WEB-INF/js/"/>--> <!-- 配置视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 视图前缀 --> <property name="prefix" value="/WEB-INF/html/"/> <!-- 视图后缀 --> <property name="suffix" value=".html"/> </bean> <!--json解析--> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>application/json;charset=utf-8</value> <value>text/html;charset=utf-8</value> </list> </property> </bean> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>application/json; charset=UTF-8</value> <value>application/x-www-form-urlencoded; charset=UTF-8</value> </list> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> <!--文件上传--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--上传文件总大小--> <property name="maxUploadSize" value="5242800"/> <!--上传单个文件的大小--> <property name="maxUploadSizePerFile" value="5242800"/> <!--临时文件路径--> <property name="uploadTempDir" value="/fileUpLoad/temp"/> <!--上传文件的编码类型--> <property name="defaultEncoding" value="UTF-8"/> </bean> </beans>
e.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"> <display-name>Archetype Created Web Application</display-name> <!--配置前端控制器--> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 读取springmvc --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <!-- 优先级 --> <load-on-startup>1</load-on-startup> </servlet> <!-- 配置拦截路径url--> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- spring上下文监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 加载Spring --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:spring.xml</param-value> </context-param> <!--配置乱码过滤器--> <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>
3.工具类-utils
a.JWT
public class JWTUtils { //设置密钥 private static final String SECRET = "xinyu"; //获取token public static String getToken(Integer id,String username,String password){ //创建集合用于装接收的数据 Map<String,Object> claims = new HashMap<String,Object>(); claims.put("id",id); claims.put("username",username); claims.put("password",password); //创建jwt对象 JwtBuilder jwtBuilder = Jwts.builder(); //签发算法,设置密钥 jwtBuilder.signWith(SignatureAlgorithm.HS512,SECRET); //添加数据 jwtBuilder.setClaims(claims); //设置签发时间 jwtBuilder.setIssuedAt(new Date(System.currentTimeMillis())); //设置过期时间-5秒 jwtBuilder.setExpiration(new Date(System.currentTimeMillis() + 1000*5)); //设置签发人 jwtBuilder.setSubject(id.toString()); //生成token return jwtBuilder.compact(); } //解析token public static Map<String,Object> parseToken(String token){ Jwt jwt = Jwts.parser().setSigningKey(SECRET).parse(token); Map<String,Object> claims = (Map<String,Object>)jwt.getBody(); return claims; } public static void main(String[] args) { String token = JWTUtils.getToken(2,"admin","111111"); System.out.println(token); Map<String,Object> claims = JWTUtils.parseToken(token); String name = (String) claims.get("username"); System.out.println(name); } }
b.切面
@Component @Aspect public class mothAspect { @Pointcut("execution(* com.xinyu.service.impl.*.*(..))") public void pointcut(){ } @Before("pointcut()") public void before(){ System.out.println("before..."); } @After("pointcut()") public void after(){ System.out.println("after..."); } @AfterReturning("pointcut()") public void afterReturning(){ System.out.println("afterReturning..."); } @AfterThrowing(value = "pointcut()",throwing = "ex") public void afterThrowing(Exception ex){ System.out.println("afterThrowing..."+ex.getMessage()); } @Around("pointcut()") public Object around(ProceedingJoinPoint jp) throws Throwable { System.out.println("aroundBefore..."); Object obj = jp.proceed(); System.out.println("aroundAfter..."); return obj; } }
c.图片验证码
public class Code { public static final String VERIFY_CODES = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private static Random random = new Random(); public static void main(String[] args) throws Exception { //调用主方法,在D盘产生名为a的验证码图片,并在服务端打印验证码内容 OutputStream fos=new FileOutputStream("d://a.jpg"); String s = Code.outputVerifyImage(100, 50, fos, 4); System.out.println(s); //此为CheckCodeServlet写入,在jsp中可直接调用 // 如:“<img id="checkCodeImg" src="/brand-demo/CheckCodeServlet">” //ServletOutputStream os = response.getOutputStream(); //String s = CheckCodeUtil.outputVerifyImage(100, 50, os, 4); } /** * 输出随机验证码图片流,并返回验证码值(一般传入输出流,响应response页面端,Web项目用的较多) * * @param width 图片宽度 * @param height 图片高度 * @param os 输出流 * @param verifySize 数据长度 * @return 验证码数据 * @throws IOException */ public static String outputVerifyImage(int width, int height, OutputStream os, int verifySize) throws IOException { String verifyCode = generateVerifyCode(verifySize); outputImage(width, height, os, verifyCode); return verifyCode; } /** * 使用系统默认字符源生成验证码 * * @param verifySize 验证码长度 * @return */ public static String generateVerifyCode(int verifySize) { return generateVerifyCode(verifySize, VERIFY_CODES); } /** * 使用指定源生成验证码 * * @param verifySize 验证码长度 * @param sources 验证码字符源 * @return */ public static String generateVerifyCode(int verifySize, String sources) { // 未设定展示源的字码,赋默认值大写字母+数字 if (sources == null || sources.length() == 0) { sources = VERIFY_CODES; } int codesLen = sources.length(); Random rand = new Random(System.currentTimeMillis()); StringBuilder verifyCode = new StringBuilder(verifySize); for (int i = 0; i < verifySize; i++) { verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1))); } return verifyCode.toString(); } /** * 生成随机验证码文件,并返回验证码值 (生成图片形式,用的较少) * * @param w * @param h * @param outputFile * @param verifySize * @return * @throws IOException */ public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException { String verifyCode = generateVerifyCode(verifySize); outputImage(w, h, outputFile, verifyCode); return verifyCode; } /** * 生成指定验证码图像文件 * * @param w * @param h * @param outputFile * @param code * @throws IOException */ public static void outputImage(int w, int h, File outputFile, String code) throws IOException { if (outputFile == null) { return; } File dir = outputFile.getParentFile(); //文件不存在 if (!dir.exists()) { //创建 dir.mkdirs(); } try { outputFile.createNewFile(); FileOutputStream fos = new FileOutputStream(outputFile); outputImage(w, h, fos, code); fos.close(); } catch (IOException e) { throw e; } } /** * 输出指定验证码图片流 * * @param w * @param h * @param os * @param code * @throws IOException */ public static void outputImage(int w, int h, OutputStream os, String code) throws IOException { int verifySize = code.length(); BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Random rand = new Random(); Graphics2D g2 = image.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // 创建颜色集合,使用java.awt包下的类 Color[] colors = new Color[5]; Color[] colorSpaces = new Color[]{Color.WHITE, Color.CYAN, Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE, Color.PINK, Color.YELLOW}; float[] fractions = new float[colors.length]; for (int i = 0; i < colors.length; i++) { colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)]; fractions[i] = rand.nextFloat(); } Arrays.sort(fractions); // 设置边框色 g2.setColor(Color.GRAY); g2.fillRect(0, 0, w, h); Color c = getRandColor(200, 250); // 设置背景色 g2.setColor(c); g2.fillRect(0, 2, w, h - 4); // 绘制干扰线 Random random = new Random(); // 设置线条的颜色 g2.setColor(getRandColor(160, 200)); for (int i = 0; i < 20; i++) { int x = random.nextInt(w - 1); int y = random.nextInt(h - 1); int xl = random.nextInt(6) + 1; int yl = random.nextInt(12) + 1; g2.drawLine(x, y, x + xl + 40, y + yl + 20); } // 添加噪点 // 噪声率 float yawpRate = 0.05f; int area = (int) (yawpRate * w * h); for (int i = 0; i < area; i++) { int x = random.nextInt(w); int y = random.nextInt(h); // 获取随机颜色 int rgb = getRandomIntColor(); image.setRGB(x, y, rgb); } // 添加图片扭曲 shear(g2, w, h, c); g2.setColor(getRandColor(100, 160)); int fontSize = h - 4; Font font = new Font("Algerian", Font.ITALIC, fontSize); g2.setFont(font); char[] chars = code.toCharArray(); for (int i = 0; i < verifySize; i++) { AffineTransform affine = new AffineTransform(); affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize / 2, h / 2); g2.setTransform(affine); g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10); } g2.dispose(); ImageIO.write(image, "jpg", os); } /** * 随机颜色 * * @param fc * @param bc * @return */ private static Color getRandColor(int fc, int bc) { if (fc > 255) { fc = 255; } if (bc > 255) { bc = 255; } int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); } private static int getRandomIntColor() { int[] rgb = getRandomRgb(); int color = 0; for (int c : rgb) { color = color << 8; color = color | c; } return color; } private static int[] getRandomRgb() { int[] rgb = new int[3]; for (int i = 0; i < 3; i++) { rgb[i] = random.nextInt(255); } return rgb; } private static void shear(Graphics g, int w1, int h1, Color color) { shearX(g, w1, h1, color); shearY(g, w1, h1, color); } private static void shearX(Graphics g, int w1, int h1, Color color) { int period = random.nextInt(2); boolean borderGap = true; int frames = 1; int phase = random.nextInt(2); for (int i = 0; i < h1; i++) { double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames); g.copyArea(0, i, w1, 1, (int) d, 0); if (borderGap) { g.setColor(color); g.drawLine((int) d, i, 0, i); g.drawLine((int) d + w1, i, w1, i); } } } private static void shearY(Graphics g, int w1, int h1, Color color) { int period = random.nextInt(40) + 10; // 50; boolean borderGap = true; int frames = 20; int phase = 7; for (int i = 0; i < w1; i++) { double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames); g.copyArea(i, 0, 1, h1, 0, (int) d); if (borderGap) { g.setColor(color); g.drawLine(i, (int) d, i, 0); g.drawLine(i, (int) d + h1, i, h1); } } } }
d.MD5加密
public class MD5 { // 加盐位置 public static int[] salts = { 3, 8, 16, 22, 25 }; public static String md5(String str) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] srcBytes = str.getBytes(StandardCharsets.UTF_8); md5.update(srcBytes); byte[] resultBytes = md5.digest(); //转为16进制 String result = ""; for(byte b : resultBytes) { String temp = Integer.toHexString(b & 0xff); if(temp.length() == 1) { temp = "0" + temp; } result = result + temp; } return result; } // 加盐方法 public static String addSalt(String md5Str) { StringBuffer sb = new StringBuffer(md5Str); for (int n = salts.length - 1; n >= 0; n--) { int r = (int) (Math.random() * 10); // 插入随机数 sb.insert(salts[n], r); } return sb.toString(); } // 去盐方法 public static String delSalt(String md5Str) { StringBuffer sb = new StringBuffer(md5Str); for (int n = 0; n < salts.length; n++) { sb.deleteCharAt(salts[n]); } return sb.toString(); } public static void main(String[] args) { try { String pwd = MD5.md5("123456"); System.out.println("加盐前"+pwd); String slatPwd = addSalt(pwd); System.out.println("加盐后"+slatPwd); String delPwd = delSalt(slatPwd); System.out.println("解盐后"+delPwd); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } }
跨域请求处理
import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CrossingFilter implements Filter { private boolean isCross = false; @Override public void destroy() { isCross = false; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (isCross) { HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; System.out.println("拦截请求: " + httpServletRequest.getServletPath()); httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); // httpServletResponse.setHeader("Access-Control-Allow-Methods", "*"); // 表示所有请求都有效 httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); httpServletResponse.setHeader("Access-Control-Max-Age", "0"); httpServletResponse.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token"); httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true"); httpServletResponse.setHeader("XDomainRequestAllowed", "1"); } chain.doFilter(request, response); } @Override public void init(FilterConfig filterConfig) throws ServletException { String isCrossStr = filterConfig.getInitParameter("IsCross"); isCross = isCrossStr.equals("true") ? true : false; System.out.println("跨域开启状态:" + isCrossStr); } }
<!--web.xml 配置跨域过滤器 --> <filter> <filter-name>CrossingFilter</filter-name> <filter-class>com.xinyu.utils.CrossingFilter</filter-class> <init-param> <param-name>IsCross</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>CrossingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>