这是最基础的SSM整合。并细心的写了注释哦~ 写的不好的地方大家多多见谅,灰常荣幸能为我指出毛病~ ~ ~///(^ v ^)\\ ~ ~ ~
Maven项目结构
pom.xml太长,最后再贴出
首先贴出web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>testSSM</display-name>
<!-- 声明应用范围(整个WEB项目)内的上下文初始化参数 -->
<!-- 初始化spring容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- ContextLoaderListener的作用就是启动Web容器时,自动装配Spring applicationContext的配置信息 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置加载springMVC -->
<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-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
<!-- 配置跨域访问,可忽略
<filter>
<filter-name>cors</filter-name>
<filter-class>com.tuoke.filter.SimpleCORSFilter</filter-class>
<init-param>
<param-name>permitUrl</param-name>
<param-value>
http://localhost:8080,
http://localhost:8082,
http://localhost:8089,
</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> -->
然后是mybatis-config.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>
<settings>
<!-- 数据可以为空 -->
<setting name="jdbcTypeForNull" value="NULL"/>
<!-- 驼峰命名法 比如:
oracle中last_name。
在java中可以写为lastName
-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!-- 延迟加载(赖加载) 也就是按需加载 -->
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
<!-- DB_VENDOR:得到数据库厂商标识-->
<databaseIdProvider type="DB_VENDOR">
<property name="MySQL" value="mysql"/>
<property name="Oracle" value="oracle"/>
</databaseIdProvider>
</configuration>
接着是我们的spring-servlet.xml(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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 该配置表示:只扫描注释配置为@Controller的类 -->
<context:component-scan base-package="com.atguigu.mybatis" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 主要就是为了Spring MVC来用的,提供Controller请求转发,json自动转换等功能 -->
<mvc:annotation-driven/>
<!--使用默认的Servlet来响应静态文件-->
<mvc:default-servlet-handler/>
</beans>
连接数据库的proerties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=123456
然后是我们的applicationContext.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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd">
<!-- 该配置表示:仅仅不扫描注释配置为@Controller的类 -->
<context:component-scan base-package="com.atguigu.mybatis">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- properties资源加载 -->
<context:property-placeholder location="classpath:dbconfig.properties"/>
<!-- 连接数据库 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="driverClass" value="${jdbc.driver}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- spring事务管理 -->
<bean id="manager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 开启基于注解的事务 -->
<tx:annotation-driven transaction-manager="manager"/>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:mybatis/mapper/*.xml"/>
</bean>
<!-- -扫描映射器并让它们自动装配-->
<!-- 这个配置如何出现could not Autowired No beans of 'EmployeeMapper' type found
那就用下面注释的配置 -->
<!--<mybatis:scan base-package="com.atguigu.mybatis.dao"/>-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.atguigu.mybatis.dao"/>
</bean>
</beans>
剩下的那些jsp和java文件直接贴代码了,方便大家测试
Employee
package com.atguigu.mybatis.bean;
public class Employee {
private Integer id;
private String lastName;
private String email;
private String gender;
public Employee() {
}
public Employee(String lastName, String email, String gender) {
this.lastName = lastName;
this.email = email;
this.gender = gender;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
JsonUsers Json数据转换(Bean)
package com.tuoke.pojo;
public class JsonUsers {
String name;
Object staffName[];
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Object[] getStaffName() {
return staffName;
}
public void setStaffName(Object[] staffName) {
this.staffName = staffName;
}
}
EmployeeMapper (接口)
package com.atguigu.mybatis.dao;
import com.atguigu.mybatis.bean.Employee;
import java.util.List;
public interface EmployeeMapper {
public List<Employee> getEmps();
public Employee EmpsByName(Integer id);
public int addEmps(Employee employee);
public void deleteByName(String name);
public int updateByName(Employee employee);
}
EmployeeMapper.xml (实现dao接口)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.atguigu.mybatis.dao.EmployeeMapper">
<select id="getEmps" resultType="com.atguigu.mybatis.bean.Employee">
select * from employee
</select>
<!-- public Employee EmpsByName(String lastName); -->
<select id="EmpsByName" resultType="com.atguigu.mybatis.bean.Employee">
select * from employee where id = #{id}
</select>
<!--public void addEmps(Employee employee);-->
<insert id="addEmps">
insert into employee(last_name,email,gender) values(#{lastName},#{email},#{gender})
</insert>
<!-- public Employee deleteByName(String name); -->
<delete id="deleteByName">
delete from employee where last_name = #{lastName}
</delete>
<!-- public Employee updateByName(String name); -->
<update id="updateByName">
update employee set last_name = #{lastName},email = #{email},gender=#{gender} where id = #{id}
</update>
</mapper>
EmployeeService
package com.atguigu.mybatis.service;
import com.atguigu.mybatis.bean.Employee;
import com.atguigu.mybatis.dao.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class EmployeeService {
@Autowired
private EmployeeMapper employeeMapper;
public List<Employee> getEmps(){
return employeeMapper.getEmps();
}
public Employee EmpsByName(Integer id){
return employeeMapper.EmpsByName(id);
}
public int addEmps(Employee employee){
return employeeMapper.addEmps(employee);
}
public void deleteByName(String name){
employeeMapper.deleteByName(name);
}
public int update(Employee employee){
return employeeMapper.updateByName(employee);
}
}
controller
package com.atguigu.mybatis.controller;
import com.atguigu.mybatis.bean.Employee;
import com.atguigu.mybatis.service.EmployeeService;
import net.sf.json.JSONArray;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Map;
@Controller
public class EmployeeController {
@Autowired
EmployeeService employeeService;
@RequestMapping("/getEmps")
public String getEmps(Map<String,Object> map){
List<Employee> emps = employeeService.getEmps();
map.put("emps",emps);
JSONArray jsonArray = JSONArray.fromObject(emps);
System.out.println("emps "+jsonArray);
JSONArray jsonArray2 = JSONArray.fromObject(map);
System.out.println("map "+jsonArray2);
return "list";
}
@RequestMapping("/add")
public String add(){
return "add";
}
@RequestMapping("/addEmp")
public String addEmps(Employee employee){
int i = employeeService.addEmps(employee);
if(i>0){
System.out.println("success");
}else{
System.out.println("error");
}
return "redirect:/getEmps";
}
@RequestMapping(value = "/{name}/delete")
public String deleteByName(@PathVariable String name){
employeeService.deleteByName(name);
System.out.println("delete"+name);
return "redirect:/getEmps";
}
@RequestMapping("/{id}/likeName")
public String likeName(@PathVariable Integer id,Model model ){
Employee employee = employeeService.EmpsByName(id);
model.addAttribute("employee",employee);
return "update";
}
@RequestMapping("/{id}/update")
public String updateByName(Employee employee){
int update = employeeService.update(employee);
if(update>0){
System.out.println("success");
}else{
System.out.println("error");
}
return "redirect:/getEmps";
}
}
AppController Json数据转换,可忽略不看
package com.tuoke.controller;
import com.tuoke.pojo.JsonUsers;
import com.tuoke.pojo.Users;
import com.tuoke.service.UsersService;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
public class UsersController {
@Autowired
private UsersService usersService;
@RequestMapping(value = "{name}", method = RequestMethod.GET)
public @ResponseBody JsonUsers getUsersJson(@PathVariable String name){
List<Users> users = usersService.getUsers();
JsonUsers json = new JsonUsers();
json.setName(name);
json.setStaffName(new Object[]{users});
return json;
}
@RequestMapping(value = "/add/{phone}/{grade}/{password}/{name}/{referees}", method = RequestMethod.GET)
public @ResponseBody JsonUsers insertUsers(@PathVariable String phone,@PathVariable String grade
,@PathVariable String password,@PathVariable String name,@PathVariable String referees){
Users user = new Users(phone,grade,password,name,referees);
usersService.insert(user);
JsonUsers json = new JsonUsers();
json.setName(name);
System.out.println(phone+" "+grade+" "+password+" "+name+" "+referees);
return json;
}
@RequestMapping(value = "/like/{referees}",method = RequestMethod.GET)
public @ResponseBody JsonUsers usersByReferees(@PathVariable String referees){
List<Users> users = usersService.usersByreferees(referees);
JsonUsers json = new JsonUsers();
json.setName(referees);
json.setStaffName(new Object[]{users});
return json;
}
}
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="getEmps">查询所有员工</a><br><br>
<button><a href="add"> 添加用户 </a></button><br><br>
</body>
</html>
list.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>员工表</title>
</head>
<body>
<table border="1" cellpadding="10" cellspacing="1">
<tr>
<th>id</th>
<th>lastName</th>
<th>email</th>
<th>gender</th>
<th colspan="2">操作</th>
</tr>
<c:forEach items="${emps}" var="emp">
<tr>
<td>${emp.id}</td>
<td>${emp.lastName}</td>
<td>${emp.email}</td>
<td>${emp.gender}</td>
<td><a href="${emp.id}/likeName"> 修改 </a></td>
<td><a href="${emp.lastName}/delete">删除</a> </td>
</tr>
</c:forEach>
</table>
</body>
</html>
add.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2019/9/6
Time: 13:39
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>
<form action="addEmp" method="post">
用户名:<input type="text" name="lastName"><br>
邮 箱<input type="text" name="email"><br>
性 别<input type="text" name="gender"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
update.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<sf:form action="update" method="post" modelAttribute="employee">
<sf:input path="id" disabled="true"/>
<sf:input path="lastName"/>
<sf:input path="email"/>
<sf:input path="gender"/>
<input type="submit" value="提交">
</sf:form>
</body>
</html>
最后贴上最长的pom.xml文件。因为做了很多测试,比如转换Json等。所以比较长。但是不影响的哈。
<?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>com.test</groupId>
<artifactId>testSSM</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>testSSM Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.6.RELEASE</version>
</dependency><!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.taglibs/taglibs-standard-spec -->
<dependency>
<groupId>org.apache.taglibs</groupId>
<artifactId>taglibs-standard-spec</artifactId>
<version>1.2.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.taglibs/taglibs-standard-impl -->
<dependency>
<groupId>org.apache.taglibs</groupId>
<artifactId>taglibs-standard-impl</artifactId>
<version>1.2.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sourceforge.cglib/com.springsource.net.sf.cglib -->
<dependency>
<groupId>net.sourceforge.cglib</groupId>
<artifactId>com.springsource.net.sf.cglib</artifactId>
<version>2.2.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/com.springsource.org.aspectj.weaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>com.springsource.org.aspectj.weaver</artifactId>
<version>1.6.4.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aopalliance/com.springsource.org.aopalliance -->
<dependency>
<groupId>org.aopalliance</groupId>
<artifactId>com.springsource.org.aopalliance</artifactId>
<version>1.0.0</version>
</dependency><!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjrt -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/cglib/cglib-nodep -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>2.1_3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
</dependencies>
<build>
<finalName>testSSM</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
package com.tuoke.filter;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class SimpleCORSFilter implements Filter {
// 存放跨域的白名单 配置跨域访问的filter
private String[] permitUrl;
@Override
public void doFilter(ServletRequest req, ServletResponse res,FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
String myOrigin = request.getHeader("origin");
boolean isValid = false;
for (String ip : permitUrl) {
if (myOrigin != null && myOrigin.equals(ip)) {
isValid = true;
break;
}
}
response.setContentType("textml;charset=UTF-8");
response.setHeader("Access-Control-Allow-Origin", isValid ? myOrigin : "null");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.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");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("P3P", "CP=\"NON DSP COR CURa ADMa DEVa TAIa PSAa PSDa IVAa IVDa CONa HISa TELa OTPa OUR UNRa IND UNI COM NAV INT DEM CNT PRE LOC\"");
response.setHeader("XDomainRequestAllowed", "1");
chain.doFilter(req, res);
}
// 初始化方法,这里的permitUrl是在web.xml中配置的
@Override
public void init(FilterConfig filterConfig) throws ServletException {
String urls = filterConfig.getInitParameter("permitUrl");
if (urls != null) {
urls = urls.replaceAll("\\n", "").replaceAll("\\r", "").replaceAll("\\t", "");
}
if (!"".equals(urls) && urls != null) {
permitUrl = urls.split(",");
}
if (permitUrl != null) {
for (int i = 0; i < permitUrl.length; i++) {
permitUrl[i] = permitUrl[i].trim();
}
}
}
// 销毁方法
@Override
public void destroy() {
}
}