SSM

spring-mvc.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:util="http://www.springframework.org/schema/util"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!-- 开始组件扫描 -->
    <context:component-scan base-package="com.six" />
    <!-- 启用注解驱动 -->
    <mvc:annotation-driven />
    <mvc:resources location="WEB-INF/static/" mapping="/static/**" />
    <!--避免IE执行AJAX时,返回JSON出现下载文件 -->
    <bean id="mappingJacksonHttpMessageConverter"
        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
    </bean>
    <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter" />   <!-- JSON转换器 -->
            </list>
        </property>
    </bean>
    <!-- 配置视图解析器 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/page/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!--拦截器 -->
    <mvc:interceptors>
        <!--多个拦截器,顺序执行 -->
        <mvc:interceptor>
            <!-- /**表示所有url包括子url路径 -->
            <mvc:mapping path="/rear/**" />
            <bean class="com.six.interceptor.UserInfoInterceptor" />
        </mvc:interceptor>
        <mvc:interceptor>
            <!-- /**表示所有url包括子url路径 -->
            <mvc:mapping path="/**/add" />
            <bean class="com.six.interceptor.AddInfoInterceptor" />
        </mvc:interceptor>
    </mvc:interceptors>

    <!-- 全局异常处理器,只要实现HandlerExceptionResolver接口就是全局异常处理器 -->
    <bean class="com.six.exception.GlobalExceptionResolver"></bean>

    <!-- 文件上传 -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 设置默认编码 -->
        <property name="defaultEncoding" value="utf-8"/>
        <!-- 文件大小最大值 -->
        <property name="maxUploadSize" value="10485760000" />
        <!-- 内存中的最大值 -->
        <property name="maxInMemorySize" value="40960" />
    </bean>

</beans>

jdbc.properties 连接池 mysql 配置

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://121.0.0.1:3306/shared?zeroDateTimeBehavior=convertToNull&characterEncoding=utf-8
username=shared
password=password

全局异常类GlobalExceptionResolver

package com.six.exception;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;

public class GlobalExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
            Exception ex) {
        // 向控制台打印错误信息
        ex.printStackTrace();
        // 定义错误信息
        String message = "系统异常,请稍后重试";
        // 判断是不是自己抛出的错误
        if (ex instanceof GlobalException) {
            message = ((GlobalException) ex).getMessage();
        }
        // 判断是json请求还是页面转发请求
        HandlerMethod handMethod = (HandlerMethod) handler;
        ResponseBody responseBody = handMethod.getMethod().getAnnotation(ResponseBody.class);
        if (responseBody != null) {
            // json请求(返回json数据)
            Map<String, Object> responseMap = new HashMap<String, Object>();
            responseMap.put("code", "999999");
            responseMap.put("message", message);
            String json = new Gson().toJson(responseMap);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            try {
                response.getWriter().write(json);
                response.getWriter().flush();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            // 返回一个空的ModelAndView表示已经手动生成响应
            return new ModelAndView();
        }

        // 页面转发(跳转至错误页面)
        ModelAndView modelAndView = new ModelAndView();
        // 将错误信息传到页面
        modelAndView.addObject("message", message);
        // 指向错误页面
        modelAndView.setViewName("error/error");
        return modelAndView;
    }

}

Spring-Mybatis 配置

