搜索词>>SLF4J 耗时0.0040
  • spring boot 使用SLF4J Logging-Java编程

    Java编程之Spring Boot 使用SLF4J Logging,spring boot,SLF4J<h2>一、项目结构图</h2> <img alt="项目结构图" class="img-thumbnail" src="/resources/assist/images/blog/b33c0281356d4650ac605ee4715f5600.png" /><br /> 默认情况下,SLF4j日志记录包含在Spring boot包中。<br /> <strong>application.properties</strong> <pre> <code>spring-boot-web-project$ mvn dependency:tree +... +- org.springframework.boot:spring-boot-starter-logging:jar:1.4.2.RELEASE:compile [INFO] | | | +- ch.qos.logback:logback-classic:jar:1.1.7:compile [INFO] | | | | \- ch.qos.logback:logback-core:jar:1.1.7:compile [INFO] | | | +- org.slf4j:jcl-over-slf4j:jar:1.7.21:compile [INFO] | | | +- org.slf4j:jul-to-slf4j:jar:1.7.21:compile [INFO] | | | \- org.slf4j:log4j-over-slf4j:jar:1.7.21:compile +...</code></pre> <p><strong>请注意</strong><br /> <em>查看这个Spring Boot Logback XML模板,了解默认的日志记录模式和配置。</em></p> <h2>二、配置文件</h2> <h3>2.1application.properties<br /> 要启用日志记录,创建一个应用程序。在资源文件夹的根目录下的属性文件。<br /> 日志记录。级别-定义日志级别,日志记录将输出到控制台。<br /> <strong>application.properties</strong></h3> <pre> <code>logging.level.org.springframework.web=ERROR logging.level.com.mkyong=DEBUG</code></pre> logging.file -定义日志文件,日志将输出到一个文件和控制台。<br /> <strong>application.properties</strong> <pre> <code>logging.level.org.springframework.web=ERROR logging.level.com.mkyong=DEBUG #output to a temp_folder/file logging.file=${java.io.tmpdir}/application.log #output to a file #logging.file=/Users/mkyong/application.log</code></pre> <code>logging.pattern</code> -定义一个定制的日志记录模式。<br /> <strong>application.properties</strong> <pre> <code>logging.level.org.springframework.web=ERROR logging.level.com.mkyong=DEBUG # Logging pattern for the console logging.pattern.console= "%d{yyyy-MM-dd HH:mm:ss} - %msg%n" # Logging pattern for file logging.pattern.file= "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n" logging.file=/Users/mkyong/application.log</code></pre> <h2><strong>application.yml</strong></h2> 这在YAML格式中是一样的<br /> <strong>application.yml</strong> <pre> <code>logging: level: org.springframework.web: ERROR com.mkyong: DEBUG pattern: console: "%d{yyyy-MM-dd HH:mm:ss} - %msg%n" file: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n" file: /Users/mkyong/application.log</code></pre> <h2><strong>Classic Logback.xml</strong></h2> 如果您不喜欢Spring引导日志模板,只需创建一个标准的logback。xml在资源文件夹的根目录或类路径的根目录下。这将覆盖Spring引导日志模板。<br /> <strong>logback.xml</strong> <pre> <code class="language-xml"><?xml version="1.0" encoding="UTF-8"?> <configuration> <property name="DEV_HOME" value="c:/logs" /> <appender name="FILE-AUDIT" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${DEV_HOME}/debug.log</file> <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <Pattern> %d{yyyy-MM-dd HH:mm:ss} - %msg%n </Pattern> </encoder> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- rollover daily --> <fileNamePattern>${DEV_HOME}/archived/debug.%d{yyyy-MM-dd}.%i.log </fileNamePattern> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <maxFileSize>10MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> </rollingPolicy> </appender> <logger name="com.mkyong" level="debug" additivity="false"> <appender-ref ref="FILE-AUDIT" /> </logger> <root level="error"> <appender-ref ref="FILE-AUDIT" /> </root> </configuration></code></pre> <h2>Spring Boot logging by Profile</h2> <p>请注意<br /> 阅读本文-概要文件的配置<br />  </p> <p>创建一个logback-spring。在类路径的根目录中使用xml,以利用Spring引导提供的模板特性。</p> <p>在以下的例子:</p> <p>如果配置文件为dev,则将日志记录到控制台和一个滚动文件。</p> <p>如果概要文件被戳了,则只记录到一个滚动文件。<br /> <strong>logback-spring.xml</strong><br />  </p> <pre> <code class="language-xml"><?xml version="1.0" encoding="UTF-8"?> <configuration> <include resource="org/springframework/boot/logging/logback/defaults.xml"/> <property name="LOG_FILE" value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}/}spring.log}"/> <springProfile name="dev"> <include resource="org/springframework/boot/logging/logback/console-appender.xml"/> <appender name="ROLLING-FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <encoder> <pattern>${FILE_LOG_PATTERN}</pattern> </encoder> <file>${LOG_FILE}</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.log</fileNamePattern> </rollingPolicy> </appender> <root level="ERROR"> <appender-ref ref="CONSOLE"/> <appender-ref ref="ROLLING-FILE"/> </root> </springProfile> <springProfile name="prod"> <appender name="ROLLING-FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <encoder> <pattern>${FILE_LOG_PATTERN}</pattern> </encoder> <file>${LOG_FILE}</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.%i.gz</fileNamePattern> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <maxFileSize>10MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> </rollingPolicy> </appender> <root level="ERROR"> <appender-ref ref="ROLLING-FILE"/> </root> </springProfile> </configuration></code></pre> <br /> <strong>application.yml</strong> <pre> <code>spring: profiles: active: prod logging: level: ROOT: ERROR org.springframework: ERROR org.springframework.data: ERROR com.mkyong: INFO org.mongodb: ERROR file: /Users/mkyong/application.log</code></pre> 对于非web启动应用程序,您可以像这样覆盖日志文件输出: <pre> <code>$ java -Dlogging.file=/home/mkyong/app/logs/app.log -jar boot-app.jar</code></pre> <h2>Set Root Level</h2> <strong>application.properties</strong> <pre> <code># root logging level, warning : too much output logging.level.=DEBUG</code></pre> <strong>application.yml</strong> <pre> <code>logging: level: ROOT: DEBUG</code></pre> <br /> <a href="http://www.mkyong.com/wp-content/uploads/2017/01/spring-boot-web-slf4j-logging.zip" rel="external nofollow" target="_blank">下载演示demo</a>
  • log4j配置_log4j2的LevelRangeFilter使用详解_log4j使用

    log4j使用,log4j框架在java编程中还是比较常见的,这里将会讲解通过log4j2的LevelRangeFilter将不同级别log存放不同文件中。一.如何使用log4j本文将讲解如何使用log4j的LevelRangeFilter过滤器,如果LogEvent中的级别处于配置的最小和最大级别的范围内,则返回onMatch,否则返回onMismatch二.log4j LevelRangeFilter 使用例子在log4j2.xml配置文件中,我们使用LevelRangeFilter去过滤日志的等级通过以下的方式:所有info级别的日志将会保存到application-log4j-info.log 文件中所有debug级别的日志将会保存到application-log4j-debug.log 文件中所有error级别日志将会保存到application-log4j-error.log 文件中当然你也可以根据自己的项目进行对log4j的最低等级日志和最高日志等级进行配置,即配置log4j的minLevel和maxLevel属性<?xml version="1.0" encoding="UTF-8"?> <Configuration status="WARN" monitorInterval="30">       <Properties>         <Property name="LOG_PATTERN">%d{yyyy-MM-dd'T'HH:mm:ss.SSSZ} %p %m%n</Property>     </Properties>       <Appenders>           <Console name="Console" target="SYSTEM_OUT" follow="true">             <PatternLayout pattern="${LOG_PATTERN}"/>         </Console>                   <RollingFile name="debugLog" fileName="${sys:APP_LOG_ROOT}/application-debug.log"             filePattern="${sys:APP_LOG_ROOT}/application-debug-%d{yyyy-MM-dd}-%i.log">               <!-- Matches only DEBUG level -->             <LevelRangeFilter minLevel="DEBUG" maxLevel="DEBUG" onMatch="ACCEPT" onMismatch="DENY"/>               <PatternLayout pattern="${LOG_PATTERN}"/>             <Policies>                 <SizeBasedTriggeringPolicy size="19500KB" />             </Policies>             <DefaultRolloverStrategy max="10"/>         </RollingFile>                   <RollingFile name="infoLog" fileName="${sys:APP_LOG_ROOT}/application-info.log"             filePattern="${sys:APP_LOG_ROOT}/application-info-%d{yyyy-MM-dd}-%i.log" >               <!-- Matches only INFO level -->             <LevelRangeFilter minLevel="INFO" maxLevel="INFO" onMatch="ACCEPT" onMismatch="DENY"/>               <PatternLayout pattern="${LOG_PATTERN}"/>             <Policies>                 <SizeBasedTriggeringPolicy size="19500KB" />             </Policies>             <DefaultRolloverStrategy max="10"/>         </RollingFile>                   <RollingFile name="errorLog" fileName="${sys:APP_LOG_ROOT}/application-error.log"             filePattern="${sys:APP_LOG_ROOT}/application-error-%d{yyyy-MM-dd}-%i.log">               <!-- Matches only ERROR level -->             <LevelRangeFilter minLevel="ERROR" maxLevel="ERROR" onMatch="ACCEPT" onMismatch="DENY"/>               <PatternLayout pattern="${LOG_PATTERN}"/>             <Policies>                 <SizeBasedTriggeringPolicy size="19500KB" />             </Policies>             <DefaultRolloverStrategy max="10"/>         </RollingFile>               </Appenders>       <Loggers>               <Logger name="com.leftso.app" additivity="false">             <AppenderRef ref="debugLog" />             <AppenderRef ref="infoLog"  />             <AppenderRef ref="errorLog" />             <AppenderRef ref="Console"  />         </Logger>                                  <Root level="all">             <AppenderRef ref="Console"/>         </Root>       </Loggers>   </Configuration>
  • modbus tcp通讯modbus4j使用说明-java编程

    modbus tcp 通讯协议在Java编程中的使用。本文主要讲解Java编程中通过modbus4j工具类来实现modbus tcp通讯协议的通讯。包括通过modbus协议读取数据,写入数据的实现。<h2>一.什么是modbus</h2>   Modbus是由Modicon(现为施耐德电气公司的一个品牌)在1979年发明的,是全球第一个真正用于工业现场的总线协议。<br /> ModBus网络是一个工业通信系统,由带智能终端的可编程序控制器和计算机通过公用线路或局部专用线路连接而成。其系统结构既包括硬件、亦包括软件。它可应用于各种数据采集和过程监控。<br />   ModBus网络只有一个主机,所有通信都由他发出。网络可支持247个之多的远程从属控制器,但实际所支持的从机数要由所用通信设备决定。采用这个系统,各PC可以和中心主机交换信息而不影响各PC执行本身的控制任务。 <h2>二.Java实现modbus协议通讯</h2> Java编程中,使用modbus4j实现Java中的modbus协议通讯<br /> <br /> modbus4j实现了Java与modbus协议的以下几种通讯方式:<br /> modbus TCP/IP通讯<br /> modubs UDP/IP通讯<br /> modbus RTU/IP通讯<br /> <br /> 核心依赖:<br /> <strong>modbus4j.jar<br /> commons-lang3-3.0.jar<br /> //下载地址代码里有</strong><br /> Java读取工具类 <pre> <code class="language-java">package com.leftso.project.demo.modbus4j; import com.serotonin.modbus4j.BatchRead; import com.serotonin.modbus4j.BatchResults; import com.serotonin.modbus4j.ModbusFactory; import com.serotonin.modbus4j.ModbusMaster; import com.serotonin.modbus4j.code.DataType; import com.serotonin.modbus4j.exception.ErrorResponseException; import com.serotonin.modbus4j.exception.ModbusInitException; import com.serotonin.modbus4j.exception.ModbusTransportException; import com.serotonin.modbus4j.ip.IpParameters; import com.serotonin.modbus4j.locator.BaseLocator; /** * modbus通讯工具类,采用modbus4j实现 * * @author lxq * @dependencies modbus4j-3.0.3.jar * @website https://github.com/infiniteautomation/modbus4j */ public class Modbus4jUtils { /** * 工厂。 */ static ModbusFactory modbusFactory; static { if (modbusFactory == null) { modbusFactory = new ModbusFactory(); } } /** * 获取master * * @return * @throws ModbusInitException */ public static ModbusMaster getMaster() throws ModbusInitException { IpParameters params = new IpParameters(); params.setHost("localhost"); params.setPort(502); // // modbusFactory.createRtuMaster(wapper); //RTU 协议 // modbusFactory.createUdpMaster(params);//UDP 协议 // modbusFactory.createAsciiMaster(wrapper);//ASCII 协议 ModbusMaster master = modbusFactory.createTcpMaster(params, false);// TCP 协议 master.init(); return master; } /** * 读取[01 Coil Status 0x]类型 开关数据 * * @param slaveId * slaveId * @param offset * 位置 * @return 读取值 * @throws ModbusTransportException * 异常 * @throws ErrorResponseException * 异常 * @throws ModbusInitException * 异常 */ public static Boolean readCoilStatus(int slaveId, int offset) throws ModbusTransportException, ErrorResponseException, ModbusInitException { // 01 Coil Status BaseLocator<Boolean> loc = BaseLocator.coilStatus(slaveId, offset); Boolean value = getMaster().getValue(loc); return value; } /** * 读取[02 Input Status 1x]类型 开关数据 * * @param slaveId * @param offset * @return * @throws ModbusTransportException * @throws ErrorResponseException * @throws ModbusInitException */ public static Boolean readInputStatus(int slaveId, int offset) throws ModbusTransportException, ErrorResponseException, ModbusInitException { // 02 Input Status BaseLocator<Boolean> loc = BaseLocator.inputStatus(slaveId, offset); Boolean value = getMaster().getValue(loc); return value; } /** * 读取[03 Holding Register类型 2x]模拟量数据 * * @param slaveId * slave Id * @param offset * 位置 * @param dataType * 数据类型,来自com.serotonin.modbus4j.code.DataType * @return * @throws ModbusTransportException * 异常 * @throws ErrorResponseException * 异常 * @throws ModbusInitException * 异常 */ public static Number readHoldingRegister(int slaveId, int offset, int dataType) throws ModbusTransportException, ErrorResponseException, ModbusInitException { // 03 Holding Register类型数据读取 BaseLocator<Number> loc = BaseLocator.holdingRegister(slaveId, offset, dataType); Number value = getMaster().getValue(loc); return value; } /** * 读取[04 Input Registers 3x]类型 模拟量数据 * * @param slaveId * slaveId * @param offset * 位置 * @param dataType * 数据类型,来自com.serotonin.modbus4j.code.DataType * @return 返回结果 * @throws ModbusTransportException * 异常 * @throws ErrorResponseException * 异常 * @throws ModbusInitException * 异常 */ public static Number readInputRegisters(int slaveId, int offset, int dataType) throws ModbusTransportException, ErrorResponseException, ModbusInitException { // 04 Input Registers类型数据读取 BaseLocator<Number> loc = BaseLocator.inputRegister(slaveId, offset, dataType); Number value = getMaster().getValue(loc); return value; } /** * 批量读取使用方法 * * @throws ModbusTransportException * @throws ErrorResponseException * @throws ModbusInitException */ public static void batchRead() throws ModbusTransportException, ErrorResponseException, ModbusInitException { BatchRead<Integer> batch = new BatchRead<Integer>(); batch.addLocator(0, BaseLocator.holdingRegister(1, 1, DataType.FOUR_BYTE_FLOAT)); batch.addLocator(1, BaseLocator.inputStatus(1, 0)); ModbusMaster master = getMaster(); batch.setContiguousRequests(false); BatchResults<Integer> results = master.send(batch); System.out.println(results.getValue(0)); System.out.println(results.getValue(1)); } /** * 测试 * * @param args */ public static void main(String[] args) { try { // 01测试 Boolean v011 = readCoilStatus(1, 0); Boolean v012 = readCoilStatus(1, 1); Boolean v013 = readCoilStatus(1, 6); System.out.println("v011:" + v011); System.out.println("v012:" + v012); System.out.println("v013:" + v013); // 02测试 Boolean v021 = readInputStatus(1, 0); Boolean v022 = readInputStatus(1, 1); Boolean v023 = readInputStatus(1, 2); System.out.println("v021:" + v021); System.out.println("v022:" + v022); System.out.println("v023:" + v023); // 03测试 Number v031 = readHoldingRegister(1, 1, DataType.FOUR_BYTE_FLOAT);// 注意,float Number v032 = readHoldingRegister(1, 3, DataType.FOUR_BYTE_FLOAT);// 同上 System.out.println("v031:" + v031); System.out.println("v032:" + v032); // 04测试 Number v041 = readInputRegisters(1, 1, DataType.FOUR_BYTE_FLOAT);// Number v042 = readInputRegisters(1, 3, DataType.FOUR_BYTE_FLOAT);// System.out.println("v041:" + v041); System.out.println("v042:" + v042); // 批量读取 batchRead(); } catch (Exception e) { e.printStackTrace(); } } }</code></pre> <h2>三、测试</h2> 使用ModbusSlave模拟modbus协议<br /> slave中模拟数据如下<br /> <img alt="modbus slave模拟数据" class="img-thumbnail" src="/resources/assist/images/blog/afe4a730-8fb5-4aa2-9f6b-ff09f4368459.png" style="height:856px; width:825px" /><br /> 运行工具类的main方法: <pre> <code>11:14:54.547 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Encap Request: 00 00 00 00 00 06 01 01 00 00 00 01 11:14:54.550 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Sending on port: 502 11:14:54.598 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Response: 00 00 00 00 00 04 01 01 01 01 11:14:54.600 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Encap Request: 00 00 00 00 00 06 01 01 00 01 00 01 11:14:54.600 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Sending on port: 502 11:14:54.650 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Response: 00 00 00 00 00 04 01 01 01 00 11:14:54.652 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Encap Request: 00 00 00 00 00 06 01 01 00 06 00 01 11:14:54.652 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Sending on port: 502 11:14:54.703 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Response: 00 00 00 00 00 04 01 01 01 01 v011:true v012:false v013:true 11:14:54.704 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Encap Request: 00 00 00 00 00 06 01 02 00 00 00 01 11:14:54.704 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Sending on port: 502 11:14:54.755 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Response: 00 00 00 00 00 04 01 02 01 01 11:14:54.757 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Encap Request: 00 00 00 00 00 06 01 02 00 01 00 01 11:14:54.757 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Sending on port: 502 11:14:54.807 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Response: 00 00 00 00 00 04 01 02 01 00 11:14:54.810 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Encap Request: 00 00 00 00 00 06 01 02 00 02 00 01 11:14:54.810 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Sending on port: 502 11:14:54.860 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Response: 00 00 00 00 00 04 01 02 01 01 v021:true v022:false v023:true 11:14:54.866 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Encap Request: 00 00 00 00 00 06 01 03 00 01 00 02 11:14:54.866 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Sending on port: 502 11:14:54.915 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Response: 00 00 00 00 00 07 01 03 04 40 20 00 00 11:14:54.917 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Encap Request: 00 00 00 00 00 06 01 03 00 03 00 02 11:14:54.917 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Sending on port: 502 11:14:54.967 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Response: 00 00 00 00 00 07 01 03 04 41 28 00 00 v031:2.5 v032:10.5 11:14:54.971 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Encap Request: 00 00 00 00 00 06 01 04 00 01 00 02 11:14:54.971 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Sending on port: 502 11:14:55.020 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Response: 00 00 00 00 00 07 01 04 04 3F C0 00 00 11:14:55.021 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Encap Request: 00 00 00 00 00 06 01 04 00 03 00 02 11:14:55.021 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Sending on port: 502 11:14:55.072 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Response: 00 00 00 00 00 07 01 04 04 40 40 00 00 v041:1.5 v042:3.0 11:14:55.074 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Encap Request: 00 00 00 00 00 06 01 02 00 00 00 01 11:14:55.074 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Sending on port: 502 11:14:55.123 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Response: 00 00 00 00 00 04 01 02 01 01 11:14:55.125 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Encap Request: 00 01 00 00 00 06 01 03 00 01 00 02 11:14:55.125 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Sending on port: 502 11:14:55.179 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Response: 00 01 00 00 00 07 01 03 04 40 20 00 00 2.5 true </code></pre> <br /> 观察输出结果与 slave上的模拟数据一致 <h2>四、Java通过modbus4j对数据的写入</h2> <strong>Modbus4jWriteUtils.java</strong> <pre> <code class="language-java">package com.leftso.project.demo.modbus4j; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.serotonin.modbus4j.ModbusFactory; import com.serotonin.modbus4j.ModbusMaster; import com.serotonin.modbus4j.code.DataType; import com.serotonin.modbus4j.exception.ErrorResponseException; import com.serotonin.modbus4j.exception.ModbusInitException; import com.serotonin.modbus4j.exception.ModbusTransportException; import com.serotonin.modbus4j.ip.IpParameters; import com.serotonin.modbus4j.locator.BaseLocator; import com.serotonin.modbus4j.msg.ModbusResponse; import com.serotonin.modbus4j.msg.WriteCoilRequest; import com.serotonin.modbus4j.msg.WriteCoilResponse; import com.serotonin.modbus4j.msg.WriteCoilsRequest; import com.serotonin.modbus4j.msg.WriteCoilsResponse; import com.serotonin.modbus4j.msg.WriteRegisterRequest; import com.serotonin.modbus4j.msg.WriteRegisterResponse; import com.serotonin.modbus4j.msg.WriteRegistersRequest; /** * modbus4j写入数据 * * @author xq * */ public class Modbus4jWriteUtils { static Log log = LogFactory.getLog(Modbus4jWriteUtils.class); /** * 工厂。 */ static ModbusFactory modbusFactory; static { if (modbusFactory == null) { modbusFactory = new ModbusFactory(); } } /** * 获取tcpMaster * * @return * @throws ModbusInitException */ public static ModbusMaster getMaster() throws ModbusInitException { IpParameters params = new IpParameters(); params.setHost("localhost"); params.setPort(502); ModbusMaster tcpMaster = modbusFactory.createTcpMaster(params, false); tcpMaster.init(); return tcpMaster; } /** * 写 [01 Coil Status(0x)]写一个 function ID = 5 * * @param slaveId * slave的ID * @param writeOffset * 位置 * @param writeValue * 值 * @return 是否写入成功 * @throws ModbusTransportException * @throws ModbusInitException */ public static boolean writeCoil(int slaveId, int writeOffset, boolean writeValue) throws ModbusTransportException, ModbusInitException { // 获取master ModbusMaster tcpMaster = getMaster(); // 创建请求 WriteCoilRequest request = new WriteCoilRequest(slaveId, writeOffset, writeValue); // 发送请求并获取响应对象 WriteCoilResponse response = (WriteCoilResponse) tcpMaster.send(request); if (response.isException()) { return false; } else { return true; } } /** * 写[01 Coil Status(0x)] 写多个 function ID = 15 * * @param slaveId * slaveId * @param startOffset * 开始位置 * @param bdata * 写入的数据 * @return 是否写入成功 * @throws ModbusTransportException * @throws ModbusInitException */ public static boolean writeCoils(int slaveId, int startOffset, boolean[] bdata) throws ModbusTransportException, ModbusInitException { // 获取master ModbusMaster tcpMaster = getMaster(); // 创建请求 WriteCoilsRequest request = new WriteCoilsRequest(slaveId, startOffset, bdata); // 发送请求并获取响应对象 WriteCoilsResponse response = (WriteCoilsResponse) tcpMaster.send(request); if (response.isException()) { return false; } else { return true; } } /*** * 写[03 Holding Register(4x)] 写一个 function ID = 6 * * @param slaveId * @param writeOffset * @param writeValue * @return * @throws ModbusTransportException * @throws ModbusInitException */ public static boolean writeRegister(int slaveId, int writeOffset, short writeValue) throws ModbusTransportException, ModbusInitException { // 获取master ModbusMaster tcpMaster = getMaster(); // 创建请求对象 WriteRegisterRequest request = new WriteRegisterRequest(slaveId, writeOffset, writeValue); WriteRegisterResponse response = (WriteRegisterResponse) tcpMaster.send(request); if (response.isException()) { log.error(response.getExceptionMessage()); return false; } else { return true; } } /** * * 写入[03 Holding Register(4x)]写多个 function ID=16 * * @param slaveId * modbus的slaveID * @param startOffset * 起始位置偏移量值 * @param sdata * 写入的数据 * @return 返回是否写入成功 * @throws ModbusTransportException * @throws ModbusInitException */ public static boolean writeRegisters(int slaveId, int startOffset, short[] sdata) throws ModbusTransportException, ModbusInitException { // 获取master ModbusMaster tcpMaster = getMaster(); // 创建请求对象 WriteRegistersRequest request = new WriteRegistersRequest(slaveId, startOffset, sdata); // 发送请求并获取响应对象 ModbusResponse response = tcpMaster.send(request); if (response.isException()) { log.error(response.getExceptionMessage()); return false; } else { return true; } } /** * 写入数字类型的模拟量(如:写入Float类型的模拟量、Double类型模拟量、整数类型Short、Integer、Long) * * @param slaveId * @param offset * @param value * 写入值,Number的子类,例如写入Float浮点类型,Double双精度类型,以及整型short,int,long * @param registerCount * ,com.serotonin.modbus4j.code.DataType * @throws ModbusTransportException * @throws ErrorResponseException * @throws ModbusInitException */ public static void writeHoldingRegister(int slaveId, int offset, Number value, int dataType) throws ModbusTransportException, ErrorResponseException, ModbusInitException { // 获取master ModbusMaster tcpMaster = getMaster(); // 类型 BaseLocator<Number> locator = BaseLocator.holdingRegister(slaveId, offset, dataType); tcpMaster.setValue(locator, value); } public static void main(String[] args) { try { //@formatter:off // 测试01 // boolean t01 = writeCoil(1, 0, true); // System.out.println("T01:" + t01); // 测试02 // boolean t02 = writeCoils(1, 0, new boolean[] { true, false, true }); // System.out.println("T02:" + t02); // 测试03 // short v = -3; // boolean t03 = writeRegister(1, 0, v); // System.out.println("T03:" + t03); // 测试04 // boolean t04 = writeRegisters(1, 0, new short[] { -3, 3, 9 }); // System.out.println("t04:" + t04); //写模拟量 writeHoldingRegister(1,0, 10.1f, DataType.FOUR_BYTE_FLOAT); //@formatter:on } catch (Exception e) { e.printStackTrace(); } } } </code></pre> <br /> <img alt="浮点类型数据写入" class="img-thumbnail" src="/resources/assist/images/blog/0cee0505f42e44bda68381524f669ba1.png" /><br /> <br /> modbus协议中常见功能代码说明:<br /> <img alt="function ID/code说明" class="img-thumbnail" src="/resources/assist/images/blog/6333daae54c94281b86fba2676238c48.png" /><br />  
  • springMVC4+Spring4+Mybaties3项目整合简单例子

    本文章主要简单讲解目前流行的springMVC4+Spring4+Mybaties3(即SSM)框架整合<h2>一.创建一个web的maven项目</h2> 项目完整结构图:<br /> <img alt="项目结构" class="img-thumbnail" src="/resources/assist/images/blog/27a2fcf7-752b-47b6-800a-99fad6608711.png" style="height:911px; width:457px" /> <h2> 二.相关文件内容</h2> <br />  1.pom.xml <pre> <code class="language-xml"><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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.xqlee.dev.project.ssm</groupId> <artifactId>demo-ssm</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>demo-ssm Maven Webapp</name> <url>http://maven.apache.org</url> <profiles> <profile> <id>jdk-1.8</id> <!-- 另外一种激活方式 --> <activation> <activeByDefault>true</activeByDefault> <jdk>1.8</jdk> </activation> <properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion> <com.fasterxml.jackson.jaxrs.version>2.4.1</com.fasterxml.jackson.jaxrs.version> </properties> </profile> </profiles> <!-- 属性版本 --> <properties> <junit.version>4.12</junit.version> <spring.version>4.1.7.RELEASE</spring.version> <mybatis.version>3.2.6</mybatis.version> <org.slf4j.version>1.7.2</org.slf4j.version> <mysql.driver.version>5.1.32</mysql.driver.version> <com.fasterxml.jackson.jaxrs.version>2.4.1</com.fasterxml.jackson.jaxrs.version> <commons-fileupload.version>1.3.1</commons-fileupload.version> </properties> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <!-- 测试所需 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <!-- spring core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <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.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- mybatis核心包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!-- mybatis/spring包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <!-- MySQL数据库驱动 导入 start --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.driver.version}</version> </dependency> <!-- MySQL数据库驱动 导入 end --> <!-- 导入dbcp的jar包,数据库连接池 --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.2.2</version> </dependency> <!-- el 标签库 --> <!-- standard.jar --> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <!-- JSTL --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.1.2</version> </dependency> <!-- /el 标签库 --> <!-- 处理json --> <dependency> <groupId>com.fasterxml.jackson.jaxrs</groupId> <artifactId>jackson-jaxrs-xml-provider</artifactId> <version>${com.fasterxml.jackson.jaxrs.version}</version> </dependency> <!-- 文件上传下载 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>${commons-fileupload.version}</version> </dependency> <!-- slf4j 和 log4j合用的Maven配置 --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${org.slf4j.version}</version> </dependency> </dependencies> <build> <finalName>demo-ssm</finalName> </build> </project> </code></pre> <br /> 2.整合spring mybaties spring-mybatis.xml <pre> <code class="language-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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 引入配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties" /> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="${initialSize}"></property> <!-- 连接池最大数量 --> <property name="maxActive" value="${maxActive}"></property> <!-- 连接池最大空闲 --> <property name="maxIdle" value="${maxIdle}"></property> <!-- 连接池最小空闲 --> <property name="minIdle" value="${minIdle}"></property> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="${maxWait}"></property> </bean> <!-- ========================================针对myBatis的配置项============================== --> <!-- 配置sqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 实例化sqlSessionFactory时需要使用上述配置好的数据源以及SQL映射文件 --> <property name="dataSource" ref="dataSource" /> <!-- 自动扫描me/gacl/mapping/目录下的所有SQL映射的xml文件, 省掉Configuration.xml里的手工配置 value="classpath:com/mapper/*.xml"指的是classpath(类路径)下com.mapping包中的所有xml文件 UserMapper.xml位于com.mapping包下,这样UserMapper.xml就可以被自动扫描 --> <property name="mapperLocations" value="classpath:com/xqlee/dev/project/ssm/mapping/*.xml" /> <!-- 加载mybatis.cfg.xml文件 --> <property name="configLocation" value="classpath:mybatis.cfg.xml"></property> </bean> <!-- 配置扫描器 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 扫描com.dao这个包以及它的子包下的所有映射接口类 --> <property name="basePackage" value="com.xqlee.dev.project.ssm.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <!-- ========================================分隔线========================================= --> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> </beans> </code></pre> <br /> 3.mybatis.cfg.xml <pre> <code class="language-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> </configuration></code></pre> <br /> 4.jdbc.properties <pre> <code>driver=com.mysql.jdbc.Driver url=jdbc:mysql://127.0.0.1:3306/test username=root password=root initialSize=0 maxActive=20 maxIdle=20 minIdle=1 maxWait=60000</code></pre> <br /> 5.log4j.properties <pre> <code>log4j.rootLogger=INFO,Console,File log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.Target=System.out log4j.appender.Console.layout = org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n log4j.appender.File = org.apache.log4j.RollingFileAppender log4j.appender.File.File = logs/ssm.log log4j.appender.File.MaxFileSize = 10MB log4j.appender.File.Threshold = ALL log4j.appender.File.layout = org.apache.log4j.PatternLayout log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n </code></pre> <br /> 6.spring-context.xml,spring容器启动配置 <pre> <code class="language-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:mvc="http://www.springframework.org/schema/mvc" 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: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.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd "> <context:annotation-config /> <import resource="classpath:spring-mybatis.xml"/> <import resource="classpath:spring-mvc.xml"/> </beans></code></pre> <br /> 7.spring-mvc.xml,springMVC配置类 <pre> <code class="language-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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd "> <!-- 自动扫描controller包下所有 --> <context:component-scan base-package="com.xqlee.dev.project.ssm" /> <!-- 注解驱动 --> <mvc:annotation-driven /> <mvc:default-servlet-handler /> <!-- 资源管理不拦截 --> <mvc:resources location="/resources/" mapping="/resources/**" /> <mvc:resources location="/upload/" mapping="/upload/**" /> <!-- 内部资源视图解析器 prefix + logicName + suffix /WEB-INF/jsps/ + index + .jsp --> <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 前缀 --> <property name="prefix" value="/WEB-INF/pages/" /> <!-- 后缀 --> <property name="suffix" value="" /> </bean> <!-- 处理在controller中使用注解@ResponseBody标签返回JSON数据 Start --> <!-- 注意[由于我在pom.xml引入的是2.4.1版本]:所以class=org.springframework.http.converter.json.MappingJackson2HttpMessageConverter --> <!-- [如果pom.xml引入的是1.xx版本]class=org.springframework.http.converter.json.MappingJacksonHttpMessageConverter --> <bean id="mappingJackson2HttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <value>text/json;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> </bean> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJackson2HttpMessageConverter" /> </list> </property> </bean> <!-- JSON数据处理 End --> <!-- 上传图片/文件需要配置 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="-1" /><!-- -1表示没有限制 --> <property name="maxInMemorySize" value="4096" /> </bean> </beans></code></pre> <br /> 8.User.java <pre> <code class="language-java">package com.xqlee.dev.project.ssm.pojo; public class User { private int id; private String name; private String password; private int age; /** * @return the id */ public int getId() { return id; } /** * @param id * the id to set */ public void setId(int id) { this.id = id; } /** * @return the name */ public String getName() { return name; } /** * @param name * the name to set */ public void setName(String name) { this.name = name; } /** * @return the password */ public String getPassword() { return password; } /** * @param password * the password to set */ public void setPassword(String password) { this.password = password; } /** * @return the age */ public int getAge() { return age; } /** * @param age * the age to set */ public void setAge(int age) { this.age = age; } } </code></pre> 9.UserMapper.java <pre> <code class="language-java">package com.xqlee.dev.project.ssm.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import com.xqlee.dev.project.ssm.pojo.User; public interface UserMapper { User findById(@Param("id")int id); List<User> findList(@Param("name")String name); } </code></pre> 10.UserMapper.xml <pre> <code class="language-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.xqlee.dev.project.ssm.dao.UserMapper"> <resultMap id="BaseMap" type="com.xqlee.dev.project.ssm.pojo.User"> <id column="id" property="id" jdbcType="INTEGER" /><!-- 注意这里的jdbcType参考mybaties官方文档 --> <result column="name" property="name" jdbcType="VARCHAR" /> </resultMap> <!-- mapper代理开发方式,namespace的值必须是对应接口的全类名 --> <select id="findById" parameterType="int" resultType="com.xqlee.dev.project.ssm.pojo.User"> select * from t_user where id = #{id} </select> <select id="findList" resultMap="BaseMap" parameterType="java.util.Map"> select * from t_user u where 1=1 <if test="name != null"> and u.name like CONCAT('%',#{name,jdbcType=VARCHAR},'%') </if> </select> </mapper> </code></pre> 11.UserService.java <pre> <code class="language-java">package com.xqlee.dev.project.ssm.service; import java.util.List; import com.xqlee.dev.project.ssm.pojo.User; public interface UserService { User getById(int id); List<User> findList(String name); } </code></pre> 12.UserServiceImp.java <pre> <code class="language-java">package com.xqlee.dev.project.ssm.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.xqlee.dev.project.ssm.dao.UserMapper; import com.xqlee.dev.project.ssm.pojo.User; @Service("userService") public class UserServiceImp implements UserService { @Autowired UserMapper userMapper; @Override public User getById(int id) { return userMapper.findById(id); } @Override public List<User> findList(String name) { // TODO Auto-generated method stub return userMapper.findList(name); } } </code></pre> <br /> 13.Test.java <pre> <code class="language-java">package com.xqlee.dev.project.ssm; import java.util.List; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.xqlee.dev.project.ssm.pojo.User; import com.xqlee.dev.project.ssm.service.UserService; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:spring-context.xml" }) public class Test { @Autowired UserService userService; @org.junit.Test public void test1() { User user = userService.getById(1); System.out.println(user.getName()); List<User> users=userService.findList(""); for(User u:users){ System.out.println("name:"+u.getName()+" id:"+u.getId()); } } } </code></pre> 14.测试表以及测试数据 <pre> <code class="language-sql">DROP TABLE IF EXISTS `t_user`; CREATE TABLE `t_user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(40) NOT NULL, `password` varchar(255) NOT NULL, `age` int(4) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; /*Data for the table `user_t` */ insert into `t_user`(`id`,`name`,`password`,`age`) values (1,'测试1','123456',24); insert into `t_user`(`id`,`name`,`password`,`age`) values (2,'测试2','123456',25); insert into `t_user`(`id`,`name`,`password`,`age`) values (3,'测试3','123456',26); </code></pre> 15.执行测试:<br /> <img alt="测试结果" class="img-thumbnail" src="/resources/assist/images/blog/a9af66c8-3278-4c69-a287-1019e80bbf72.jpg" style="height:515px; width:972px" /><br /> <br /> 看到上图的结果,表示spring+mybaties已经完成整合,接下来将springMVC整合进来就OK了。<br /> <br /> 16.配置web.xml,整合上面的springMVC+spring+mybaties <pre> <code class="language-xml"><web-app 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" version="3.0"> <display-name>Archetype Created Web Application</display-name> <!-- 字符集处理 --> <filter> <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- spring 核心配置 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/spring-context.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 配置缓存清除监听器,负责处理由 JavaBean Introspector 功能而引起的缓存泄露 --> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!-- springMVC配置 --> <servlet> <servlet-name>springMVCSerlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <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> <servlet-mapping> <servlet-name>springMVCSerlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 添加下面容器,防止同一个服务器部署多个项目web.root冲突 --> <context-param> <param-name>webAppRootKey</param-name> <param-value>springMVC4</param-value> </context-param> <!-- session timeout --> <session-config> <!-- 分钟 --> <session-timeout>60</session-timeout> </session-config> <!-- log4j配置 --> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:/log4j.properties</param-value> </context-param> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>60000</param-value> </context-param> <!--添加监听 --> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <!-- /log4j配置 --> <!-- welcome page --> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- session copy --> <distributable /> </web-app></code></pre> 17.WEB-INF目录下创建pages目录,并且在里面创建一个hello.jsp<br /> hello.jsp: <pre> <code class="language-html"><%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>hello</title> </head> <body> Hello ,<B>${name }</B> </body> </html></code></pre> 18.创建UserController.java <pre> <code class="language-java">package com.xqlee.dev.project.ssm.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import com.xqlee.dev.project.ssm.pojo.User; import com.xqlee.dev.project.ssm.service.UserService; @Controller public class UserController { @Autowired UserService userService; @RequestMapping("/hello/{id}.html") public String hello(@PathVariable(value="id") int id, Model model) { User user = userService.getById(id); model.addAttribute("name", user.getName()); return "hello.jsp"; } } </code></pre> <br /> 上面内容创建完成后,将项目添加到tomcat或者其他容器中,启动项目<br /> <img alt="tomcat启动日志" class="img-thumbnail" src="/resources/assist/images/blog/fab24f7c-8095-48cd-8b7c-8c6a27dd1f0c.png" style="height:684px; width:871px" /><br /> <br /> 上图是tomcat的启动日志,圈出来的是我们在UserController写的一个访问类<br /> 下面在浏览器中输入地址:<br /> <img alt="浏览器" class="img-thumbnail" src="/resources/assist/images/blog/e65e25b3-a9f8-4608-acc8-1481c12f20f4.png" style="height:323px; width:512px" /><br /> 说明:访问地址 /hello/1.html<br /> 1表示后台control中接受到的用户id的参数值。<br /> 之所以页面显示的测试1,是因为前面我们已经将测试数据导入数据库,id等于1的用户刚好名称叫测试1<br /> 至此SSM三大框架整合基础完成。
  • Apache httpclient4.5 GET/POST/PUT/OPTION/DELETE工具类

    Apache httpclient4.5 GET/POST/PUT/OPTION/DELETE工具类Apache httpclient4.5 GET/POST/PUT/OPTION/DELETE工具类<br /> <br /> 该工具类使用比较新的<br /> Apache httpclient4.5版本<br /> <br /> 支持GET请求、POST请求、DELETE请求、PATCH请求、PUT请求、DELETE请求、OPTIONS请求<br /> <br /> 工具类代码如下: <pre> <code class="language-java"> import org.apache.http.Header; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.*; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.StringUtils; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; import java.nio.charset.Charset; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 工具类 httpclient4.5 * * @author xq */ public class HttpclientUtils { private final static Logger logger = LoggerFactory.getLogger(HttpclientUtilss.class); /** * post请求 json参数 * * @param url * @param bodyJsonParams * @param headers * @return * @throws IOException */ public static String doPost(String url, String bodyJsonParams, Map<String, String> headers) throws IOException { HttpPost httpPost = new HttpPost(url); httpPost.addHeader("Content-Type", "application/json"); httpPost.setEntity(new StringEntity(bodyJsonParams, Charset.forName("UTF-8"))); addHeader(httpPost, headers); return execute(httpPost); } /** * post k-v参数 * * @param url * @param params * @param headers * @return * @throws IOException */ public static String doPost(String url, Map<String, String> params, Map<String, String> headers) throws IOException { HttpPost httpPost = new HttpPost(url); if (params != null && params.keySet().isEmpty()) { httpPost.setEntity(getUrlEncodedFormEntity(params)); } addHeader(httpPost, headers); return execute(httpPost); } /** * patch json参数 * * @param url * @param bodyJsonParams * @param headers * @return * @throws IOException */ public static String doPatch(String url, String bodyJsonParams, Map<String, String> headers) throws IOException { HttpPatch httpPatch = new HttpPatch(url); httpPatch.setEntity(new StringEntity(bodyJsonParams)); addHeader(httpPatch, headers); return execute(httpPatch); } /** * patch k-v参数 * * @param url * @param params * @param headers * @return * @throws IOException */ public static String doPatch(String url, Map<String, String> params, Map<String, String> headers) throws IOException { HttpPatch httpPatch = new HttpPatch(url); if (params != null && !params.isEmpty()) { httpPatch.setEntity(getUrlEncodedFormEntity(params)); } addHeader(httpPatch, headers); return execute(httpPatch); } /** * PUT JSON参数 * * @param url * @param bodyJsonParams * @param headers * @return * @throws IOException */ public static String doPut(String url, String bodyJsonParams, Map<String, String> headers) throws IOException { HttpPut httpPut = new HttpPut(url); httpPut.addHeader("Content-Type", "application/json"); httpPut.setEntity(new StringEntity(bodyJsonParams, Charset.forName("UTF-8"))); addHeader(httpPut, headers); return execute(httpPut); } /** * put k-v参数 * * @param url * @param params * @param headers * @return * @throws IOException */ public static String doPut(String url, Map<String, String> params, Map<String, String> headers) throws IOException { HttpPut httpPut = new HttpPut(url); if (params != null && params.keySet().isEmpty()) { httpPut.setEntity(getUrlEncodedFormEntity(params)); } addHeader(httpPut, headers); return execute(httpPut); } /** * Delete json 参数 * * @param url * @param bodyJsonParams * @param headers * @return * @throws IOException */ public static String doDeletedoPut(String url, String bodyJsonParams, Map<String, String> headers) throws IOException { HttpDeleteWithEntity httpDelete = new HttpDeleteWithEntity(url); httpDelete.setEntity(new StringEntity(bodyJsonParams)); addHeader(httpDelete, headers); return execute(httpDelete); } /** * delete k-v参数 * * @param url * @param params * @param headers * @return * @throws IOException */ public static String doDelete(String url, Map<String, String> params, Map<String, String> headers) throws IOException { HttpDeleteWithEntity httpDelete = new HttpDeleteWithEntity(url); addHeader(httpDelete, headers); if (params != null && !params.isEmpty()) { httpDelete.setEntity(getUrlEncodedFormEntity(params)); } return execute(httpDelete); } /** * options json参数 * * @param url * @param bodyJsonParams * @param headers * @return * @throws IOException */ public static String doOptions(String url, String bodyJsonParams, Map<String, String> headers) throws IOException { HttpOptionsWithEntity httpOptions = new HttpOptionsWithEntity(url); addHeader(httpOptions, headers); httpOptions.setEntity(new StringEntity(bodyJsonParams)); return execute(httpOptions); } /** * options k-v参数 * * @param url * @param params * @param headers * @return * @throws IOException */ public static String doOptions(String url, Map<String, String> params, Map<String, String> headers) throws IOException { HttpOptionsWithEntity httpOptions = new HttpOptionsWithEntity(url); addHeader(httpOptions, headers); if (params != null && !params.isEmpty()) { httpOptions.setEntity(getUrlEncodedFormEntity(params)); } return execute(httpOptions); } /** * head请求 * * @param url * @param headers * @return * @throws IOException */ public static String doHeader(String url, Map<String, String> headers) throws IOException { HttpHead httpHead = new HttpHead(url); addHeader(httpHead, headers); return execute(httpHead); } /** * get请求 * * @param url * @param params * @param headers * @return * @throws IOException * @throws ClientProtocolException */ public static String doGet(String url, Map<String, String> params, Map<String, String> headers) throws IOException { // 参数 StringBuilder paramsBuilder = new StringBuilder(url); if (params != null && params.keySet().isEmpty()) { if (url.indexOf("?") == -1) { paramsBuilder.append("?"); } List<NameValuePair> list = new ArrayList<>(); Set<String> keySet = headers.keySet(); Iterator<String> iterator = keySet.iterator(); while (iterator.hasNext()) { String key = iterator.next(); String value = headers.get(key); list.add(new BasicNameValuePair(key, value)); } String paramsStr = EntityUtils.toString(new UrlEncodedFormEntity(list)); paramsBuilder.append(paramsStr); } HttpGet httpGet = new HttpGet(paramsBuilder.toString()); // 头 addHeader(httpGet, headers); return execute(httpGet); } /** * 执行请求并返回string值 * * @param httpUriRequest * @return * @throws IOException */ private static String execute(HttpUriRequest httpUriRequest) throws IOException { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { CloseableHttpResponse response = httpClient.execute(httpUriRequest); // if (response.getStatusLine().getStatusCode() == 200) {// 请求成功状态 // try (BufferedReader bufferedReader = new BufferedReader( // new InputStreamReader(response.getEntity().getContent()))) { // StringBuilder sb = new StringBuilder(); // String tmp; // while ((tmp = bufferedReader.readLine()) != null) { // sb.append(tmp); // } // return sb.toString(); // } // } Header type = response.getEntity().getContentType(); logger.debug("Type:" + type.getValue()); String defaultCharset = "UTF-8"; String charset = getCharSet(type.getValue()); if (!StringUtils.isEmpty(charset)) { defaultCharset = charset; } return EntityUtils.toString(response.getEntity(), defaultCharset); } // return null; } /** * 添加请求头部 * * @param httpUriRequest * @param headers */ private static void addHeader(HttpUriRequest httpUriRequest, Map<String, String> headers) { if (httpUriRequest != null) { if (headers != null && !headers.keySet().isEmpty()) { Set<String> keySet = headers.keySet(); Iterator<String> iterator = keySet.iterator(); while (iterator.hasNext()) { String key = iterator.next(); String value = headers.get(key); httpUriRequest.addHeader(key, value); } } } } /** * 获取 UrlEncodedFormEntity 参数实体 * * @param params * @return * @throws UnsupportedEncodingException */ private static UrlEncodedFormEntity getUrlEncodedFormEntity(Map<String, String> params) throws UnsupportedEncodingException { if (params != null && params.keySet().isEmpty()) { List<NameValuePair> list = new ArrayList<>(); Set<String> keySet = params.keySet(); Iterator<String> iterator = keySet.iterator(); while (iterator.hasNext()) { String key = iterator.next(); String value = params.get(key); list.add(new BasicNameValuePair(key, value)); } return new UrlEncodedFormEntity(list); } return null; } /** * 根据HTTP 响应头部的content type抓取响应的字符集编码 * * @param content * @return */ private static String getCharSet(String content) { String regex = ".*charset=([^;]*).*"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(content); if (matcher.find()) return matcher.group(1); else return null; } /** * 解决httpclient 的DELETE默认不支持setEntity */ static class HttpDeleteWithEntity extends HttpEntityEnclosingRequestBase { public static final String METHOD_NAME = "DELETE"; @Override public String getMethod() { return METHOD_NAME; } public HttpDeleteWithEntity(final String uri) { super(); setURI(URI.create(uri)); } public HttpDeleteWithEntity(final URI uri) { super(); setURI(uri); } public HttpDeleteWithEntity() { super(); } } /** * 解决httpclient 的OPTIONS默认不支持setEntity */ static class HttpOptionsWithEntity extends HttpEntityEnclosingRequestBase { public static final String METHOD_NAME = "OPTIONS"; @Override public String getMethod() { return METHOD_NAME; } public HttpOptionsWithEntity() { super(); } public HttpOptionsWithEntity(final String uri) { super(); setURI(URI.create(uri)); } public HttpOptionsWithEntity(final URI uri) { super(); setURI(uri); } } public static void main(String[] args) { } } </code></pre>  
  • java dom4j处理xml添加document删除document

    java dom4j处理xml添加document删除document <pre> <code class="language-java">package org.xqlee.utils.xml; import java.util.List; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; /** * * * <pre> * _________________________INFO_____________________________ * | Description : [dom4j处理xml] * | Encoding : [UTF-8] * | Package : [org.xqlee.utils.xml.test] * | Project : [utils] * | Author : [LXQ] * | CreateDate : [2016年3月23日上午11:14:35] * | Updater : [] * | UpdateDate : [] * | UpdateRemark: [] * | Company : [www.zhljc.com] * | Version : [v 1.0] * | Libs : [dom4j-1.6.1.jar xml-apis-1.0b2.jar jaxen-1.1.6.jar] * __________________________________________________________ * </pre> */ public class Dom4j { public static void main(String[] params) { System.out.println("=====1.开始生产xml====="); String xml = createXML(); System.out.println("=====2.结束生产xml====="); System.out.println("=====3.第一次解析====="); String2XML(xml); System.out.println("=====4.第二次解析"); xml=" "+xml;//注意xml文档的<?xml version="1.0" encoding="GBK"?>前面不允许有其他值 String2XML(xml); } /** * 创建xml * * @return xml文档字符串 */ public static String createXML() { System.out.println("============xml创建==============="); // 1.创建文档 Document doc = DocumentHelper.createDocument(); // 设置文件编码格式 doc.setXMLEncoding("GBK"); // 2.文档中添加节点||注意文档中只能有一个root节点 Element root = doc.addElement("ROOT"); root.addAttribute("root", "http://www.zhljc.com"); // 头部 Element header = root.addElement("HEADER"); header.addAttribute("header", "http://zhljc.com"); header.addElement("HPARAM1").addText("Header param 1"); header.addElement("HPARAM2").addText("Header param 2"); // fields Element f1 = header.addElement("field"); f1.addAttribute("name", "F1"); f1.addText("0000f2"); Element f2 = header.addElement("field"); f2.addAttribute("name", "F2"); f2.addText("0000f2"); Element f3 = header.addElement("field"); f3.addAttribute("name", "F3"); f3.addText("0000f3"); // body Element body = root.addElement("BODY"); body.addAttribute("body", "http://www.zhljc.com"); body.addElement("BPARAM1").addText("Body param 1"); body.addElement("BPARAM2").addText("Body param 2"); // 3.转换为字符集的xml String xml = doc.asXML(); System.out.println("xml1:\n" + xml); return xml; } /** * 解析xml * * @param xml * 字符串的xml参数 */ public static void String2XML(String xml) { System.out.println("============xml解析==============="); try { // 转换 Document doc = DocumentHelper.parseText(xml); // 获取节点内容 String headerParam1Text = doc.selectSingleNode("/ROOT/HEADER/HPARAM1").getText(); System.out.println("节点ROOT->HEADER->HPARAM1的值为:" + headerParam1Text); @SuppressWarnings("unchecked") List<Element> ns = doc.selectNodes("/ROOT/HEADER/field"); System.out.println("通过属性名称查询节点TEXT值:"+getTextByAttribute(ns,"name","F1")); } catch (DocumentException e) { System.out.println("转换异常:" + e.getMessage()); e.printStackTrace(); } } public static String getTextByAttribute(List<Element> nodes, String attributeName, String attributeValue) { for (Element node : nodes) { if (node.attributeValue(attributeName).equals(attributeValue)) { return node.getText(); } } return null; } } </code></pre>
  • java常用框架SpringMVC3/4入门教程

    SpringMVC框架是一个java里面非常轻量级的mvc框架之一,与spring框架同源,整合方便快捷.java常用框架SpringMVC3/4入门教程 <p>1SpringMVC3</p> <p>1.1项目结构图</p> <img alt="java常用框架SpringMVC3/4入门教程" src="/resources/assist/images/blog/50f775fc-8470-4e98-bab8-a9195d8d2671.png" style="height:527px; width:313px" /> <p>1.2Pom.xml</p> <pre> <code class="language-xml"><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/maven-v4_0_0.xsd">    <modelVersion>4.0.0</modelVersion>    <groupId>seven.org</groupId>    <artifactId>springmvc3</artifactId>    <packaging>war</packaging>    <version>0.0.1-SNAPSHOT</version>    <name>springmvc3 Maven Webapp</name>    <url>http://maven.apache.org</url>    <properties>       <junit.version>4.12</junit.version>       <spring.version>3.2.2.RELEASE</spring.version>       <org.codehaus.jackson.version>1.9.13</org.codehaus.jackson.version>       <commons-fileupload.version>1.3.1</commons-fileupload.version>    </properties>    <dependencies>       <dependency>          <!-- test -->          <groupId>junit</groupId>          <artifactId>junit</artifactId>          <version>${junit.version}</version>          <scope>test</scope>       </dependency>         <!-- spring framework start -->       <dependency>          <groupId>org.springframework</groupId>          <artifactId>spring-core</artifactId>          <version>${spring.version}</version>       </dependency>       <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>       <!-- spring framework end -->         <!-- 为SpringMVC提供json数据类型支持 -->         <!-- 注意,新版的 jackson-core-asl已经升级为Group:com.fasterxml.jackson.core|Artifact:jackson-core在SpringMVC4中需要使用新版 -->       <dependency>          <groupId>org.codehaus.jackson</groupId>          <artifactId>jackson-core-asl</artifactId>          <version>${org.codehaus.jackson.version}</version>       </dependency>       <dependency>          <groupId>org.codehaus.jackson</groupId>          <artifactId>jackson-mapper-asl</artifactId>          <version>${org.codehaus.jackson.version}</version>       </dependency>         <!-- el 标签库 -->       <!-- standard.jar -->       <dependency>          <groupId>taglibs</groupId>          <artifactId>standard</artifactId>          <version>1.1.2</version>       </dependency>       <!-- JSTL -->       <dependency>          <groupId>javax.servlet</groupId>          <artifactId>jstl</artifactId>          <version>1.1.2</version>       </dependency>       <!-- /el 标签库 -->         <!-- 文件上传下载 -->       <dependency>          <groupId>commons-fileupload</groupId>          <artifactId>commons-fileupload</artifactId>          <version>${commons-fileupload.version}</version>       </dependency>         <!-- slf4j 和 log4j合用的Maven配置 -->       <dependency>          <groupId>org.slf4j</groupId>          <artifactId>slf4j-log4j12</artifactId>          <version>1.7.2</version>       </dependency>      </dependencies>    <build>       <finalName>springmvc3</finalName>    </build> </project></code></pre>   <p>1.3web.xml</p> <pre> <code class="language-xml"><web-app 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"    version="3.0">    <display-name>Archetype Created Web Application</display-name>      <!-- 字符集处理 -->    <filter>       <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>       <url-pattern>/*</url-pattern>    </filter-mapping>        <!-- spring 配置 -->    <context-param>       <param-name>contextConfigLocation</param-name>       <param-value>classpath:/cfg/spring/spring-beans.xml</param-value>    </context-param>    <listener>       <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    </listener>      <!-- 配置缓存清除监听器,负责处理由 JavaBean Introspector 功能而引起的缓存泄露 -->    <listener>       <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>    </listener>        <!-- springMVC配置 -->    <servlet>       <servlet-name>springMVCSerlet</servlet-name>       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>       <init-param>          <param-name>contextConfigLocation</param-name>          <param-value>classpath:/cfg/spring/spring-servlet.xml</param-value>       </init-param>       <load-on-startup>1</load-on-startup>    </servlet>    <servlet-mapping>       <servlet-name>springMVCSerlet</servlet-name>       <url-pattern>/</url-pattern>    </servlet-mapping>      <!-- 添加下面容器,防止同一个服务器部署多个项目web.root冲突 -->    <context-param>       <param-name>webAppRootKey</param-name>       <param-value>springMVC3</param-value>    </context-param>        <!-- log4j配置 -->    <context-param>       <param-name>log4jConfigLocation</param-name>       <param-value>classpath:/cfg/log/Log4j.properties</param-value>    </context-param>    <context-param>       <param-name>log4jRefreshInterval</param-name>       <param-value>60000</param-value>    </context-param>      <!-- session timeout -->    <session-config>       <!-- 分钟 -->       <session-timeout>60</session-timeout>    </session-config>      <!-- welcome page -->    <welcome-file-list>       <welcome-file>index.html</welcome-file>       <welcome-file>index.jsp</welcome-file>    </welcome-file-list>      <!-- session copy -->    <distributable /> </web-app></code></pre>   <p>1.4spring-servlet.xml</p> <pre> <code class="language-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:mvc="http://www.springframework.org/schema/mvc"    xmlns:context="http://www.springframework.org/schema/context"    xsi:schemaLocation="http://www.springframework.org/schema/beans             http://www.springframework.org/schema/beans/spring-beans-3.2.xsd             http://www.springframework.org/schema/mvc             http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd             http://www.springframework.org/schema/context             http://www.springframework.org/schema/context/spring-context-3.2.xsd ">      <!-- 自动扫描包 -->    <context:component-scan base-package="com" />      <!-- 注解驱动 -->    <mvc:annotation-driven />    <mvc:default-servlet-handler />    <!-- 资源管理不拦截 -->    <mvc:resources location="/resources/" mapping="/resources/**" />    <mvc:resources location="/upload/" mapping="/upload/**" />      <!-- 内部资源视图解析器 prefix + logicName + suffix /WEB-INF/jsps/ + index + .jsp -->    <bean id="internalResourceViewResolver"       class="org.springframework.web.servlet.view.InternalResourceViewResolver">       <!-- 前缀 -->       <property name="prefix" value="/WEB-INF/pages/" />       <!-- 后缀 -->       <property name="suffix" value="" />    </bean>        <!-- 上传图片/文件需要配置 -->    <bean id="multipartResolver"       class="org.springframework.web.multipart.commons.CommonsMultipartResolver">       <property name="maxUploadSize" value="104857600" />       <property name="maxInMemorySize" value="4096" />    </bean>        <!-- 配置JSON支持 start -->    <bean id="mappingJacksonHttpMessageConverter"    class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">       <property name="supportedMediaTypes">          <list>             <!-- 处理返回的json数据的编码,默认是ISO-88859-1 -->             <value>text/html;charset=UTF-8</value>          </list>       </property>    </bean>    <bean    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">       <!-- messageConverters属性中加入 mappingJacksonHttpMessageConverter用来处理json数据类行 -->       <property name="messageConverters">          <list>             <ref bean="mappingJacksonHttpMessageConverter" />          </list>       </property>    </bean>    <!-- 配置JSON支持 end -->     </beans></code></pre> <br /> 1.5spring-beans.xml <pre> <code class="language-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:mvc="http://www.springframework.org/schema/mvc"    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:jpa="http://www.springframework.org/schema/data/jpa"    xsi:schemaLocation="http://www.springframework.org/schema/beans                 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd             http://www.springframework.org/schema/mvc             http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd               http://www.springframework.org/schema/aop             http://www.springframework.org/schema/aop/spring-aop-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/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.xsd ">    <context:annotation-config />    <!-- 启动自动扫描该包下所有的注解(如@controller) -->    <context:component-scan base-package="com" />   </beans>  </code></pre>   <p>1.6Log4j配置文件</p> <pre> <code>#defind the rooeLogger ,the rootlogger min level is INFO,and two way to output log log4j.rootLogger = INFO,FILE,CONSOLE,DATABASE   #---------------------------------------------------------------------- #defind the FILE as file everyday                                     | #---------------------------------------------------------------------- log4j.appender.FILE = org.apache.log4j.DailyRollingFileAppender   #the log min level set as INFO log4j.appender.FILE.Threshold=INFO   #log file encoding set UTF-8 log4j.appender.FILE.encoding=UTF-8   #log file path log4j.appender.FILE.File=/home/tomcat/log/springmvc3/springmvc3   #log file name append log4j.appender.FILE.DatePattern='_'yyyy-MM-dd'.log'   #Immediate write the log is true log4j.appender.FILE.ImmediateFlush=true   #the layout of the log log4j.appender.FILE.layout=org.apache.log4j.PatternLayout   #the detail layout of log  in the log file log4j.appender.FILE.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} Springmvc3 %-5p [%c:%L] | %m%n   #------------------------------------------------------------------------- #this use the 'org.apache.log4j.ConsoleAppender' to output in the Console| #------------------------------------------------------------------------- log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender   #output min level is INFO log4j.appender.Threshold=INFO   #the output target is Console log4j.appender.CONSOLE.Target=System.out   #the layout of the log log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} springmvc3 %-5p | %m%n   #---------------------------------------------------------------------------- #insert the log into database                                               | #---------------------------------------------------------------------------- log4j.appender.DATABASE=org.apache.log4j.jdbc.JDBCAppender #The jdbc url log4j.appender.DATABASE.URL=jdbc:mysql://localhost:3306/springmvc3 #The jdbc driver log4j.appender.DATABASE.driver=com.mysql.jdbc.Driver #DB user log4j.appender.DATABASE.user=root #DB password log4j.appender.DATABASE.password=root #sql log4j.appender.DATABASE.sql=INSERT INTO zhl_log (operationTime,logLevel,logClass,logDetail)  VALUES ("%d{yyyy-MM-dd HH:mm:ss}", "%-5p","%F:%L", "%m") #layout log4j.appender.DATABASE.layout=org.apache.log4j.PatternLayout #layout detail log4j.appender.DATABASE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n</code></pre> <br /> 1.7测试vo <pre> <code class="language-java">package com.xqlee.springmvc.vo;   /**  *  *  * <pre>  * @功能说明 [测试bean]  * @其他说明 [暂无]  * @文件编码 [UTF-8]  * @所属包名 [com.xqlee.springmvc.vo]  * @项目名称 [cdws]  * @创建日期 []  * @创建人员 [lxq]  * @最后修改 []  * @修改说明 [暂无更新]  * @修改人员 [lxq]  * @公司组织 [org]  * @版本说明 [v 1.0]  *  * </pre>  */ public class Tobject {      private String id;    private String name;    private String num;      public Tobject(String id, String name, String num) {       this.id = id;       this.name = name;       this.num = num;    }      public String getId() {       return id;    }      public void setId(String id) {       this.id = id;    }      public String getName() {       return name;    }      public void setName(String name) {       this.name = name;    }      public String getNum() {       return num;    }      public void setNum(String num) {       this.num = num;    }   }</code></pre> <br /> 1.8测试controller <pre> <code class="language-java">package com.xqlee.springmvc.controller;   import java.util.Vector;   import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;   import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody;   import com.xqlee.springmvc.vo.Tobject;   /**  *  *  * <pre>  * @功能说明 [测试类]  * @其他说明 [暂无]  * @文件编码 [UTF-8]  * @所属包名 [com.xqlee.springmvc.controller]  * @项目名称 [cdws]  * @创建日期 []  * @创建人员 [lxq]  * @最后修改 []  * @修改说明 [暂无更新]  * @修改人员 [lxq]  * @公司组织 [org]  * @版本说明 [v 1.0]  *  * </pre>  */ @Controller(value = "/beanTestController.do") public class BeanTestController {    @RequestMapping(params = "method=Vector")    // @ResponseBody    public Object testVector(HttpServletRequest request,          HttpServletResponse response) {       // 创建容器       Vector<Tobject> vtb = new Vector<Tobject>();       Tobject tb;       for (int i = 0; i <= 5; i++) {          tb = new Tobject("ID-" + i, "名称Name-" + i, "Num-" + i);          vtb.add(tb);       }       request.setAttribute("vtb", vtb);       return "../../vector.jsp";    }      @RequestMapping(params = "method=testJson")    @ResponseBody    public Object testJson(HttpServletRequest request,          HttpServletResponse response) {       // 创建容器       Vector<Tobject> vtb = new Vector<Tobject>();       Tobject tb;       for (int i = 0; i <= 5; i++) {          tb = new Tobject("ID-" + i, "名称Name-" + i, "Num-" + i);          vtb.add(tb);       }       return vtb;    }   }</code></pre>   <p>1.9index.jsp</p> <pre> <code class="language-html"><!DOCTYPE> <html> <body>    <h2>Hello World!</h2>    <a href="beanTestController.do?method=Vector">Vector Test</a> </body> </html></code></pre> <br /> 1.10vector.jsp <pre> <code class="language-html"><%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE> <html> <body>    <table border='1'>       <thead>          <tr>             <td>ID</td>             <td>Name</td>             <td>Num</td>          </tr>       </thead>       <tbody>          <c:forEach items="${vtb}" var="Object">             <tr>                 <td>${Object.id}</td>                 <td>${Object.name}</td>                 <td>${Object.num}</td>             </tr>          </c:forEach>       </tbody>    </table>     </body> </html></code></pre> <br /> 2 SpringMVC4 <p>2.1项目结构图</p> <img alt="2" src="/resources/assist/images/blog/63555b40-5fa1-41e6-9d7c-3d9e088a6223.png" style="height:510px; width:387px" /> <p>2.2pom.xml</p> <pre> <code class="language-xml"><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/maven-v4_0_0.xsd">    <modelVersion>4.0.0</modelVersion>    <groupId>seven.org</groupId>    <artifactId>springMVC</artifactId>    <packaging>war</packaging>    <version>0.0.1-SNAPSHOT</version>    <name>springMVC Maven Webapp</name>    <url>http://maven.apache.org</url>    <!-- 属性版本 -->    <properties>       <junit.version>4.12</junit.version>       <spring.version>4.1.7.RELEASE</spring.version>       <org.slf4j.version>1.7.2</org.slf4j.version>       <mysql.driver.version>5.1.32</mysql.driver.version>    <com.fasterxml.jackson.jaxrs.version>2.4.1</com.fasterxml.jackson.jaxrs.version>       <commons-fileupload.version>1.3.1</commons-fileupload.version>      </properties>    <dependencies>         <!-- 测试所需 -->       <dependency>          <groupId>junit</groupId>          <artifactId>junit</artifactId>          <version>${junit.version}</version>          <scope>test</scope>       </dependency>         <!-- spring core -->       <dependency>          <groupId>org.springframework</groupId>          <artifactId>spring-core</artifactId>          <version>${spring.version}</version>       </dependency>       <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>         <!-- MySQL数据库驱动 导入 start -->       <dependency>          <groupId>mysql</groupId>          <artifactId>mysql-connector-java</artifactId>          <version>${mysql.driver.version}</version>       </dependency>       <!-- MySQL数据库驱动 导入 end -->           <!-- el 标签库 -->       <!-- standard.jar -->       <dependency>          <groupId>taglibs</groupId>          <artifactId>standard</artifactId>          <version>1.1.2</version>       </dependency>       <!-- JSTL -->       <dependency>          <groupId>javax.servlet</groupId>          <artifactId>jstl</artifactId>          <version>1.1.2</version>       </dependency>       <!-- /el 标签库 -->         <!-- 处理json -->       <dependency>          <groupId>com.fasterxml.jackson.jaxrs</groupId>          <artifactId>jackson-jaxrs-xml-provider</artifactId>          <version>${com.fasterxml.jackson.jaxrs.version}</version>       </dependency>         <!-- 文件上传下载 -->       <dependency>          <groupId>commons-fileupload</groupId>          <artifactId>commons-fileupload</artifactId>          <version>${commons-fileupload.version}</version>       </dependency>         <!-- slf4j 和 log4j合用的Maven配置 -->       <dependency>          <groupId>org.slf4j</groupId>          <artifactId>slf4j-log4j12</artifactId>          <version>${org.slf4j.version}</version>       </dependency>      </dependencies>    <build>       <finalName>springMVC</finalName>    </build> </project></code></pre> <br /> 2.3web.xml <pre> <code class="language-xml"><web-app 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"    version="3.0">    <display-name>Archetype Created Web Application</display-name>      <!-- 字符集处理 -->    <filter>       <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>       <url-pattern>/*</url-pattern>    </filter-mapping>        <!-- spring 核心配置 -->    <context-param>       <param-name>contextConfigLocation</param-name>       <param-value>classpath:/cfg/spring/spring-beans.xml</param-value>    </context-param>    <listener>       <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    </listener>      <!-- 配置缓存清除监听器,负责处理由 JavaBean Introspector 功能而引起的缓存泄露 -->    <listener>       <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>    </listener>        <!-- springMVC配置 -->    <servlet>       <servlet-name>springMVCSerlet</servlet-name>       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>       <init-param>          <param-name>contextConfigLocation</param-name>          <param-value>classpath:/cfg/spring/spring-servlet.xml</param-value>       </init-param>       <load-on-startup>1</load-on-startup>    </servlet>    <servlet-mapping>       <servlet-name>springMVCSerlet</servlet-name>       <url-pattern>/</url-pattern>    </servlet-mapping>      <!-- 添加下面容器,防止同一个服务器部署多个项目web.root冲突 -->    <context-param>       <param-name>webAppRootKey</param-name>       <param-value>springMVC4</param-value>    </context-param>      <!-- session timeout -->    <session-config>       <!-- 分钟 -->       <session-timeout>60</session-timeout>    </session-config>      <!-- log4j配置 -->    <context-param>       <param-name>log4jConfigLocation</param-name>       <param-value>classpath:/cfg/log/Log4j.properties</param-value>    </context-param>    <context-param>       <param-name>log4jRefreshInterval</param-name>       <param-value>60000</param-value>    </context-param>    <!--添加监听 -->    <listener>       <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>    </listener>    <!-- /log4j配置 -->      <!-- welcome page -->    <welcome-file-list>       <welcome-file>index.html</welcome-file>       <welcome-file>index.jsp</welcome-file>    </welcome-file-list>      <!-- session copy -->    <distributable /> </web-app></code></pre>   <p>2.4 weblogic.xml</p> <pre> <code class="language-xml"><?xml version="1.0" encoding="UTF-8"?> <weblogic-web-app xmlns="http://xmlns.oracle.com/weblogic/weblogic-web-app"    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/ejb-jar_3_0.xsd    http://xmlns.oracle.com/weblogic/weblogic-web-app    http://xmlns.oracle.com/weblogic/weblogic-web-app/1.2/weblogic-web-app.xsd">      <container-descriptor>       <!-- 针对weblogic10以下的版本使用该语句,不能与厦门的prefer-application-packages同时使用 -->       <!-- <prefer-web-inf-classes>true</prefer-web-inf-classes> -->       <!-- 针对weblogic10及以上的版本如果上面语句无法成功使用该语句,不能与厦门的prefer-web-inf-classes同时使用 -->       <prefer-application-packages>          <package-name>org.apache.commons.lang.*</package-name>          <package-name>antlr.*</package-name>          <package-name>org.hibernate.*</package-name>          <package-name>javax.persistence.*</package-name>       </prefer-application-packages>    </container-descriptor> </weblogic-web-app></code></pre>   <p>2.5spring-servlet.xml</p> <pre> <code class="language-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:mvc="http://www.springframework.org/schema/mvc"    xmlns:context="http://www.springframework.org/schema/context"    xsi:schemaLocation="http://www.springframework.org/schema/beans             http://www.springframework.org/schema/beans/spring-beans-4.1.xsd             http://www.springframework.org/schema/mvc             http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd             http://www.springframework.org/schema/context             http://www.springframework.org/schema/context/spring-context-4.1.xsd ">      <!-- 自动扫描controller包下所有 -->    <context:component-scan base-package="com.xqlee.springmvc.controller" />    <!-- 注解驱动 -->    <mvc:annotation-driven />    <mvc:default-servlet-handler />    <!-- 资源管理不拦截 -->    <mvc:resources location="/resources/" mapping="/resources/**" />    <mvc:resources location="/upload/" mapping="/upload/**" />      <!-- 内部资源视图解析器 prefix + logicName + suffix /WEB-INF/jsps/ + index + .jsp -->    <bean id="internalResourceViewResolver"       class="org.springframework.web.servlet.view.InternalResourceViewResolver">       <!-- 前缀 -->       <property name="prefix" value="/WEB-INF/pages/" />       <!-- 后缀 -->       <property name="suffix" value="" />    </bean>      <!-- 处理在controller中使用注解@ResponseBody标签返回JSON数据 Start -->    <!-- 注意[由于我在pom.xml引入的是2.4.1版本]:所以class=org.springframework.http.converter.json.MappingJackson2HttpMessageConverter -->    <!-- [如果pom.xml引入的是1.xx版本]class=org.springframework.http.converter.json.MappingJacksonHttpMessageConverter -->    <bean id="mappingJackson2HttpMessageConverter"    class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">       <property name="supportedMediaTypes">          <list>             <value>text/html;charset=UTF-8</value>             <value>text/json;charset=UTF-8</value>             <value>application/json;charset=UTF-8</value>          </list>       </property>    </bean>    <bean    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">       <property name="messageConverters">          <list>             <ref bean="mappingJackson2HttpMessageConverter" />          </list>       </property>    </bean>    <!-- JSON数据处理 End -->      <!-- 上传图片/文件需要配置 -->    <bean id="multipartResolver"       class="org.springframework.web.multipart.commons.CommonsMultipartResolver">       <property name="maxUploadSize" value="-1" /><!-- -1表示没有限制 -->       <property name="maxInMemorySize" value="4096" />    </bean>   </beans></code></pre>   <p>2.6spring-beans.xml</p> <pre> <code class="language-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:mvc="http://www.springframework.org/schema/mvc"    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: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.1.xsd             http://www.springframework.org/schema/mvc             http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd               http://www.springframework.org/schema/aop             http://www.springframework.org/schema/aop/spring-aop-4.1.xsd             http://www.springframework.org/schema/context             http://www.springframework.org/schema/context/spring-context-4.1.xsd             http://www.springframework.org/schema/tx             http://www.springframework.org/schema/tx/spring-tx-4.1.xsd             http://www.springframework.org/schema/data/jpa             http://www.springframework.org/schema/data/jpa/spring-jpa.xsd ">    <context:annotation-config />    <!-- 启动自动扫描该包下所有的注解(如@controller) 一般扫描service,entity,dao,controller由springMVC扫描 -->    <context:component-scan       base-package="com.xqlee.springmvc.service,com.xqlee.springmvc.entity,com.xqlee.springmvc.dao" /> </beans></code></pre>   <p>2.7 Log4j配置文件</p> <pre> <code>#defind the rooeLogger ,the rootlogger min level is INFO,and two way to output log log4j.rootLogger = INFO,FILE,CONSOLE,DATABASE   #---------------------------------------------------------------------- #defind the FILE as file everyday                                     | #---------------------------------------------------------------------- #log4j.appender.FILE = org.apache.log4j.DailyRollingFileAppender   #the log min level set as INFO #log4j.appender.FILE.Threshold=INFO   #log file encoding set UTF-8 #log4j.appender.FILE.encoding=UTF-8   #log file path #log4j.appender.FILE.File=/home/tomcat/log/springmvc4/springmvc4   #log file name append #log4j.appender.FILE.DatePattern='_'yyyy-MM-dd'.log'   #Immediate write the log is true #log4j.appender.FILE.ImmediateFlush=true   #the layout of the log #log4j.appender.FILE.layout=org.apache.log4j.PatternLayout   #the detail layout of log  in the log file #log4j.appender.FILE.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} springmvc4 %-5p [%c:%L] | %m%n   #------------------------------------------------------------------------- #this use the 'org.apache.log4j.ConsoleAppender' to output in the Console| #------------------------------------------------------------------------- log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender   #output min level is INFO log4j.appender.Threshold=INFO   #the output target is Console log4j.appender.CONSOLE.Target=System.out   #the layout of the log log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} springmvc4 %-5p | %m%n   #---------------------------------------------------------------------------- #insert the log into database                                               | #---------------------------------------------------------------------------- #log4j.appender.DATABASE=org.apache.log4j.jdbc.JDBCAppender #The jdbc url #log4j.appender.DATABASE.URL=jdbc:mysql://localhost:3306/springmvc4 #The jdbc driver #log4j.appender.DATABASE.driver=com.mysql.jdbc.Driver #DB user #log4j.appender.DATABASE.user=root #DB password #log4j.appender.DATABASE.password=root #sql #log4j.appender.DATABASE.sql=INSERT INTO zhl_log (operationTime,logLevel,logClass,logDetail)  VALUES ("%d{yyyy-MM-dd HH:mm:ss}", "%-5p","%F:%L", "%m") #layout #log4j.appender.DATABASE.layout=org.apache.log4j.PatternLayout #layout detail #log4j.appender.DATABASE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n</code></pre>   <p>2.8测试vo</p> <pre> <code class="language-java">package com.xqlee.springmvc.vo;   /**  *  *  * <pre>  * @功能说明 [测试bean]  * @其他说明 [暂无]  * @文件编码 [UTF-8]  * @所属包名 [com.xqlee.springmvc.vo]  * @项目名称 [cdws]  * @创建日期 []  * @创建人员 [lxq]  * @最后修改 []  * @修改说明 [暂无更新]  * @修改人员 [lxq]  * @公司组织 [org]  * @版本说明 [v 1.0]  *  * </pre>  */ public class User {      private String id;    private String name;    private String num;      public User(String id, String name, String num) {       this.id = id;       this.name = name;       this.num = num;    }      public String getId() {       return id;    }      public void setId(String id) {       this.id = id;    }      public String getName() {       return name;    }      public void setName(String name) {       this.name = name;    }      public String getNum() {       return num;    }      public void setNum(String num) {       this.num = num;    }   }</code></pre>   <p>2.9测试controller</p> <pre> <code class="language-java">package com.xqlee.springmvc.controller;   import java.util.Vector;   import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;   import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping;   import com.xqlee.springmvc.vo.User;   /**  *  *  * <pre>  * &#64;功能说明 [测试类]  * &#64;其他说明 [暂无]  * &#64;文件编码 [UTF-8]  * &#64;所属包名 [com.xqlee.springmvc.controller]  * &#64;项目名称 [cdws]  * &#64;创建日期 []  * &#64;创建人员 [lxq]  * &#64;最后修改 []  * &#64;修改说明 [暂无更新]  * &#64;修改人员 [lxq]  * &#64;公司组织 [org]  * &#64;版本说明 [v 1.0]  *  * </pre>  */ @Controller(value = "/beanTestController.do") public class TestController {    /** 日志 **/    private static final Log log = LogFactory.getLog(TestController.class);      @RequestMapping(params = "method=Vector")    // @ResponseBody    public Object testVector(HttpServletRequest request, HttpServletResponse response) {       // 创建容器       Vector<User> vtb = new Vector<User>();       User tb;       for (int i = 0; i <= 5; i++) {          tb = new User("ID-" + i, "小Name-" + i, "李Num-" + i);          vtb.add(tb);       }       request.setAttribute("vtb", vtb);       log.info("即将跳转.....");       return "../../vector.jsp";    } }</code></pre>   <p>2.10 index.jsp</p> <pre> <code class="language-html"><!DOCTYPE> <html> <body>    <h2>Hello World!</h2>    <a href="beanTestController.do?method=Vector">Vector Test</a> </body> </html></code></pre>   <p>2.11 vector.jsp</p> <pre> <code class="language-html"><%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE> <html> <body>    <table border='1'>       <thead>          <tr>             <td>ID</td>             <td>Name</td>             <td>Num</td>          </tr>       </thead>       <tbody>          <c:forEach items="${vtb}" var="Object">             <tr>                 <td>${Object.id}</td>                 <td>${Object.name}</td>                 <td>${Object.num}</td>             </tr>          </c:forEach>       </tbody>    </table>     </body> </html></code></pre>   <p>2.12运行结果</p> <img alt="3" src="/resources/assist/images/blog/d439127f-c160-4faa-a47b-1f3118f87ba5.png" style="height:213px; width:422px" /><br /> <img alt="4" src="/resources/assist/images/blog/46005b58-d05f-4bab-b517-11ed209014c9.png" style="height:486px; width:611px" /><br />  
  • springmvc集成logback不打印spring mvc启动日志解决

    springmvc集成logback不打印spring mvc启动日志解决<strong>问题:</strong><br />     springmvc集成logback不打印spring mvc启动日志<br /> <br /> <strong>Logback简介</strong><br />     Logback是在log4j基础上重写了内部的实现,在某些特定的场景上面,甚至可以比之前的速度快上10倍。在保证logback的组件更加快速的同时,同时所需的内存更加少。所以logback是一个不错的选择,当然你也可以选择其他的日志组件。<br /> <br /> <strong>1.为了使logback能打印Spring的日志这里需要添加几个依赖,默认logback是不会打印Spring的日志</strong> <pre> <code class="language-xml"> <!-- https://mvnrepository.com/artifact/org.logback-extensions/logback-ext-spring --> <dependency> <groupId>org.logback-extensions</groupId> <artifactId>logback-ext-spring</artifactId> <version>0.1.4</version> </dependency> <!-- https://mvnrepository.com/artifact/org.slf4j/jcl-over-slf4j --> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>1.7.25</version> </dependency></code></pre> <strong>2.再次启动即可</strong><br /> <img alt="spring mvc启动日志" class="img-thumbnail" src="/resources/assist/images/blog/6174d1be296f43c3b87d5094858d4641.png" />
  • Servlet 4.0 新特性

    Servlet 4.0 新特性,Java EE的下一个版本将是版本8,当它最终发布时,我们将在现有的API中看到一些非常有趣的改进。其中一项改进是将HTTP / 2应用于Servlet技术。<h2>前言</h2> <blockquote> <p>Java EE的下一个版本将是版本8,当它最终发布时,我们将在现有的API中看到一些非常有趣的改进。其中一项改进是将HTTP / 2应用于Servlet技术。</p> </blockquote> <h2 style="margin-left:0px; margin-right:0px; text-align:start">适当的抽象</h2> Servlet API已经很好地支持HTTP / 2优化,并允许框架利用服务器推送。 <h3 style="margin-left:0px; margin-right:0px; text-align:start"><br /> Servlet如何展示HTTP / 2特点?</h3> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="font-family:"Noto Sans",sans-serif"><span style="color:#000000"><span style="background-color:#ffffff">Servlet是RFC的正确抽象。您不希望编程帧和流,因此隐藏网络层的高级API会很好。在Servlets层,你可以做服务器推出没有做低层次的东西。</span></span></span></p> <h3 style="margin-left:0px; margin-right:0px; text-align:start"><br /> 一个请求和多个响应</h3> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="font-family:"Noto Sans",sans-serif"><span style="color:#000000"><span style="background-color:#ffffff">Servlet API中的一个变化是在HTTP 1中我们有一个请求和一个响应。在HTTP/2中,这不再是唯一。可以有一个请求,服务器可能决定推送多个资源,然后最终以最初请求的页面进行响应。您同时有一个请求和多个响应,这对Servlet API来说是一个挑战。</span></span></span><br />  </p> <h2 style="margin-left:0px; margin-right:0px; text-align:start">服务器推送</h2> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="font-family:"Noto Sans",sans-serif"><span style="color:#000000"><span style="background-color:#ffffff">服务器推送是HTTP/2中出现在servlet API中的许多改进中最明显的部分。HTTP/2中的所有新功能(包括服务器推送)都旨在提高Web浏览体验的感知性能。</span></span></span></p> <p style="margin-left:0px; margin-right:0px; text-align:start"> </p> <h3 style="margin-left:0px; margin-right:0px; text-align:start">改进了浏览器感知的性能</h3> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="font-family:"Noto Sans",sans-serif"><span style="color:#000000"><span style="background-color:#ffffff">启用服务器推送可提高浏览器的性能,因为服务器比客户更能了解请求可能要求的附加资产(如图像,样式表和JavaScript)。</span></span></span></p> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="font-family:"Noto Sans",sans-serif"><span style="color:#000000"><span style="background-color:#ffffff">例如,服务器可以知道,无论何时浏览器请求index.html页面,它都会请求标识图像,样式表和菜单JavaScript等。由于服务器知道这一点,他们可以先发制人地开始发送这些资产处理index.html。</span></span></span><br />  </p> <h3 style="margin-left:0px; margin-right:0px; text-align:start">不是Web Sockets的替代品</h3> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="font-family:"Noto Sans",sans-serif"><span style="color:#000000"><span style="background-color:#ffffff">它只是允许你填充浏览器缓存。预计构建在像JSF这样的Servlet上的框架将使用这个框架,并且我们使用push builder API来解决这个问题。</span></span></span></p> <h2 style="margin-left:0px; margin-right:0px; text-align:start">典型的流程</h2> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="font-family:"Noto Sans",sans-serif"><span style="color:#000000"><span style="background-color:#ffffff">浏览器请求索引页面。服务器会注意到它需要<em><strong>style_1.css</strong></em>和<em><strong>javaScript_1.js</strong></em>  文件,所以我们从HTTP请求中获取<em><strong>PushBuilder</strong></em>,并将路径设置为<em><strong>style_1.css</strong></em>文件并调用push,然后将路径设置为<em><strong>javaScript_1。 js</strong></em>文件并再次调用推送。</span></span></span></p> <img alt="http2执行流程" class="img-thumbnail" src="/resources/assist/images/blog/a3f0a7423df24f4a8823dc13df1e3c60.png" /><br /> 注意在这种情况下,CSS和JavaScript将首先返回到客户端,然后index页面返回。 <h3 style="margin-left:0px; margin-right:0px; text-align:start">从HTTP请求推送生成器</h3> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="font-family:"Noto Sans",sans-serif"><span style="color:#000000"><span style="background-color:#ffffff">只需从HTTP Request对象中获取推式生成器,并将路径设置为资源并推送即可。</span></span></span></p> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="font-family:"Noto Sans",sans-serif"><span style="color:#000000"><span style="background-color:#ffffff">在这个序列图中有两件事要注意,</span></span></span></p> <ul> <li>推构建器可以重用。在示例中,我使用推式构建器将两个资源推送到CSS文件和JavaScript文件。</li> <li>第二件事是index.html在推送资源后返回浏览器。</li> </ul> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="font-family:"Noto Sans",sans-serif"><span style="color:#000000"><span style="background-color:#ffffff">原因是,如果索引在推送资源之前返回,浏览器将分析它并看到它需要这两个资源。<strong>它会查看缓存并查看它没有这些资源,它会请求它们。</strong>此时,浏览器缓存将不会预填充。所以推送的资源必须在索引发送之前先返回。</span></span></span></p> <h3 style="margin-left:0px; margin-right:0px; text-align:start"><br /> 推送答应</h3> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="font-family:"Noto Sans",sans-serif"><span style="color:#000000"><span style="background-color:#ffffff">前面提到的其中一种框架类型是  <em><strong>RST_STREAM,</strong> </em>这就是客户如何拒绝推送承诺。因此,如果服务器推送一个资源,并且浏览器已经将其存储在缓存中,那么不是让服务器发送文件,而是发送一个<em><strong>RST_STREAM</strong> </em>帧,表明它已经有文件文件,因此不发送它。</span></span></span><br />  </p> <h2 style="margin-left:0px; margin-right:0px; text-align:start">PushBuilder</h2> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="font-family:"Noto Sans",sans-serif"><span style="color:#000000"><span style="background-color:#ffffff">要使用服务器推送,从<strong><em>HttpServletRequest</em></strong>获取对<strong><em>PushBuilder</em> </strong>的引用,根据需要改变生成器,然后调用  <em><strong>push()</strong></em>  方法。</span></span></span></p> <pre> <code class="language-java">PubshBuilder pubshBuilder= request.getPubshBuilder();</code></pre> <p style="margin-left:0px; margin-right:0px; text-align:start">这会根据从中获取此构建器的<strong><em>HttpServletRequest</em></strong>构建推送请求<br /> <img alt="获取推送构建起" class="img-thumbnail" src="/resources/assist/images/blog/397a5f47e3eb4e9abfebaec671c468cb.png" /><br />  </p> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="font-family:"Noto Sans",sans-serif"><span style="color:#000000"><span style="background-color:#ffffff">这会根据从中获取此构建器的<em><strong>HttpServletRequest</strong></em>生成推送请求。</span></span></span></p> <h3 style="margin-left:0px; margin-right:0px; text-align:start">javax.servlet.http.PushBuilder类</h3> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="font-family:"Noto Sans",sans-serif"><span style="color:#000000"><span style="background-color:#ffffff">推送请求由请求方法设置为<em><strong>GET</strong></em> 构建<em><strong>。</strong></em><strong><em>有条件,</em> <em>范围,</em> <em>期望,</em> <em>授权</em></strong>和<strong><em>请求</em></strong>标题被删除。只有在<strong><em>maxAge</em></strong>未过期的情况下才会添加Cookie 。请求标头将被设置为请求URL和存在的任何查询字符串。如果  <em><strong>If-Modified-Since</strong></em>  或  <em><strong>If-None-Match</strong></em>  中的任何一个出现,则  <em><strong>isConditional()</strong></em>  将被设置为true。</span></span></span></p> <h3 style="margin-left:0px; margin-right:0px; text-align:start">只有URI路径必需</h3> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="font-family:"Noto Sans",sans-serif"><span style="color:#000000"><span style="background-color:#ffffff">唯一需要的设置是要用于推送请求的URI路径。这必须在每次调用<em><strong>push()</strong></em>之前调用  。如果路径包含查询字符串,则查询字符串将附加到现有查询字符串(如果有),并且不会发生重复数据删除。</span></span></span></p> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="font-family:"Noto Sans",sans-serif"><span style="color:#000000"><span style="background-color:#ffffff">以'/'开头的路径被视为绝对路径。所有其他路径都视为相对于用于创建此构建器实例的请求的上下文路径。该路径可能包含查询字符串。</span></span></span></p> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="font-family:"Noto Sans",sans-serif"><span style="color:#000000"><span style="background-color:#ffffff">通过 在<em><strong>pushBuilder</strong></em>实例上调用<em><strong>push()</strong></em>方法来<em><strong>推送</strong></em>资源  。</span></span></span></p> <pre> <code class="language-java">@WebServlet("/WelcomeServlet") public class WelcomeServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{ if(request.getRequestURI.equals("/index.html")&&reqeust.isPubshSupported()){ request.getPushBuilder().path("/images/logo.jpg").push(); } } }</code></pre> <h3 style="margin-left:0px; margin-right:0px; text-align:start">过滤器和服务器推送</h3> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="font-family:"Noto Sans",sans-serif"><span style="color:#000000"><span style="background-color:#ffffff">解决这个问题的另一种方法是在过滤器中实现服务器推送。Jetty  在  <em><strong>org.eclipse.jetty.servlets</strong></em>  包中有一个  <em><strong>PushCacheFilter</strong></em>。</span></span></span></p> <pre> <code class="language-java">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.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import org.apache.catalina.servlet4preview.http.PushBuilder; @WebFilter(urlPatterns="/*") public class PushFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpServletRequest=(HttpServletRequest)request; String uri=httpServletRequest.getRequestURI(); switch (uri) { case "/index.html": PushBuilder pushBuilder=httpServletRequest.getPushBuilder(); pushBuilder.path("/styles.css").push(); pushBuilder.path("/logo.png").push(); break; default: break; } chain.doFilter(request, response);; } @Override public void destroy() { } } </code></pre> <h3 style="margin-left:0px; margin-right:0px; text-align:start">JSF用例</h3> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="font-family:"Noto Sans",sans-serif"><span style="color:#000000"><span style="background-color:#ffffff">框架案例是服务器推送最重要的用例之一。它完全依赖于服务器事先知道客户在客户请求之前要求的资源。服务器端Web框架可以充分利用服务器推送的优势。</span></span></span></p> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="font-family:"Noto Sans",sans-serif"><span style="color:#000000"><span style="background-color:#ffffff">所以JSF可以很容易地使用服务器推送。所以每当JSF要呈现样式表时,例如,它将调用<em><strong>encodeResourceURL</strong></em>方法,这是入口点,在这里我们可以初始化服务器推送的调用。</span></span></span></p> <pre> <code class="language-java">import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ExternalContextImp extends ExternalContext{ @Override public String encodeResourceURL(String url) { //... ((HttpServletRequest)request).getPushBuilder().path(url).push(); //... return ((HttpServletResponse)response).encodeURL(url); } } </code></pre> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="font-family:"Noto Sans",sans-serif"><span style="color:#000000"><span style="background-color:#ffffff">这就是Web框架的工作原理,就像JSF将能够利用服务器推送修改一样。这还没有实现,我们将看看他们是如何决定这么做的,或者他们是否想出了另一种方法。</span></span></span></p> <h3 style="margin-left:0px; margin-right:0px; text-align:start">禁用/拒绝服务器推送</h3> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="font-family:"Noto Sans",sans-serif"><span style="color:#000000"><span style="background-color:#ffffff">客户端可以通过发送<em><strong>SETTINGS_ENABLE_PUSH</strong></em>设置值0(零)来显式禁用服务器推送。</span></span></span></p> <p style="margin-left:0px; margin-right:0px; text-align:start"><span style="font-family:"Noto Sans",sans-serif"><span style="color:#000000"><span style="background-color:#ffffff">除了允许客户端使用<em><strong>SETTINGS_ENABLE_PUSH</strong></em>设置禁用服务器推送之外,servlet容器还必须尊重客户端的请求,以便不通过引用推送流的流标识符的<em><strong>CANCEL</strong></em>或<em><strong>REFUSED_STREAM</strong></em>代码在更细粒度的基础上接收推送的响应。这种交互的一个常见用途是浏览器在其缓存中已有资源时。</span></span></span></p> <p style="margin-left:0px; margin-right:0px; text-align:start"> </p>
  • Java编程中spring boot项目获取spring容器applicationContext

    Java编程中spring boot项目如何获取spring容器applicationContextJava编程中spring boot项目如何获取spring容器applicationContext<br /> <br /> 代码如下: <pre> <code class="language-java">package com.example; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; /** * * <pre> * [Summary] * spring boot项目中获取spring容器applicationContext * [Detail] * TODO * [Author] * Leftso * [Version] * v1.0 * 2017年3月18日下午6:10:13 * </pre> */ @Component public class SpringUtils implements ApplicationContextAware { Logger log=LoggerFactory.getLogger(SpringUtils.class); public static ApplicationContext applicationContext = null; @Override public void setApplicationContext(ApplicationContext arg0) throws BeansException { if (SpringUtils.applicationContext == null) { SpringUtils.applicationContext = arg0; } log.info("Spring 容器对象:"+applicationContext); } /** * @return the applicationContext */ public static ApplicationContext getApplicationContext() { return applicationContext; } } </code></pre> 启动项目,注意观察日志:<br /> <img alt="容器对象实例" class="img-thumbnail" src="/resources/assist/images/blog/63f2fb42-8dca-4f21-b16f-e644f9b12283.jpg" /><br /> 上图可以看出容器对象已经在,在需要获得容器的地方注解如该类,就可以通过get方法随时获取spring的applicationcontext容器进行其他操作