目录
SpringMVC拦截器_拦截器过滤敏感词案例
SpringMVC跨域请求_同源策略
SpringMVC跨域请求_跨域请求
SpringMVC跨域请求_控制器接收跨域请求
SSM整合_需求分析
SSM整合_创建父工程
SSM整合_创建dao子工程
SSM整合_创建service子工程
SSM整合_创建controller子工程
SSM整合_运行项目
SpringMVC拦截器_拦截器过滤敏感词案例
接下来我们编写一个拦截器案例,需求如下: 在系统中,我们需要将所有响应中的一些敏感词替换为 *** ,此时可以使用拦截器达到要求:
1、编写控制器方法
@RequestMapping("/m2") public String m2(Model model){ model.addAttribute("name","大笨蛋"); return "result"; }
2、编写敏感词拦截器
// 敏感词拦截器 public class SensitiveWordInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { return true; } @Override
// 敏感词拦截器 public class SensitiveWordInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { return true; } @Override public void postHandle(HttpServletRequest request,HttpServletResponse response, Object handler, ModelAndView modelAndView) { // 敏感词列表 String[] sensitiveWords = {"坏人","暴力","笨蛋"}; // 获取model中所有数据 Map<String, Object> model = modelAndView.getModel(); Set<Map.Entry<String, Object>> entries = model.entrySet(); // 遍历model for (Map.Entry<String, Object> entry : entries) { String key = entry.getKey(); String value = entry.getValue().toString(); // 将model值和敏感词列表遍历比对 for (String sensitiveWord : sensitiveWords) { // 如果model值包含敏感词,则替换 if(value.contains(sensitiveWord)){ String newStr = value.replaceAll(sensitiveWord, "***"); model.put(key,newStr); } } } } }
3、配置拦截器
<!-- 配置拦截器--> <mvc:interceptors> <!-- 敏感词拦截器 --> <mvc:interceptor> <mvc:mapping path="/**"/> <bean class="com.tong.interceptor.SensitiveWordInterceptor"></bean> </mvc:interceptor> </mvc:interceptors>
SpringMVC跨域请求_同源策略
同源策略是浏览器的一个安全功能。同源,指的是两个URL的协 议,域名,端口相同。浏览器出于安全方面的考虑,不同源的客户 端脚本在没有明确授权的情况下,不能读写对方资源。
哪些不受同源策略限制:
最容易收到同源策略影响的就是Ajax请求。
SpringMVC跨域请求_跨域请求
当请求URL的协议、域名、端口三者中任意一个与当前页面URL不 同时即为跨域。浏览器执行JavaScript脚本时,会检查当前请求是否 同源,如果不是同源资源,就不会被执行。
比如:
1、编写控制器方法
@RequestMapping("/m3") @ResponseBody public String m3(){ System.out.println("测试跨域请求"); return "success"; }
2、编写JSP页面,发送异步请求
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>跨域请求</title> <script src="/js/jquery2.1.1.min.js"></script> <script> $(function (){ $("#btn").click(function() { //$.get("http://localhost:8080/m3",function(data) { // console.log(data); // }) $.get("http://127.0.0.1:8080/m3",function(data) { console.log(data); }) }) }) </script> </head> <body> <button id="btn">异步请求</button> </body> </html>
SpringMVC跨域请求_控制器接收跨域请求
SpringMVC提供了注解@CrossOrigin解决跨域问题。用法如下:
@RequestMapping("/m3")
@ResponseBody
// 如果请求从http://localhost:8080发出,则允许跨域访问
@CrossOrigin("http://localhost:8080")
public String m3(){
System.out.println("测试跨域请求");
return "success";
}
SSM整合_需求分析
接下来我们使用Maven+Spring+MyBatis+SpringMVC完成一个案 例,案例需求为在页面可以进行添加学生+查询所有学生!
案例需要使用以下技术:
1、使用Maven创建聚合工程,并使用Maven的tomcat插件运行工 程
2、使用Spring的IOC容器管理对象
3、使用MyBatis操作数据库
4、使用Spring的声明式事务进行事务管理
5、使用SpringMVC作为控制器封装Model并跳转到JSP页面展示数据
6、使用Junit测试方法
7、使用Log4j在控制台打印日志
案例的编写流程如下:
1、创建maven父工程,添加需要的依赖和插件
2、创建dao子工程,配置MyBatis操作数据库,配置Log4j在控制台 打印日志。
3、创建service子工程,配置Spring声明式事务
4、创建controller子工程,配置SpringMVC作为控制器,编写JSP页 面展示数据。
5、每个子工程都使用Spring进行IOC管理
# 准备数据库数据
CREATE DATABASE `student`;
USE `student`;
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) DEFAULT NULL,
`sex` VARCHAR(10) DEFAULT NULL,
`address` VARCHAR(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB CHARSET=utf8;
INSERT INTO `student`(`id`,`name`,`sex`,`address`)
VALUES (1,'程序员','男','北京'),(2,'辛苦学堂','女','北京');
SSM整合_创建父工程
创建maven父工程,添加需要的依赖和插件
<properties>
<!--Spring版本-->
<spring.version>5.2.12.RELEASE</spring.version>
</properties>
<dependencies>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
<!-- druid连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
<!-- MyBatis与Spring的整合包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- springmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</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-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 事务 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
<!-- jstl -->
<dependency>
<groupId>org.apache.taglibs</groupId>
<artifactId>taglibs-standard-spec</artifactId>
<version>1.2.5</version>
</dependency>
<dependency>
<groupId>org.apache.taglibs</groupId>
<artifactId>taglibs-standard-impl</artifactId>
<version>1.2.5</version>
</dependency>
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!-- jsp -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}
</version>
</dependency>
<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- tomcat插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-mavenplugin</artifactId>
<version>2.1</version>
<configuration>
<port>8080</port>
<path>/</path>
<uriEncoding>UTF8</uriEncoding>
<server>tomcat7</server>
<systemProperties>
<java.util.logging.SimpleFormatter.format>
%1$tH:%1$tM:%1$tS %2$s%n%4$s: %5$s%6$s%n
</java.util.logging.SimpleFormatter.format>
</systemProperties>
</configuration>
</plugin>
</plugins>
</build>
SSM整合_创建dao子工程
1、在父工程下创建maven普通java子工程
2、编写实体类
public class Student { private int id; private String name; private String sex; private String address; // 省略getter/setter/tostring/构造方法 }
3、编写持久层接口
@Repository public interface StudentDao { // 查询所有学生 @Select("select * from student") List<Student> findAll(); // 添加学生 @Insert("insert into student values(null,#{name},#{sex},#{address})") void add(Student student); }
4、编写log4j.properties配置文件
log4j.rootCategory=debug, CONSOLE, LOGFILE log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=[%d{MM/dd HH:mm:ss}] %-6r [%15.15t] %-5p %30.30c %x - %m\n
5、编写数据库配置文件druid.properties
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql:///student jdbc.username=root jdbc.password01=root
6、编写MyBatis配置文件SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> </configuration>
7、编写Spring配置文件applicationContext-dao.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" 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"> <!-- 读取数据库配置文件 --> <context:property-placeholder location="classpath:druid.properties"> </context:property-placeholder> <!-- 配置数据源 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}"></property> <property name="url" value="${jdbc.url}"></property> <property name="username" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!-- SqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="configLocation" value="classpath:SqlMapConfig.xml"> </property> </bean> <!-- 配置扫描包对象,为包下的接口创建代理对象 --> <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.itbaizhan.dao"></property> </bean> </beans>
8、测试持久层接口的方法
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:applicationContext-dao.xml") public class StudentDaoTest { @Autowired private StudentDao studentDao; @Test public void testFindAll(){ List<Student> all = studentDao.findAll(); all.forEach(System.out::println); } @Test public void testAdd(){ Student student = new Student(0,"SXT", "女", "上海"); studentDao.add(student); } }
SSM整合_创建service子工程
1、在父工程下创建maven普通java子工程
2、service子工程引入dao子工程的依赖
<dependencies> <dependency> <groupId>com.tong</groupId> <artifactId>ssm_dao</artifactId> <version>1.0-SNAPSHOT</version> </dependency> </dependencies>
3、创建服务层方法
@Service public class StudentService { @Autowired private StudentDao studentDao; public List<Student> findAllStudent(){ return studentDao.findAll(); } public void addStudent(Student student){ studentDao.add(student); } }
4、创建服务层的Spring配置文件applicationContextservice.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 包扫描 --> <context:component-scan basepackage="com.tong.service"></context:component-scan> <!-- 事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 通知 --> <tx:advice id="txAdvice" transactionmanager="transactionManager"> <tx:attributes> <tx:method name="*"/> </tx:attributes> </tx:advice> <!-- 切面 --> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.itbaizhan.service.*.*(..))"></aop:advisor> </aop:config> </beans>
SSM整合_创建controller子工程
1、在父工程下使用maven创建web类型子工程
2、controller工程引入service子工程的依赖,并配置ssm父工程
<parent> <artifactId>ssm_demo</artifactId> <groupId>com.tong</groupId> <version>1.0-SNAPSHOT</version> </parent> <dependencies> <dependency> <groupId>com.tong</groupId> <artifactId>ssm_service</artifactId> <version>1.0-SNAPSHOT</version> </dependency> </dependencies>
3、编写控制器类
@Controller @RequestMapping("/student") public class StudentController { @Autowired private StudentService studentService; @RequestMapping("/all") public String all(Model model){ List<Student> allStudent = studentService.findAllStudent(); model.addAttribute("students",allStudent); return "allStudent"; } @RequestMapping("/add") public String add(Student student){ studentService.addStudent(student); // 重定向到查询所有学生 return "redirect:/student/all"; } }
4、编写SpringMVC配置文件springmvc.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 扫描Controller包 --> <context:component-scan basepackage="com.tong.controller"/> <!-- 配置视图解析器 --> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.vie w.InternalResourceViewResolver"> <property name="prefix" value="/"/> <property name="suffix" value=".jsp"/> </bean> <!-- 开启SpringMVC注解的支持 --> <mvc:annotation-driven/> <!-- 放行静态资源 --> <mvc:default-servlet-handler /> </beans>
5、编写Spring的总配置文件applicationContext.xml,该文件引入 dao和service层的Spring配置文件
<?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"> <import resource="applicationContextdao.xml"></import> <import resource="applicationContextservice.xml"></import> </beans>
6、在web.xml中配置Spring监听器,该监听器会监听服务器启动, 并自动创建Spring的IOC容器
<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/webapp_3_1.xsd" version="3.1"> <display-name>Archetype Created Web Application</display-name> <!-- 创建spring容器的监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> </web-app>
7、在web.xml中配置SpringMVC的前端控制器和编码过滤器
<!--前端控制器--> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.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> <!--编码过滤器--> <filter> <filter-name>encFilter</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>encFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
8、编写JSP页面allStudent.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> <%-- 添加学生表单 --%> <form action="/student/add" method="post"> 姓名:<input name="name"> 性别:<input name="sex"> 地址:<input name="address"> <input type="submit" value="提交"> </form> <%-- 展示学生表格 --%> <table width="500" cellpadding="0" cellspacing="0" border="1" align="center"> <tr> <th>id</th> <th>姓名</th> <th>性别</th> <th>地址</th> </tr> <c:forEach items="${students}" var="student"> <tr> <td>${student.id}</td> <td>${student.name}</td> <td>${student.sex}</td> <td>${student.address}</td> </tr> </c:forEach> </table> </body> </html>
SSM整合_运行项目
1、在idea中配置使用tomcat插件启动maven父项目
2、启动项目,访问http://localhost:8080/student/all