<?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:util="http://www.springframework.org/schema/util"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <util:properties id="config" location="classpath:jdbc.properties"></util:properties>
    <!-- 配置数据库连接参数及连接池 -->
    <bean id="ds" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="#{config.driver}" />
        <property name="url" value="#{config.url}" />
        <property name="username" value="#{config.username}" />
        <property name="password" value="#{config.password}" />

        <!--initialSize: 初始化连接 -->
        <property name="initialSize" value="0" />
        <!--minIdle: 最小空闲连接 -->
        <property name="minIdle" value="1" />
        <!--maxIdle: 最大空闲连接 -->
        <property name="maxIdle" value="20" />
        <!-- 连接池中可同时连接的最大的连接数 -->
        <property name="maxActive" value="20" />
        <!-- 最大等待时间,当没有可用连接时,连接池等待连接释放的最大时间,超过该时间限制会抛出异常 -->
        <property name="maxWait" value="60000" />
        <!-- 超过removeAbandonedTimeout时间后,是否进 行没用连接(废弃)的回收 -->
        <property name="removeAbandoned" value="true" />
        <!-- 超过时间限制,回收没有用(废弃)的连接 -->
        <property name="removeAbandonedTimeout" value="180" />
        <!-- 每60秒运行一次空闲连接回收器 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="300000" />
    </bean>

    <!-- spring集成mybatis,不再需要mybatis的配置文件 -->
    <!-- 配置SqlSessionFactoryBean -->
    <bean id="ssfb" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入连接池 -->
        <property name="dataSource" ref="ds"></property>
        <property name="configLocation" value="classpath:mybatis-config.xml" />
        <!-- 映射文件的位置 -->
        <property name="mapperLocations"
            value="classpath*:com/mapper/*Mapper.xml"/>
    </bean>
    <!-- 该bean负责调用SqlSession的getMapper函数 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.*.mapper" />
        <property name="sqlSessionFactoryBeanName" value="ssfb" />
    </bean>
    <!-- 开启事务注解驱动 -->
    <tx:annotation-driven />
    <!-- (事务管理) -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="ds" />
    </bean>
</beans>

log4j.properties配置

### Log4j配置 ###
#允许DEBUG级别以上的日志可以打印到控制台和写入日志文件
log4j.rootLogger=DEBUG,console,file

#-----------------------------------#
#1 定义日志输出目的地为控制台
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target=System.out
log4j.appender.console.Threshold=DEBUG
####可以灵活地指定日志输出格式,下面一行是指定具体的格式 ###
#%c: 输出日志信息所属的类目,通常就是所在类的全名
#%m: 输出代码中指定的消息,产生的日志具体信息 
#%n: 输出一个回车换行符,Windows平台为"/r/n",Unix平台为"/n"输出日志信息换行
log4j.appender.console.layout=org.apache.log4j.PatternLayout
#日志记录格式(根据自己喜好更改)
log4j.appender.console.layout.ConversionPattern=%d [%-5p] - %c (%F.%M:%L) - %m%n

#-----------------------------------#
#2 文件大小到达指定尺寸的时候产生一个新的文件 
log4j.appender.file=org.apache.log4j.RollingFileAppender
#日志文件输出目录
log4j.appender.file.File=E\:/dummmmmmmy/logs/log.log
#定义文件最大大小
log4j.appender.file.MaxFileSize=1024kb
#最多生成多少个文件
log4j.appender.file.MaxBackupIndex=20
###输出日志信息###
#写到文件的日志的最低级别
log4j.appender.file.Threshold=ERROR
log4j.appender.file.layout=org.apache.log4j.PatternLayout
#日志记录格式(根据自己喜好更改)
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss} [%p] - %c - %F(%L) -%m%n

#-----------------------------------#
#3 mybatis 显示SQL语句部分
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <display-name>Shared equipment</display-name>
    <!-- 默认首页 -->
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:cxf-*.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

        <!-- cxf 的servlet   webserver的扫描启动 -->
    <servlet>
        <servlet-name>CXFServlet</servlet-name>
        <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>CXFServlet</servlet-name>
        <url-pattern>/ws/*</url-pattern>
    </servlet-mapping>

    <!-- ================配置SpringMVC核心调度器================ -->
    <!-- 不指定具体文件的话,默认为"/WEB-INF/<servlet name>-servlet.xml" -->
    <!-- load-on-startup代表启动顺序,设置为大于等于0表示容器在应用启动时就加载并初始化这个servlet -->
    <!-- 推荐拦截/,风格优雅 -->
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-*.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>*.json</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>


    <!-- 字符过滤,防止post请求乱码 -->
    <filter>
        <filter-name>SpringCharacterEncodingFilter</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>SpringCharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- 在线人数监听类 -->
    <listener>
        <listener-class>com.six.listener.OnlineUsersSessionListener</listener-class>
    </listener>
    <listener>
        <listener-class>com.six.listener.OnlineUsersRequestListener</listener-class>
    </listener>
    <!-- session超时定义session超时时间设置为30分钟 -->
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>

    <error-page>
        <error-code>404</error-code>
        <location>/WEB-INF/page/error/error-404.jsp</location>
    </error-page>
    <error-page>
        <error-code>500</error-code>
        <location>/WEB-INF/page/error/error-500.jsp</location>
    </error-page>
</web-app>

在线人数监听类

OnlineUsersSessionListener(待完善)

/**
 * 
 */
