该项目基于Maven开发,该项目中包含了MyBatis自动创建表的功能,具体实现查阅MyBatis---自动创建表
配置
maven支持pom.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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.xiaobaizhiqian</groupId> <artifactId>SpringMVCMyBatis</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <properties> <springside.version>4.2.2.GA</springside.version> <spring.version>4.0.5.RELEASE</spring.version> <mybatis.version>3.2.5</mybatis.version> <mybatis-spring.version>1.2.2</mybatis-spring.version> <logback.version>1.1.1</logback.version> <tomcat-jdbc.version>7.0.52</tomcat-jdbc.version> <jackson.version>2.3.1</jackson.version> <!-- Plugin的属性定义 --> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.7</java.version> <jdbc.driver.groupId>mysql</jdbc.driver.groupId> <jdbc.driver.artifactId>mysql-connector-java</jdbc.driver.artifactId> <jdbc.driver.version>5.1.22</jdbc.driver.version> </properties> <dependencies> <dependency> <groupId>com.gitee.sunchenbin.mybatis.actable</groupId> <artifactId>mybatis-enhance-actable</artifactId> <version>1.0.1</version> </dependency> <!-- JSON begin --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.module</groupId> <artifactId>jackson-module-jaxb-annotations</artifactId> <version>${jackson.version}</version> </dependency> <!-- JSON end --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>${logback.version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</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-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis-spring.version}</version> </dependency> <!-- connection pool --> <dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-jdbc</artifactId> <version>${tomcat-jdbc.version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>${jdbc.driver.groupId}</groupId> <artifactId>${jdbc.driver.artifactId}</artifactId> <version>${jdbc.driver.version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.41</version> </dependency> <dependency> <groupId>javax.activation</groupId> <artifactId>activation</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.3.2</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.1</version> </dependency> <dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.7.3</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.8</version> </dependency> <dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>javax.servlet.jsp.jstl-api</artifactId> <version>1.2.1</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> </dependencies> <build> <plugins> <!-- compiler插件, 设定JDK版本 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> <showWarnings>true</showWarnings> </configuration> </plugin> <!-- war打包插件, 设定war包名称不带版本号 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.4</version> <configuration> <warName>${project.artifactId}</warName> </configuration> </plugin> </plugins> </build> <repositories> <repository> <id>spring-snapshots</id> <name>Spring Snapshots</name> <url>http://repo.spring.io/snapshot</url> <snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories> </project>
web.xml配置
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:jsp="http://java.sun.com/xml/ns/javaee/jsp" 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></display-name> <!-- spring框架必须定义ContextLoaderListener,在启动Web容器时,自动装配Spring applicationContext.xml的配置信息 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <!-- 指定Spring上下文配置文件 --> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config/applicationContext.xml</param-value> </context-param> <context-param> <param-name>spring.profiles.active</param-name> <param-value>production</param-value> </context-param> <servlet> <servlet-name>Dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <!-- 指定SpringMVC配置文件 --> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config/springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <!-- 指定请求的后缀,可以随意写,如*.html作为请求后缀,这里拦截所有的请求 --> <servlet-name>Dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 编码格式为UTF-8 --> <filter> <filter-name>encodingFilter</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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app>
我这里将除pom、web之外的所有的配置文件均放在resources资源文件中。设置resources方法:在src/main/java文件夹下创建resources文件夹,右击文件夹,选择Build Path,选择use as Source Folder即可
项目中,我将applicationContext.xml、config.properties、logback.xml、springmvc.xml等项目支持配置文件放在config文件夹中;将与MyBatis相关的配置文件放在mybatisConfig文件夹中
项目支持配置文件config文件夹
springmvc.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- spring可以自动去扫描base-package下面或者子包下面的java文件, 如果扫描到有@Component @Controller @Service @Repository等这些注解的类,则把这些类注册为bean --> <context:component-scan base-package="com.xiaobaizhiqian.SpringMVCMyBatis.*" /> <!-- 模型解析,在请求时为模型视图名称添加前后缀 比如在controller类中需要请求/WEB-INF/page/index.jsp文件,直接写index就可以了 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/page/" p:suffix=".jsp" /> <!-- 在请求时为模型视图名称添加前后缀的另一种方法 <bean id="internalResourceViewResolover" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/page/" /> <property name="suffix" value=".jsp" /> </bean> --> </beans>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task" 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/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd"> <description>Spring公共配置</description> <!-- 开启定时任务 --> <task:annotation-driven/> <!-- 引入属性文件 --> <context:property-placeholder location="classpath:config/config.properties,classpath:mybatisConfig/jdbc.properties" /> <!-- 扫描底层注入 --> <context:component-scan base-package="com.gitee.sunchenbin.mybatis.actable.manager.*" /> <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="locations"> <list> <value>classpath*:mybatisConfig/autoCreateTable.properties</value> </list> </property> </bean> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer"> <property name="properties" ref="configProperties" /> </bean> <!-- MyBatis配置 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 显式指定Mapper文件位置 --> <property name="mapperLocations"> <array> <value>classpath*:com/xiaobaizhiqian/SpringMVCMyBatis/mybatisMapper/*Mapper.xml</value> <value>classpath*:com/gitee/sunchenbin/mybatis/actable/mapping/*/*.xml</value> </array> </property> <!-- mybatis配置文件路径 --> <property name="configLocation" value="classpath:/mybatisConfig/config.xml"/> </bean> <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory" /> <!-- 这个执行器会批量执行更新语句, 还有SIMPLE 和 REUSE --> <constructor-arg index="1" value="BATCH" /> </bean> <!-- 扫描basePackage接口 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 映射器接口文件的包路径, --> <property name="basePackage" value="com.xiaobaizhiqian.SpringMVCMyBatis.dao;com.gitee.sunchenbin.mybatis.actable.dao.*" /> </bean> <!-- 使用annotation定义事务 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" /> <!-- 数据源配置, 使用Tomcat JDBC连接池 --> <bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource" destroy-method="close"> <!-- Connection Info --> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- Connection Pooling Info --> <property name="maxActive" value="${jdbc.pool.maxActive}" /> <property name="maxIdle" value="${jdbc.pool.maxIdle}" /> <property name="minIdle" value="0" /> <property name="defaultAutoCommit" value="false" /> </bean> </beans>
config.properties这个配置文件暂时没有使用到,即配置文件中没有内容
logback.xml
<?xml version="1.0" encoding="UTF-8" ?> <configuration> <appender name="console" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>%date{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <!-- 时间滚动输出 level为 DEBUG 日志 --> <appender name="file-debug" class="ch.qos.logback.core.rolling.RollingFileAppender"> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>DEBUG</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY </onMismatch> </filter> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <FileNamePattern>/export/data/logs/debug.%d{yyyy-MM-dd}.log</FileNamePattern> <MaxHistory>30</MaxHistory> </rollingPolicy> <encoder> <pattern>%date{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <!-- 时间滚动输出 level为 INFO 日志 --> <appender name="file-info" class="ch.qos.logback.core.rolling.RollingFileAppender"> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>INFO</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY </onMismatch> </filter> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <FileNamePattern>/export/data/logs/info.%d{yyyy-MM-dd}.log</FileNamePattern> <MaxHistory>30</MaxHistory> </rollingPolicy> <encoder> <pattern>%date{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <!-- 时间滚动输出 level为 INFO 日志 --> <appender name="file-error" class="ch.qos.logback.core.rolling.RollingFileAppender"> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>ERROR</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY </onMismatch> </filter> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <FileNamePattern>/export/data/logs/error.%d{yyyy-MM-dd}.log</FileNamePattern> <MaxHistory>30</MaxHistory> </rollingPolicy> <encoder> <pattern>%date{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <!-- 很多人使用Mybatis的时候,控制台不能输出SQL语句,造成调试困难。只需要让DAO层的日志级别调整为DEBUG就可以了 --> <logger name="com.jikexueyuan.dao" level="DEBUG" /> <!-- 指定项目可输出的最低级别日志 --> <root level="INFO"> <appender-ref ref="console" /> <appender-ref ref="file-debug" /> <appender-ref ref="file-info" /> <appender-ref ref="file-error" /> </root> </configuration>
MyBatis相关的配置文件mybatisConfig文件夹
config.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <setting name="cacheEnabled" value="true" /> </settings> </configuration>
autoCreateTable.properties
#
mybatis.table.auto=update
#
mybatis.model.pack=com.xiaobaizhiqian.SpringMVCMyBatis.entity
mybatis.database.type=mysql
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://127.0.0.1:3306/dbName?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&allowMultiQueries=true jdbc.username=root jdbc.password=root #connection pool settings # maxIdle是最大的空闲连接数,这里取值为20,表示即使没有数据库连接时依然可以保持20个空闲的连接,它们不会被清除,随时处于待命状态 jdbc.pool.maxIdle=20 # maxActive是最大激活连接数,这里取值为190,表示同时最多有190个数据库连接 jdbc.pool.maxActive=190
代码
我将界面WEB-INF/page/都放置在WEB-INF文件夹下,这样外部便无法直接访问jsp文件
index.jsp
<%@page import="com.xiaobaizhiqian.SpringMVCMyBatis.common.PageParam"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <% request.setAttribute("domain", "http://localhost:8080/SpringMVCMyBatis/"); %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>代理IP提取系统</title> </head> <body> <!-- head --> <div id="page-header" class="wrap header"> <header id="masthead" class="site-header" role="banner"> <div class="hgroup"> <h1 class="site-title"> <a class="home-link" href="${domain }" title="代理IP提取系统" rel="home">代理IP提取系统</a> </h1> <h2 class="site-description" id="site-description">最便宜、最稳定、实时更新、API接口、实用软件</h2> </div> <div class="clear"></div> </header> </div> <!-- menu --> <div id="primary-nav"> <div class="wrap nav"> <nav id="site-navigation" class="main-navigation" role="navigation"> <h3 class="menu-toggle">Menu</h3> <a class="assistive-text" href="#content" title="Skip to content">Skip to content</a> <ul class="nav-menu"> <li id="menu_index" class="menu-item menu-item-type-custom menu-item-object-custom current-menu-item"> <a href="${domain }">首页</a> </li> <li id="menu_api" class="menu-item menu-item-type-taxonomy menu-item-object-custom "> <a href="${domain }fetch.html">API接口</a> </li> <li id="menu_help" class="menu-item menu-item-type-taxonomy menu-item-object-custom"> <a href="${domain }help.html">帮助中心</a> </li> <li style="margin-right: 10px;" class="menu-item menu-item-type-taxonomy menu-item-object-custom right">
<i class="qq-icon" style="cursor: pointer;" onclick="window.open('http://jq.qq.com/?_wv=1027&k=VFVEFs','_blank')"></i>
QQ群:66782959
</li> </ul> </nav> </div> </div> <!-- body --> <div class="wrap fullwidth"> <div id="content" style=" auto;"> <div id="post-2" class="post-2 page type-page status-publish hentry"> <div class="entry entry-content"> <blockquote style="font-style:normal;"> <p><b style="font-size: 14px;">你们的代理IP是怎么获取到的?</b></p> <p>① 全网代理IP使用5台4核ECS服务器,运行分布式IP与端口扫描系统,每天扫描IP量几十万条。</p> <p>② 我们不间断的运行着IP验证系统,精确地检测每一个代理IP的匿名度、响应时间、数据传输速度、地域、运营商,每秒钟都在验证,保证网站的IP都是高度可用的。</p> <p>③ 我们提供了极其丰富的代理筛选和API接口,每次提取的IP不相同,只为更便捷地提取、更便捷的开发。</p> </blockquote> </div> <div class="clear"></div> <div class="entry entry-content"> <div class="entry-title">最新100个可用免费高速HTTP代理IP</div> <div id="list"> <table class="table"> <thead> <tr> <th>IP</th> <th>PORT</th> <th>国家</th> <th>省市</th> <th>运营商</th> <th>录入时间</th> </tr> </thead> <tbody> <c:forEach items="${pageParam.data }" var="item"> <tr> <td>${item.ip }</td> <td>${item.port }</td> <td>${item.country }</td> <td>${item.province } ${item.city }</td> <td>${item.isp }</td> <td>${item.findTime }</td> </tr> </c:forEach> </tbody> </table> <p class="message">注:表中响应速度是中国测速服务器的测试数据,仅供参考。响应速度根据你机器所在的地理位置不同而有差异。</p> <div class="wp-pagenavi"> <span>第</span> <% PageParam pageParam = (PageParam)request.getAttribute("pageParam"); int currPage = pageParam.getCurrPage(); int totalPage = pageParam.getTotalPage(); for(int i = 1; i <= totalPage; i ++){ if(i == currPage){ %><span class="current"><%=currPage %></span><% }else{ %><a href="index.html?page=<%=i %>"><%=i %></a><% } } %> <span>页</span> </div> </div> </div> </div> </div> <div class="clear"></div> <div id="footer"> <div class="copyright"> <span class="footerleft">友情链接: <a href="http://www.qiaodm.com/" target="_blank" title="敲代码,IT技术任你学">敲代码</a> <a href="http://ip.qiaodm.com/" target="_blank" title="敲代码免费代理IP">敲代码免费代理IP</a> <a href="http://proxy.goubanjia.com/" target="_blank" title="敲代码免费代理IP">全网代理IP</a> <a href="http://wantsee.cn" target="_blank" title="">想看就看</a> <a href="http://www.66ip.cn/index.html" target="_blank" title="">66代理</a> </span> <div class="clear"></div> </div> <div class="copyright" style="display: none;"> <span class="footerleft">Copyright © 2015</span> <span class="footerright">All rights reserved</span> <div class="clear"></div> </div> </div> </div> </body> </html>
fetch.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% request.setAttribute("domain", "http://localhost:8080/SpringMVCMyBatis/"); %> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>代理IP提取系统 帮助中心</title> </head> <body> <!-- head --> <div id="page-header" class="wrap header"> <header id="masthead" class="site-header" role="banner"> <div class="hgroup"> <h1 class="site-title"> <a class="home-link" href="${domain }" title="代理IP提取系统" rel="home">代理IP提取系统</a> </h1> <h2 class="site-description" id="site-description">最便宜、最稳定、实时更新、API接口、实用软件</h2> </div> <div class="clear"></div> </header> </div> <!-- menu --> <div id="primary-nav"> <div class="wrap nav"> <nav id="site-navigation" class="main-navigation" role="navigation"> <h3 class="menu-toggle">Menu</h3> <a class="assistive-text" href="#content" title="Skip to content">Skip to content</a> <ul class="nav-menu"> <li id="menu_index" class="menu-item menu-item-type-custom menu-item-object-custom"> <a href="${domain }">首页</a> </li> <li id="menu_api" class="menu-item menu-item-type-taxonomy menu-item-object-custom current-menu-item"> <a href="${domain }fetch.html">API接口</a> </li> <li id="menu_help" class="menu-item menu-item-type-taxonomy menu-item-object-custom "> <a href="${domain }help.html">帮助中心</a> </li> <li style="margin-right: 10px;" class="menu-item menu-item-type-taxonomy menu-item-object-custom right"><i class="qq-icon" style="cursor: pointer;" onclick="window.open('http://jq.qq.com/?_wv=1027&k=VFVEFs','_blank')"></i>QQ群:66782959 </li> </ul> </nav> </div> </div> <!-- body --> <div class="wrap fullwidth"> <div id="content" style=" auto;"> <div id="breadcrumbs"> <a href="${domain }">首页</a>»» 生成API提取接口 </div> <div id="post-2" class="post-2 page type-page status-publish hentry"> <div class="entry entry-content"> <form id="fetchForm" class="largeinput" accept-charset="UTF-8" method="POST" target="_blank" action="${domain }get.html"> <div class="control-group"> <label class="control-label" for="name">提取数量</label> <div class="controls"> <input id="num" type="text" name="num" class="span4 required" value="100" placeholder="填入数字,一次做多提取10000个"> <span class="star">* </span><a href="${domain }help/" target="_blank">数量该怎么填?</a> </div> </div> <div class="control-group"> <label class="control-label" for="name">所在国家</label> <div class="controls"> <input id="num" type="text" name="country" class="span4 required" value="" placeholder="国家,比如中国"> </div> </div> <div class="control-group"> <label class="control-label" for="name">IP运营商</label> <div class="controls"> <select name="isp"> <option value="">不限</option> <option value="电信">电信</option> <option value="联通">联通</option> <option value="移动">移动</option> <option value="网通">网通</option> </select> </div> </div> <div class="submit" style="margin-top: 22px;"> <span class="smallbutton"><a id="postcontent" href="javascript:fetchForm.submit();">提取IP</a></span> <a href="${domain }help/" target="_blank">我提取的代理都能用吗,能用多久?</a> </div> </form> </div> <div class="clear"></div> </div> </div> <div class="clear"></div> <div id="footer"> <div class="copyright"> <span class="footerleft">友情链接: <a href="http://www.qiaodm.com/" target="_blank" title="敲代码,IT技术任你学">敲代码</a> <a href="http://ip.qiaodm.com/" target="_blank" title="敲代码免费代理IP">敲代码免费代理IP</a> <a href="http://proxy.goubanjia.com/" target="_blank" title="敲代码免费代理IP">全网代理IP</a> <a href="http://wantsee.cn" target="_blank" title="">想看就看</a> <a href="http://www.66ip.cn/index.html" target="_blank" title="">66代理</a> </span> <div class="clear"></div> </div> <div class="copyright" style="display: none;"> <span class="footerleft">Copyright © 2015</span> <span class="footerright">All rights reserved</span> <div class="clear"></div> </div> </div> </div> </body> </html>
common/PageParam.java:通用分页类
package com.xiaobaizhiqian.SpringMVCMyBatis.common; import java.util.List; import com.xiaobaizhiqian.SpringMVCMyBatis.entity.TableIp; public class PageParam { private int currPage ; // 当前页 private int totalPage ; // 总页 private int rowCount ; // 总记录数 public static int pageSize = 10; // 页大小 private List<TableIp> data ; // 数据 public int getCurrPage() { return currPage; } public void setCurrPage(int currPage) { this.currPage = currPage; } public int getTotalPage() { return totalPage; } public void setTotalPage(int totalPage) { this.totalPage = totalPage; } public int getRowCount() { return rowCount; } public void setRowCount(int rowCount) { int totalPage = rowCount / pageSize; if (rowCount % pageSize > 0) { totalPage += 1; } setTotalPage(totalPage); this.rowCount = rowCount; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { PageParam.pageSize = pageSize; } public List<TableIp> getData() { return data; } public void setData(List<TableIp> data) { this.data = data; } }
entity/TableIp.java
package com.xiaobaizhiqian.SpringMVCMyBatis.entity; import java.util.Date; public class TableIp { private int id ; private String ip ; private String port ; private String country ; private String province ; private String city ; private String isp ; private Date findTime ; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getPort() { return port; } public void setPort(String port) { this.port = port; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getIsp() { return isp; } public void setIsp(String isp) { this.isp = isp; } public Date getFindTime() { return findTime; } public void setFindTime(Date findTime) { this.findTime = findTime; } }
entity/Test.java:用于测试MyBatis自动创建数据库表的实体
package com.xiaobaizhiqian.SpringMVCMyBatis.entity; import java.sql.Date; import com.gitee.sunchenbin.mybatis.actable.annotation.Column; import com.gitee.sunchenbin.mybatis.actable.annotation.Table; import com.gitee.sunchenbin.mybatis.actable.constants.MySqlTypeConstant; @Table(name = "test") public class Test{ @Column(name = "id",type = MySqlTypeConstant.CHAR,length = 11,isNull=false) private Integer id; @Column(name = "name",type = MySqlTypeConstant.VARCHAR,length = 111) private String name; @Column(name = "description",type = MySqlTypeConstant.TEXT,length = 100) private String description; @Column(name = "create_time",type = MySqlTypeConstant.DATETIME,length = 0) private Date create_time; @Column(name = "update_time",type = MySqlTypeConstant.DATETIME,length = 0) private Date update_time; @Column(name = "number",type = MySqlTypeConstant.DOUBLE,length = 5,decimalLength = 2,isNull=false,isKey = true) private Long number; @Column(name = "lifecycle",type = MySqlTypeConstant.CHAR,length = 1) private String lifecycle; @Column(name = "dekes",type = MySqlTypeConstant.DOUBLE,length = 5,decimalLength = 2) private Double dekes; public Integer getId(){ return id; } public void setId(Integer id){ this.id = id; } public String getName(){ return name; } public void setName(String name){ this.name = name; } public Date getCreate_time(){ return create_time; } public void setCreate_time(Date create_time){ this.create_time = create_time; } public Date getUpdate_time(){ return update_time; } public void setUpdate_time(Date update_time){ this.update_time = update_time; } public String getDescription(){ return description; } public void setDescription(String description){ this.description = description; } public Long getNumber(){ return number; } public void setNumber(Long number){ this.number = number; } public String getLifecycle(){ return lifecycle; } public void setLifecycle(String lifecycle){ this.lifecycle = lifecycle; } public Double getDekes(){ return dekes; } public void setDekes(Double dekes){ this.dekes = dekes; } }
controller/IndexController.java
package com.xiaobaizhiqian.SpringMVCMyBatis.controller; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.xiaobaizhiqian.SpringMVCMyBatis.common.PageParam; import com.xiaobaizhiqian.SpringMVCMyBatis.service.TableIpService; @Controller public class IndexController { @Resource private TableIpService tableIpService; @RequestMapping({"/","index"}) public String getIndex(HttpServletRequest request) { String currPageStr = request.getParameter("page"); int currPage = 1; try { currPage = Integer.parseInt(currPageStr); } catch (Exception e) { } int rowCount = tableIpService.getRowCount(); PageParam pageParam = new PageParam(); pageParam.setRowCount(rowCount); if (currPage > pageParam.getTotalPage()) { currPage = pageParam.getTotalPage(); } pageParam.setCurrPage(currPage); pageParam = tableIpService.getIpListByPage(pageParam); request.setAttribute("pageParam", pageParam); return "index"; } }
controller/FetchControlle.java控制器
package com.xiaobaizhiqian.SpringMVCMyBatis.controller; import java.io.IOException; import java.io.PrintWriter; import javax.annotation.Resource; 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.RequestMethod; import com.xiaobaizhiqian.SpringMVCMyBatis.service.TableIpService; @Controller public class FetchController { @Resource TableIpService service; @RequestMapping(value = "fetch") public String helloWorld(){ return "fetch"; } @RequestMapping(value = "get", method = RequestMethod.POST) public void get(HttpServletRequest request, HttpServletResponse response){ String number = request.getParameter("num"); String country = request.getParameter("country"); String isp = request.getParameter("isp"); String txt = service.printIp(number, country, isp); PrintWriter writer; try { response.setCharacterEncoding("GBK"); writer = response.getWriter(); writer.write(txt); writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } }
service/TableIpService.jave
package com.xiaobaizhiqian.SpringMVCMyBatis.service; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.xiaobaizhiqian.SpringMVCMyBatis.common.PageParam; import com.xiaobaizhiqian.SpringMVCMyBatis.dao.ITableIpDao; import com.xiaobaizhiqian.SpringMVCMyBatis.entity.TableIp; @Service public class TableIpService { @Resource ITableIpDao dao ; public int getRowCount() { return dao.getRowCount(); } public PageParam getIpListByPage(PageParam pageParam) { int currPage = pageParam.getCurrPage(); // limit offset, size int offset = (currPage - 1) * PageParam.pageSize ; int size = PageParam.pageSize; Map<String, Object> params = new HashMap<String, Object>(); params.put("offset", offset); params.put("size", size); List<TableIp> ipList = dao.selectByParams(params); pageParam.setData(ipList); return pageParam; } public String printIp(String number, String country, String isp) { int size = 100; try { size = Integer.parseInt(number); } catch (Exception e) { } Map<String, Object> params = new HashMap<String, Object>(); params.put("size", size); params.put("country", country); params.put("isp", isp); List<TableIp> ipList = dao.fetchByParams(params); StringBuilder sBuilder = new StringBuilder(); for (TableIp tableIp : ipList) { sBuilder
.append(tableIp.getIp()).append(":")
.append(tableIp.getPort()).append(",")
.append(tableIp.getCountry()).append(",")
.append(tableIp.getIsp()); sBuilder.append(" "); } return sBuilder.toString(); } }
dao/ITableIpDao.java:数据库操作接口,与表对应
package com.xiaobaizhiqian.SpringMVCMyBatis.dao; import java.util.List; import java.util.Map; import org.springframework.stereotype.Repository; import com.xiaobaizhiqian.SpringMVCMyBatis.entity.TableIp; @Repository public interface ITableIpDao { int getRowCount(); List<TableIp> selectByParams(Map<String, Object> params); List<TableIp> fetchByParams(Map<String, Object> params); }
这里我将MyBatis的mapper文件放在mybatisMapper包中
tableIpMapper.xml:与数据库操作接口对应的mapper.xml文件(MyBatis的mapper文件)
<?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"> <!-- namespace必须指向Dao接口 --> <mapper namespace="com.xiaobaizhiqian.SpringMVCMyBatis.dao.ITableIpDao"> <select id="getRowCount" resultType="int"> select count(*) from table_ip </select> <select id="selectByParams" resultType="com.xiaobaizhiqian.SpringMVCMyBatis.entity.TableIp" parameterType="map"> select * from table_ip order by findTime desc limit ${offset}, ${size} </select> <select id="fetchByParams" resultType="com.xiaobaizhiqian.SpringMVCMyBatis.entity.TableIp" parameterType="map"> select * from table_ip where 1=1 <if test="country != null and country != ''"> and country = '${country}' </if> <if test="isp != null and isp != ''"> and isp = '${isp}' </if> limit ${size} </select> </mapper>