SSM配置XML
程序员文章站
2022-04-25 16:53:36
...
SSM整合xml
XML头文件
// An highlighted block
<?xml version="1.0" encoding="UTF-8"?>
<beans default-lazy-init="true"
xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.3.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">
</beans>
SpringConfig.xml主配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans default-lazy-init="true"
xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.3.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 如果没配置包扫描,则要求控制器类继承Controler,配置了则可以使用注解 -->
<!-- 配置bean组件扫描(@service @controller... -->
<context:component-scan base-package="com.jt"></context:component-scan>
<!-- 整合spring-mvc的xml -->
<import resource="classpath:spring-mvc.xml"/>
<!-- 整合mybatis的xml -->
<import resource="classpath:spring-mybatis.xml"/>
</beans>
配置主要的依赖包:
<dependencies>
<!-- 配置spring-webmvc就不用配spring-context了 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
<!-- jackson和fastjson,可以任选一个. -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.5</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.38</version>
</dependency>
<!-- 根据数据库版本选择connector4j版本. -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
<!-- springJDBC和spring主版本相匹配 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
<!-- MyBatis主包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<!-- 整合包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<!-- druid连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.16</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
SpringMVC.xml配置:添加MVC配置文件,配置bean扫描,启用mvc默认配置,配置视图解析器。
<?xml version="1.0" encoding="UTF-8"?>
<beans default-lazy-init="true"
xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.3.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 启用mvc注解配置 -->
<mvc:annotation-driven>
<!-- 不配置 则默认 将fastjon设为默认转换器 -->
<mvc:message-converters register-defaults="true">
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=utf-8</value>
<value>application/json;charset=utf-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- 配置视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 配置拦截器 -->
<mvc:interceptors><!-- 先配置先执行 构成拦截器连,由配置顺序决定-->
<!-- 系统运维监控 -->
<mvc:interceptor><!-- 注意配置元素的顺序 -->
<!-- 配置拦截哪些路径 -->
<mvc:mapping path="/**"/>
<!-- 配置哪些路径不进行拦截 -->
<!-- <mvc:exclude-mapping path="/dologin.do"/> -->
<!-- 拦截到请求后由哪个拦截器进行处理 -->
<ref bean="systemInterceptor"/>
</mvc:interceptor>
<!-- 控制层执行时常监控 -->
<mvc:interceptor><!-- 注意配置元素的顺序 -->
<!-- 配置拦截哪些路径 -->
<mvc:mapping path="/**"/>
<!-- 配置哪些路径不进行拦截 -->
<mvc:exclude-mapping path="/dologin.do"/>
<!-- 拦截到请求后由哪个拦截器进行处理 -->
<ref bean="timeInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
</beans>
对比MVC配置
<!-- 这里要求 控制器类继承Controler 若主配置文件有扫描则不用配了-->
<!-- <context:component-scan base-package="com.jt"></context:component-scan> -->
<!-- 启动MVC注解默认配置 -->
<mvc:annotation-driven>
<!-- 写东西代表修改配置,这里是把fastjson设置为默认转换器 -->
<mvc:message-converters register-defaults="true">
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="SupportedMediaTypes">
<list>
<value>text/html;charset=utf-8</value>
<value>application/json;charset=utf-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- 视图解析器,将控制器返回的结果进行拼接,变成页面路径 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 配置HandleMaping(URL到Controller直接的映射,vlaue里写的是控制器的beanID
若配置了包扫描,则可以使用注解代替HandlerMapping.一下全部不用
-->
<bean
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="UrlMap">
<map>
<entry key="/hello.do" value="helloController" />
</map>
</property>
</bean>
<!-- 这里要给上面helloController配置正确bean才能正常运行, 这里myDAO是直接跳过业务层从DAO层拿到数据 -->
<!-- <bean id="helloController" class="com.mypratice.controler.MyControler">
<property name="myDAO" ref="myDao"></property> </bean> -->
<!-- 配置拦截器,拦截器无法延时加载,若没有包扫描则需要额外配置拦截器的bean -->
<mvc:interceptors>
<mvc:interceptor>
<!-- 多个拦截器构成拦截器链,xml模式中写在前面的先执行 -->
<mvc:mapping path="/**"/>
<ref bean="systemInterceptor"/>
</mvc:interceptor>
<mvc:interceptor><!-- 以下配置的额顺序不能改变 -->
<!-- 配置拦截哪些路径 /**表示拦截所有-->
<mvc:mapping path="/**" />
<!-- 配置哪些路径不进行拦截 -->
<mvc:exclude-mapping path="/doLogin.do" />
<!-- 拦截到请求后由哪个拦截器进行处理,timeInterceptor的bean 已经由注解自动生成了[email protected] -->
<ref bean="timeInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
默认的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" version="2.5">
<display-name>CGB-SSM-V01</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<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:spring-configs.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
参考配置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"
version="2.5">
<display-name>CGB-SPRING-MVC-02</display-name>
web.xml内容配置
<!-- 前端控制器 -->
<servlet>
<servlet-name>frontController</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!-- 不是spring的set注入,这里找的是那个参数名 -->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:SpringConfig.xml</param-value>
</init-param>
<!-- 数字越小,优先级越高.让tomcat启动时既加载初始化servlet 如果没配置,会等到访问的时候再初始化 -->
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 表示拦截的请求后缀名-->
<servlet-mapping>
<servlet-name>frontController</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
SpringMybatis.xml相关配置
<?xml version="1.0" encoding="UTF-8"?>
<beans default-lazy-init="true"
xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.3.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 整合DRUID数据源对象 -->
<util:properties id="cfg" location="classpath:configs.properties"> </util:properties>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close" lazy-init="false">
<property name="driverClassName" value="#{cfg.jdbcDriver}"/>
<property name="url" value="#{cfg.jdbcUrl}"/>
<property name="username" value="#{cfg.jdbcUser}"/>
<property name="password" value="#{cfg.jdbcPassword}"/>
</bean>
<!-- 整合sqlsessionfactroyBean对象 -->
<bean id="sqlSessionFactroy" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="DataSource" ref="dataSource"/><!-- 数据源 -->
<property name="MapperLocations"
value="classpath*:mapper/sys/*Mapper.xml"/><!-- -->
</bean>
<!-- 配置 dao层接口扫描-->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.jt.**.dao"/>
<property name="sqlSessionFactoryBeanName"
value="sqlSessionFactroy"/>
</bean>
</beans>
相关简洁配置mybati.xml
配置druid和MyBatis工厂
<util:properties id="cfg"
location="classpath:jdbc.properties" />
<bean id="druidDataSource"
class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="#{cfg.driver}" />
<property name="url" value="#{cfg.url}" />
<property name="username" value="#{cfg.usernameddd}" />
<property name="password" value="#{cfg.password}" />
</bean>
<!-- 配置SqlSessionFactoryBean对象
这个对象取出来的东西是 sqlSessionFactory
相当于取代了MyBatis的配置文件
只需要在MapperLocations里配置Mapper映射就好了. -->
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="DataSource" ref="druidDataSource" />
<property name="MapperLocations"
value="classpath*:mapper/*Mapper.xml" />
</bean>
<!-- 这里配置自动扫描接口,自动生成实现类 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- com.jt.**.dao表示com.jt包下,任意包下+任意包下+dao包下的位置 -->
<property name="basePackage" value="com.jt.**.dao" />
<!-- 这个可以不配,无所谓. -->
<!-- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> -->
</bean>
<!-- 给实现类配置sqlSessionFactory -->
<!-- <bean id="myDao" class="com.mypratice.DAO.impl.myDAOimpl"> -->
<!-- <property name="sqlSessionFactory" ref="sqlSessionFactory" /> -->
<!-- </bean> -->
数据库属性文件:jdbc.properties
jdbcDriver=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql:localhost:3306/jtsys?useUnicode=true&characterEncoding=utf-8
jdbcUser=root
jdbcPassword=root
日志文件:log4j.properties
log4j.rootLogger=INFO,stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%-5p] %c - %m%n
log4j.logger.com.mybatis3=DEBUG
log4j.logger.com.jt=DEBUG
Mapper.xml文件
<?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.jt.sys.dao.SysConfigDao">
<select id="findPageObjects"
resultType="com.jt.sys.entity.SysConfig">
select *
from sys_configs
where name like concat("%",#{name},"%")
limit #{startIndex},#{pageSize}
</select>
<select id="getRowCount" resultType="int">
select count(*)
from sys_configs
where name like concat("%",#{name},"%")
</select>
</mapper>
后端控制器常用配置:
package com.mypratice.controler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mypratice.DAO.myDAO;
import com.mypratice.POJO.Db1Pojo;
public class MyControler implements Controller{
private myDAO myDAO;
public void setMyDAO(myDAO DAO) {
this.myDAO=DAO;
}
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView mav=new ModelAndView();
mav.setViewName("hello");
mav.addObject("MSG", "Hello SpringMVC~!");
String strs[]= {"啊啊啊1","棒棒棒2","踩踩踩3"};
mav.addObject("array", new ObjectMapper().writeValueAsString(strs));
Db1Pojo pojo = myDAO.findPOJObyId(1);
System.out.println(pojo);
mav.addObject("dao", new ObjectMapper().writeValueAsString(pojo));
return mav;
}
}
自己写实现类方式,设置bean让Spring给自动注入sqlSessionFactory
package com.mypratice.DAO.impl;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import com.mypratice.DAO.myDAO;
import com.mypratice.POJO.Db1Pojo;
public class myDAOimpl implements myDAO{
private SqlSessionFactory sqlSessionFactory;
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
this.sqlSessionFactory = sqlSessionFactory;
}
@Override
public Db1Pojo findPOJObyId(Integer id) {
SqlSession session = sqlSessionFactory.openSession();
String statement = "com.mypratice.DAO.myDAO.findById";
Db1Pojo pojo = session.selectOne(statement,1);
session.close();
return pojo;
}
}
SSM配置的基本步骤
基本步骤
1.创建maven web项目,
2.生成部署描述文件 web.xml
3.修改项目编码为utf-8
4.设置项目targeted runtimes (Tomcat)
5.修改项目project facets (jdk1.8)
2.2.资源整合
整合流程分析:
1.整合Spring MVC 环境(一个依赖spring-webmvc)
2.整合fastjson(jackson)库(一个依赖fastjson(jackson),用于将对象转换为json串)
3.整合Druid 连接池(两个依赖:mysql驱动,druid库文件)
4.整合Mybatis 框架(三个依赖:mybatis,mybatis-spring,spring-jdbc)
5.整合Junit 单元测试框架
资源整合实现:
第一步:整合Spring MVC 应用组件
1.1)添加依赖(spring-webmvc)
1.2)添加配置文件(spring-configs.xml)
配置bean扫描,启用mvc默认配置,配置视图解析器。
1.3)配置前端控制器(DispatcherServlet)
1.4)启动环境进行测试。
第二步:整合fastjson库(用于将对象转换为json串)
//如果是jackson则Spring默认支持
2.1) 添加fastjson依赖
2.2) 配置fastjson 对象转换器
第三步:整合Druid连接池对象
3.1) 添加依赖(mysql,druid)
3.2) 添加configs.properties文件,并定义key/value
3.3) 配置druid对象(spring-configs.xml)
第四步:整合mybatis框架(用户实现持久层的数据操作)
4.1) 添加依赖(mybatis,mybatis-spring,spring-jdbc)
4.2) 配置mybatis(spring-configs.xml)
说明:配置完成以后部署项目,启动tomcat测试是否有问题.
全局异常类定义
/**
* 全局异常处理类(需要使用@ControllerAdvice注释)
* 可以在此类中添加所有Conroller中
* 需要共享的异常处理方法
*
*/
@ControllerAdvice
public class GlobalExceptionHandler {
/**
* @ExceptionHandler 此注解声明的方法
* 为异常处理方法
* 1.Spring mvc 如何识别这个方法是一个异常处理方法@ExceptionHandler
* 2.spring mvc 后端处理器的方法出现异常底层会如何处理
* @return Class[]
*/
@ExceptionHandler(Exception.class)
@ResponseBody
public JsonResult doHandlerException(Exception e){
System.out.println(e.getMessage());
return new JsonResult(e);
}
//继承层次,先找直接父类再找,上面的父类
@ExceptionHandler(RuntimeException.class)//
@ResponseBody
public JsonResult doRuntimeException( RuntimeException e){
System.out.println(e.getMessage());
return new JsonResult(e);
}
}
自定义异常类
/**
*
* 只在业务层才定义 业务异常
* 1.更好的定位错误
* 2.更好的事项用户交互
*
*/
public class ServiceException extends RuntimeException {
private static final long serialVersionUID = 1L;
public ServiceException() {
super();
// TODO Auto-generated constructor stub
}
public ServiceException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
// TODO Auto-generated constructor stub
}
public ServiceException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public ServiceException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public ServiceException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
}
自定义注解:
/**
* 自定义注解
*
*/
@Retention(RetentionPolicy.RUNTIME)//运行时有效
@Target(ElementType.METHOD)//只能修饰方法
public @interface HandlerMonitor {
}
自定义拦截器:
/**
* 拦截器
*
*/
@Component
public class TimeInterceptor implements HandlerInterceptor {
public TimeInterceptor() {
// TODO Auto-generated constructor stub
System.out.println("拦截器初始化");
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
// TODO Auto-generated method stub
System.out.println("preHandle"+handler.getClass());
long startTime=System.nanoTime();
//封装控制层要执行的方法信息
HandlerMethod handmeth=(HandlerMethod)handler;
Method method = handmeth.getMethod();//利用反射获取方法
String name = method.getName();//获取方法名
System.out.println(name);
if(method.isAnnotationPresent(HandlerMonitor.class)){//是否有注解
System.out.println("有注解");
request.setAttribute("startTime", startTime);
}
return true;//true 放行
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// TODO Auto-generated method stub
System.out.println("posthandler");
Method method = ((HandlerMethod)handler).getMethod();
if(method.isAnnotationPresent(HandlerMonitor.class)){
long totalTime=System.nanoTime()-(long)request.getAttribute("startTime");
System.out.println(totalTime);
}
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
// TODO Auto-generated method stub
System.out.println("afterCompletion");
}
}
Controller配置:
@Controller
@RequestMapping("/config/")
public class SysConfigController {//mvc
@Autowired
private SysConfigService sysConfigService;
//@RequestMapping("doFindPageObjects")
//@ResponseBody
//@HandlerMonitor //自定义注解只能修饰方法对象
//public PageObject<SysConfig> doFindPageObjects(String name,Integer pageCurrent){
// return sysConfigService.findPageObjects(name, pageCurrent);
//}//将对象装换为json输出(底层借用fastjson)
@RequestMapping("doFindPageObjects")
@ResponseBody
@HandlerMonitor //自定义注解只能修饰方法对象
public JsonResult doFindPageObjects(String name,Integer pageCurrent){
return new JsonResult(sysConfigService.findPageObjects(name, pageCurrent));
}//将对象装换为json输出(底层借用fastjson)
//controller--->service---->dao---->DB
@RequestMapping("ajax")
public String ajax(){
return "congif-ajax";
}
@RequestMapping("ajax1")
public String ajax1(){
return "jquery_ajax";
}
}
推荐阅读
-
Sublime Text 3如何配置本地服务器? Sublime本地服务器的配置方法
-
在MyEclipse中配置Tomcat服务器7.0图文教程
-
使用vscode 编辑调试php 配置方与VSCode断点调试PHP
-
暴风墨镜有什么用?暴风影音新品暴风魔镜功能配置介绍
-
动态108M和静态108M的介绍以及区别 用是108M网卡,配置软件上显示的却是54M的原因
-
#实践笔记#本地配置PHPnow与WordPress运行环境
-
windows mobile+webservice+sql server 2005配置方法
-
用EXCEL表格和软件打开xml文件的方法具体步骤
-
CorePlex的安装、配置和使用图文教程
-
JDK1.6的下载、安装与配置图文详细教程 推荐