package com.six.listener;

import java.util.ArrayList;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import com.six.entity.OnlineUsers;
import com.six.utils.Util;

/**
 * @Description 在线人数监听器
 * @author dummmmmmmy
 * @date 2018年11月17日
 */
@WebListener
public class OnlineUsersSessionListener implements HttpSessionListener {
    private int num=0;//统计用户在线人数
    /**
     * Title: sessionCreated Description:
     * 
     * @param se
     * @see javax.servlet.http.HttpSessionListener#sessionCreated(javax.servlet.http.HttpSessionEvent)
     */
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        num++;
        //设置到ServletContext域中
        se.getSession().getServletContext().setAttribute("num",num);
        //System.out.println(" add....");
    }

    /**
     * Title: sessionDestroyed Description:
     * 
     * @param se
     * @see javax.servlet.http.HttpSessionListener#sessionDestroyed(javax.servlet.http.HttpSessionEvent)
     */
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {

        num--;
        //设置到ServletContext域中
        se.getSession().getServletContext().setAttribute("num",num);
        //System.out.println(" remove....");

        //注意,此处还要进行设置
        //从session列表中移除session
        ArrayList<OnlineUsers> list=null;
        list=(ArrayList<OnlineUsers>) se.getSession().getServletContext().getAttribute("list");
        if(Util.getByUserId(list, se.getSession().getId())!=null){
            list.remove(Util.getByUserId(list, se.getSession().getId()));
        }

    }

}

OnlineUsersRequestListener

/**
 * 
 */
package com.six.listener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.six.entity.OnlineUsers;
import com.six.utils.Util;

/**
 * @Description 在线人数监听器
 * @author dummmmmmmy
 * @date 2018年11月17日
 */
@WebListener
public class OnlineUsersRequestListener implements ServletRequestListener {
    private ArrayList<OnlineUsers> list;// 存储访问用户的信息

    /**
     * Title: requestInitialized Description:
     * 
     * @param sre
     * @see javax.servlet.ServletRequestListener#requestInitialized(javax.servlet.ServletRequestEvent)
     */
    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        // 获得ServletContext域中的list
        list = (ArrayList<OnlineUsers>) sre.getServletContext().getAttribute("list");

//              if(list.isEmpty())
        if (list == null) {
            list = new ArrayList<OnlineUsers>();
        }
        // 为了获得session对象,进行强制类型转换
        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
        HttpSession session = request.getSession();
        String sessionId = session.getId();// sessionId

        // session的列表中没有当前的sessionId,即:以前的所有访问用户中,没有当前的访问用户,所以把当前的访问用户信息加入
        if (Util.getByUserId(list, sessionId) == null) {
            OnlineUsers user = new OnlineUsers();
            user.setSessionId(sessionId);
            user.setIp(request.getRemoteAddr());
            // 设置时间
            user.setFirstTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
//                  user.setFirstTime(System.currentTimeMillis()+"");
            list.add(user);
        }
//              request.getServletContext().setAttribute("list", list);//保存所有用户信息到list中
        sre.getServletContext().setAttribute("list", list);// 保存所有用户信息到list中

    }

    /**
     * Title: requestDestroyed Description:
     * 
     * @param sre
     * @see javax.servlet.ServletRequestListener#requestDestroyed(javax.servlet.ServletRequestEvent)
     */
    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        // TODO Auto-generated method stub

    }

}
Last modification:August 9th, 2019 at 09:57 am
如果觉得我的文章对你有用,请随意赞赏

Leave a Comment