1. 效果:效果很一般很一般,望不要吐槽,重要的是功能。
添加:
上面的批量删除:
文件上传功能:
树状结构代码:
2. 代码结构:
3. 数据库结构(很简单的用户表)
4. 配置文件
所使用的 maven 依赖:
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>com.rdkl.ddyun</groupId> <artifactId>shiro-redis</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.7.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.7.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.7.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.jr</groupId> <artifactId>jackson-jr-all</artifactId> <version>2.7.4</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.2.1</version> </dependency> <dependency> <groupId>com.baidu.ueditor</groupId> <artifactId>ueditor</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.3.0</version> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.3.0</version> </dependency> <dependency> <groupId>com.thoughtworks.xstream</groupId> <artifactId>xstream</artifactId> <version>1.4.7</version> </dependency> <dependency> <groupId>com.qq.connect</groupId> <artifactId>Sdk4J</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.30</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.2.4.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-web --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.2.4.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.2.4.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-aop --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>4.2.4.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>4.2.4.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/aspectj/aspectjrt --> <dependency> <groupId>aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.5.4</version> </dependency> <!-- https://mvnrepository.com/artifact/aspectj/aspectjweaver --> <dependency> <groupId>aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.5.4</version> </dependency> <!--以前用的版本是 4.3.16========================================================================================--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.2.4.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.2.4.RELEASE</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.3</version> </dependency> <dependency> <groupId>com.rdkl.ddyun</groupId> <artifactId>shiro-redis</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.23</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.10</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.8.1</version> </dependency> <!-- https://mvnrepository.com/artifact/org.im4java/im4java --> <dependency> <groupId>org.im4java</groupId> <artifactId>im4java</artifactId> <version>1.4.0</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.4.4</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.47</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.13</version> </dependency> <dependency> <groupId>com.thoughtworks.xstream</groupId> <artifactId>xstream</artifactId> <version>1.4.7</version> </dependency> <!-- poi --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>${poi.version}</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>${poi.version}</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <exclusions> <exclusion> <groupId>xerces</groupId> <artifactId>xercesImpl</artifactId> </exclusion> </exclusions> <version>${poi.version}</version> </dependency> <!-- sax 读取时候用到的 --> <dependency> <groupId>xerces</groupId> <artifactId>xercesImpl</artifactId> <version>${xerces.version}</version> <optional>true</optional> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-scratchpad</artifactId> <version>${poi.version}</version> <optional>true</optional> </dependency> <!-- google 工具类 --> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>${guava.version}</version> </dependency> <!-- PDF --> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.6</version> <optional>true</optional> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-asian</artifactId> <version>5.2.0</version> <optional>true</optional> </dependency> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency> <dependency> <groupId>jave</groupId> <artifactId>jave</artifactId> <version>1.0.2</version> </dependency> <!-- https://mvnrepository.com/artifact/cglib/cglib-nodep --> <dependency> <groupId>cglib</groupId> <artifactId>cglib-nodep</artifactId> <version>2.1_3</version> </dependency> <!-- https://mvnrepository.com/artifact/cglib/cglib --> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.1_3</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.2.4.Final</version> </dependency> <dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>jstl-api</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!--为了使用jsp页面的jstl的依赖--> <!-- https://mvnrepository.com/artifact/taglibs/standard --> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <!--日志文件正常使用--> <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api --> <!--<dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.25</version> </dependency>--> <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-nop --> <!-- <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-nop</artifactId> <version>1.7.25</version> <scope>test</scope> </dependency>--> <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-simple --> <!--<dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.7.25</version> <scope>test</scope> </dependency>--> <!-- https://mvnrepository.com/artifact/log4j/log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 --> <!-- <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.25</version> <scope>test</scope> </dependency>--> <!-- https://mvnrepository.com/artifact/net.sourceforge.jexcelapi/jxl --> <!-- 导出excel表格需要的依赖 --> <dependency> <groupId>net.sourceforge.jexcelapi</groupId> <artifactId>jxl</artifactId> <version>2.6</version> </dependency> <!--上传文件使用--> <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> </dependencies>
mybatis的配置 mybatis-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> <!--相关联内容都会被初始化加载 true时延迟加载启动--> <setting name="lazyLoadingEnabled" value="false"/> </settings> <!--设置别名--> <typeAliases> <typeAlias type="com.rdkl.young.entity.User" alias="User"/> </typeAliases> <plugins> <plugin interceptor="com.rdkl.young.plugin.PagePlugin"> <property name="dialect" value="mysql" /> <property name="pageSqlId" value=".*listPage.*" /> </plugin> </plugins> </configuration>
application.properties 数据源的配置:
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://127.0.0.1:3306/young?useUnicode=true&characterEncoding=utf8 jdbc.username=root jdbc.password=root jdbc.initialSize=3 jdbc.minIdle=2 jdbc.maxActive=60 jdbc.maxWait=60000 jdbc.timeBetweenEvictionRunsMillis=60000 jdbc.minEvictableIdleTimeMillis=30000 jdbc.validationQuery=select 1 jdbc.testWhileIdle=true jdbc.testOnBorrow=false jdbc.testOnReturn=false jdbc.poolPreparedStatements=true jdbc.maxPoolPreparedStatementPerConnectionSize=20 jdbc.removeAbandoned=true jdbc.removeAbandonedTimeout=120 jdbc.logAbandoned=false jdbc.filters=stat
spring的配置 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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:cache="http://www.springframework.org/schema/cache" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd"> <!--加载properties配置文件--> <context:property-placeholder location="classpath:application.properties" /> <!--扫描service层--> <context:component-scan base-package="com.rdkl.young.service" annotation-config="true"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!--记载事物管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!--数据源的配置--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" > <!-- <property name="driverClassName" value="${jdbc.driver}"/>--> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="initialSize" value="${jdbc.initialSize}" /> <property name="minIdle" value="${jdbc.minIdle}" /> <property name="maxActive" value="${jdbc.maxActive}" /> <property name="maxWait" value="${jdbc.maxWait}" /> <property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}" /> <property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}" /> <property name="validationQuery" value="${jdbc.validationQuery}" /> <property name="testWhileIdle" value="${jdbc.testWhileIdle}" /> <property name="testOnBorrow" value="${jdbc.testOnBorrow}" /> <property name="testOnReturn" value="${jdbc.testOnReturn}" /> <property name="removeAbandoned" value="${jdbc.removeAbandoned}" /> <property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}" /> <property name="filters" value="${jdbc.filters}" /> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:mybatis-config.xml" /> <property name="mapperLocations" value="classpath:com/rdkl/young/mapper/*.xml" /> <property name="typeAliasesPackage" value="com.rdkl.young.entity" /> </bean> <!--配置dao层 自动扫描,将dao中的接口生成代理注入到spring,供给类使用--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.rdkl.young.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> <!--注解式事物--> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" /> </beans>
springmvc的配置 spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:task="http://www.springframework.org/schema/task" xmlns:mvc="http://www.springframework.org/schema/mvc" 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:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd"> <!-- proxy-target-class属性值决定是基于接口的还是基于类的代理被创建。如果proxy-target-class 属性值被设置为true,那么基于类的代理将起作用 (这时需要cglib库)。如果proxy-target-class属值被设置为false或者这个属性被省略,那么标准的JDK 基于接口的代理 --> <aop:aspectj-autoproxy proxy-target-class="true"/> <!--下面一行的作用:可以使用@Controller注解,--> <context:component-scan base-package="com.rdkl.young.controller"/> <!-- aop 实现记录日志功能 --> <mvc:default-servlet-handler /> <!--对静态资源的支持--> <mvc:resources mapping="/images/**" location="/images/" /> <mvc:resources mapping="/css/**" location="/css/" /> <mvc:resources mapping="/js/**" location="/js/" /> <!--对json格式的设定--> <mvc:annotation-driven> <!-- 消息转换使用json格式 --> <mvc:message-converters> <!--先进行string转换 可以解决字符串输出有双引号的问题 --> <bean class="org.springframework.http.converter.StringHttpMessageConverter" /> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> <value>text/plain;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> </list> </property> <property name="prettyPrint" value="true" /> </bean> </mvc:message-converters> </mvc:annotation-driven> <!-- 视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".jsp"/> <property name="order" value="1" /> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> </bean> <!-- 上传文件定义大小 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 默认编码格式 --> <property name="defaultEncoding" value="UTF-8" /> <!-- 文件大小最大值 --> <property name="maxUploadSize" value="10485760000" /> <!-- 内存中的最大值 --> <property name="maxInMemorySize" value="40960" /> </bean> <!-- <aop:config proxy-target-class="true"/>--> </beans>
log4j.properties 日志文件的配置
# Output pattern : date [thread] priority category - message log4j.rootLogger=INFO, stdout, logfile log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS}: %-4r - method:%l%n%m%n log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender log4j.appender.logfile.file=${webRoot}/log/log log4j.appender.logfile.DatePattern= '.'yyyy-MM-dd'.log' log4j.appender.logfile.Append=true log4j.appender.logfile.layout=org.apache.log4j.PatternLayout log4j.appender.logfile.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS}: %-4r - method:%l%n%m%n #mybatis logger config log4j.logger.org.apache.ibatis=INFO log4j.logger.java.sql.Connection=debug log4j.logger.java.sql.Statement=debug log4j.logger.java.sql.PreparedStatement=debug
web.xml 文件的配置
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Archetype Created Web Application</display-name> <!--spring的配置--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>webAppRootKeySite</param-name> <param-value>webRoot</param-value> </context-param> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <!--解决post乱码--> <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> <servlet> <servlet-name>dispatcher</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>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/WEB-INF/views/jsps/one.jsp</welcome-file> </welcome-file-list> </web-app>
5. 首页面功能详解
(1)实体类:
package com.rdkl.young.entity; import org.springframework.format.annotation.DateTimeFormat; import java.io.Serializable; import java.util.Date; import java.util.List; public class User implements Serializable { private Long uid; private String uname; // 用户名 private String loginname; // 登录名 private String password; // 密码 private String emile; // 邮箱 @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date createtime; // 创建时间 private String file; // 上传文件地址 private String fileName; // 上传文件名 /*获取自身集合*/ private List<User> userList; public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getFile() { return file; } public void setFile(String file) { this.file = file; } public Long getUid() { return uid; } public void setUid(Long uid) { this.uid = uid; } public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } public String getLoginname() { return loginname; } public void setLoginname(String loginname) { this.loginname = loginname; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmile() { return emile; } public void setEmile(String emile) { this.emile = emile; } public Date getCreatetime() { return createtime; } public void setCreatetime(Date createtime) { this.createtime = createtime; } public List<User> getUserList() { return userList; } public void setUserList(List<User> userList) { this.userList = userList; } }
使用到的分页工具类:Page.java
package com.rdkl.young.entity; public class Page { private int pageSize = 10; //每页显示记录数 private int totalPage; //总页数 private int totalCount; //总记录数 private int pageNo; //当前页 private int currentIndex; //当前记录起始索引 private boolean entityOrField; //true:需要分页的地方,传入的参数就是Page实体;false:需要分页的地方,传入的参数所代表的实体拥有Page属性 public int getTotalPage() { if(totalCount%pageSize==0) totalPage = totalCount/pageSize; else totalPage = totalCount/pageSize+1; return totalPage; } public void setTotalPage(int totalPage) { this.totalPage = totalPage; } public int getTotalCount() { return totalCount; } public void setTotalCount(int totalCount) { this.totalCount = totalCount; } public int getPageNo() { if(pageNo<=0) pageNo = 1; if(pageNo>getTotalPage()) pageNo = getTotalPage(); return pageNo; } public void setPageNo(int pageNo) { this.pageNo = pageNo; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getCurrentIndex() { currentIndex = (getPageNo()-1)*getPageSize(); if(currentIndex<0) currentIndex = 0; return currentIndex; } public void setCurrentIndex(int currentIndex) { this.currentIndex = currentIndex; } public boolean isEntityOrField() { return entityOrField; } public void setEntityOrField(boolean entityOrField) { this.entityOrField = entityOrField; } }
dao层 代码:
package com.rdkl.young.dao; import com.rdkl.young.entity.User; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Map; @Repository public interface UserMapper { List<User> myPageAllUser(); /* 根据条件查询用户全部信息 */ List<User> listPageAllUser(Map<String,Object> map); /* 根据用户id查询 */ User getByID(Long uid); /* 修改 */ void updataUser(User user); /* 添加 */ void insertUser(User uu); /* 删除 */ void delUser(Map<String,Object> map); }
service 层:
package com.rdkl.young.service; import com.rdkl.young.entity.User; import com.rdkl.young.dao.UserMapper; import jxl.CellView; import jxl.format.Alignment; import jxl.format.Colour; import jxl.format.UnderlineStyle; import jxl.format.VerticalAlignment; import jxl.write.*; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.Map; @Service @Transactional public class UserService { @Autowired private UserMapper userMapper; /*这里spring的severity的值设置为”warning”, 降低Autowired检测的级别 不然会报红线 但是对运行项目没影响*/ public List<User> myPageAllUser(){ return userMapper.myPageAllUser(); } public List<User> listPageAllUser(Map<String,Object> map){ return userMapper.listPageAllUser(map); } public User getByID(Long uid) { return userMapper.getByID(uid); } public void updataUser(User user){ userMapper.updataUser(user); } public void insertUser(User uu) { userMapper.insertUser(uu); } public void delUser(Map<String,Object> map) { userMapper.delUser(map); } /** * id放入list * * @param id * id(多个已逗号分隔) * @return List集合 */ public List<String> getList(String id) { List<String> list = new ArrayList<String>(); String[] str = id.split(","); for (int i = 0; i < str.length; i++) { list.add(str[i]); } return list; } /** * 导出数据成excel表格 * @param response * @param listUser * @param */ public void exportUser(HttpServletRequest request,HttpServletResponse response, List<User> listUser) { WritableWorkbook wwb = null; OutputStream os = null; SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); try { os = response.getOutputStream();// 取得输出流 response.reset();// 清空输出流 // excel 文件的 MIME 类型 response.setContentType("application/msexcel"); //在导出前对名称根据浏览器做下处理 String agent = request.getHeader("USER-AGENT").toLowerCase(); response.setContentType("application/vnd.ms-excel"); //***************很重要 String fileName = "问卷调查";//文件名中文乱码 String codedFileName = java.net.URLEncoder.encode(fileName, "UTF-8"); if (agent.contains("firefox")) { response.setCharacterEncoding("utf-8"); response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes(), "ISO8859-1") + ".xls"); } else { response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xls"); } /* response.setHeader("Content-disposition", "attachment; filename=courseStatistics.xls");// 设定输出文件头 response.setContentType("application/msexcel");// 定义输出类型*/ // os = new FileOutputStream(fileName); wwb = jxl.Workbook.createWorkbook(os); WritableSheet ws = wwb.createSheet("课程统计", 10); // 创建一个工作表 // 设置标题单元格的文字格式 WritableFont titleFont = new WritableFont(WritableFont.createFont("宋体"), 12, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE,Colour.BLACK); WritableCellFormat titleFontFormat = new WritableCellFormat(titleFont); titleFontFormat.setVerticalAlignment(VerticalAlignment.CENTRE); titleFontFormat.setAlignment(Alignment.CENTRE); titleFontFormat.setBackground(Colour.LIGHT_TURQUOISE); /*======================================================================第二种标题====================================*/ WritableFont titleFont1 = new WritableFont(WritableFont.createFont("宋体"), 12, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE,Colour.BLACK); WritableCellFormat titleFontFormat1 = new WritableCellFormat(titleFont1); titleFontFormat1.setVerticalAlignment(VerticalAlignment.CENTRE); titleFontFormat1.setAlignment(Alignment.CENTRE); titleFontFormat1.setBackground(Colour.LAVENDER); /*=======================================================================第三种标题===================================*/ WritableFont titleFont2 = new WritableFont(WritableFont.createFont("宋体"), 12, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE,Colour.BLACK); WritableCellFormat titleFontFormat2 = new WritableCellFormat(titleFont2); titleFontFormat2.setVerticalAlignment(VerticalAlignment.CENTRE); titleFontFormat2.setAlignment(Alignment.CENTRE); titleFontFormat2.setBackground(Colour.LIGHT_GREEN); /*=======================================================================第四种标题===================================*/ WritableFont titleFont3 = new WritableFont(WritableFont.createFont("宋体"), 12, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE,Colour.BLACK); WritableCellFormat titleFontFormat3 = new WritableCellFormat(titleFont3); titleFontFormat3.setVerticalAlignment(VerticalAlignment.CENTRE); titleFontFormat3.setAlignment(Alignment.CENTRE); titleFontFormat3.setBackground(Colour.LIGHT_ORANGE); /*=======================================================================第五种标题===================================*/ WritableFont titleFont4 = new WritableFont(WritableFont.createFont("宋体"), 12, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE,Colour.BLACK); WritableCellFormat titleFontFormat4 = new WritableCellFormat(titleFont4); titleFontFormat4.setVerticalAlignment(VerticalAlignment.CENTRE); titleFontFormat4.setAlignment(Alignment.CENTRE); titleFontFormat4.setBackground(Colour.YELLOW); // 设置内容数据单元格的文字格式 WritableFont cellFont = new WritableFont(WritableFont.createFont("宋体"), 12, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE,Colour.BLACK); WritableCellFormat cellFontFormat = new WritableCellFormat(cellFont); cellFontFormat.setVerticalAlignment(VerticalAlignment.CENTRE);//垂直居中 cellFontFormat.setAlignment(Alignment.CENTRE);//文字对齐方式 WritableFont firstCellFont = new WritableFont(WritableFont.createFont("宋体"), 12, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE,Colour.BLACK); WritableCellFormat firstCellFontFormat = new WritableCellFormat(firstCellFont); ws.getSettings().setDefaultColumnWidth(18); ws.getSettings().setDefaultRowHeight(300); ws.setColumnView(0, 26); ws.setColumnView(1, 26); ws.setColumnView(2, 24); ws.setColumnView(3, 24); ws.setColumnView(12, 24); ws.setColumnView(13, 24); ws.setColumnView(14, 24); ws.setColumnView(15, 24); ws.setColumnView(16, 24); ws.setColumnView(17, 24); ws.setColumnView(18, 24); // 填充标题 //ws.addCell(new Label(0, 0, "课程知识点规划", titleFontFormat)); //ws.mergeCells(0, 0, 3, 0);//合并单元格 第一个参数从哪个列开始合并,第二个参数为第几行,第三个参数为到那一列结束,第四个参数为合并几行 ws.addCell(new Label(0, 0, "用户名", titleFontFormat)); ws.mergeCells(0, 0, 0, 1); for (int j = 0; j < listUser.size(); j++) { User entity = listUser.get(j); ws.addCell(new Label(0, j + 2, "" + entity.getUname(), firstCellFontFormat)); } ws.addCell(new Label(1, 0, "可以登录", titleFontFormat)); ws.addCell(new Label(1, 1, "登录名", titleFontFormat)); for (int j = 0; j < listUser.size(); j++) { User entity = listUser.get(j); ws.addCell(new Label(1, j + 2, "" + entity.getLoginname(), firstCellFontFormat)); } ws.addCell(new Label(2, 1, "邮箱", titleFontFormat)); for (int j = 0; j < listUser.size(); j++) { User entity = listUser.get(j); ws.addCell(new Label(2, j + 2, "" + entity.getEmile(), firstCellFontFormat)); } ws.mergeCells(1, 0, 2, 0); // 向右合并6列单元格 ws.addCell(new Label(3, 0, "创建时间", titleFontFormat)); ws.mergeCells(3, 0, 0, 1); for (int j = 0; j < listUser.size(); j++) { User entity = listUser.get(j); ws.addCell(new Label(3, j + 2, "" + df.format(entity.getCreatetime()), cellFontFormat)); } ws.toString(); wwb.write(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (wwb != null) { wwb.close(); } if (os != null) { os.close(); } } catch (Exception e) { e.printStackTrace(); } } } public void download(String path,String fileName,HttpServletRequest request, HttpServletResponse response) throws IOException{ BufferedInputStream buff = null; FileInputStream fis = null; OutputStream myout = null; try { String finalFileName = null; // 获取浏览器代理信息 final String userAgent = request.getHeader("USER-AGENT"); if(StringUtils.contains(userAgent, "MSIE")||StringUtils.contains(userAgent,"Trident")){//IE浏览器 finalFileName = URLEncoder.encode(fileName,"UTF8"); System.out.println("IE浏览器"); }else if(StringUtils.contains(userAgent, "Mozilla")){//google,火狐浏览器 finalFileName = new String(fileName.getBytes(), "ISO8859-1"); }else{ finalFileName = URLEncoder.encode(fileName,"UTF8");//其他浏览器 } File file = new File(path); response.setCharacterEncoding("UTF-8"); response.setHeader("Content-Disposition", "attachment; filename=" + finalFileName); response.setContentLength((int) file.length()); response.setContentType("application/zip");// 定义输出类型 fis = new FileInputStream(file); buff = new BufferedInputStream(fis); byte[] b = new byte[1024];// 相当于我们的缓存 long k = 0;// 该值用于计算当前实际下载了多少字节 myout = response.getOutputStream();// 从response对象中得到输出流,准备下载 // 开始循环下载 while (k < file.length()) { int j = buff.read(b, 0, 1024); k += j; myout.write(b, 0, j); } myout.flush(); } catch (Exception e) { System.out.println(e); } finally { if(buff != null){ buff.close(); } if(fis != null){ fis.close(); } if(myout != null){ myout.close(); } } } }
controller 层:
package com.rdkl.young.controller; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializerFeature; import com.rdkl.young.entity.Page; import com.rdkl.young.entity.User; import com.rdkl.young.service.UserService; import com.rdkl.young.utils.DateTimeUtils; import com.rdkl.young.utils.EncodingDetect; import com.rdkl.young.utils.HttpUtils; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.apache.commons.lang.StringUtils; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URL; import java.text.SimpleDateFormat; import java.util.*; @RequestMapping("test") @Controller public class UserTestController { private static final Logger logger= LoggerFactory.getLogger(UserTestController.class); @Autowired private UserService userService; @RequestMapping("/shouye") public String shouye(Model model){ return "jsps/two"; } @RequestMapping(value="/twouser", produces = "application/json;charset=UTF-8") @ResponseBody public String twouser(HttpServletRequest request, HttpServletResponse response,Page page){ JSONObject jsonObject= new JSONObject(); String pageSize = request.getParameter("rows"); if (StringUtils.isBlank(pageSize)){ pageSize="15"; } String pageNo = request.getParameter("page"); if (StringUtils.isBlank(pageNo)){ pageNo="1"; } page.setPageSize(Integer.parseInt(pageSize)); page.setPageNo(Integer.parseInt(pageNo)); Map<String,Object> map=new HashMap<String, Object>(); map.put("page",page); List<User> listUser = userService.listPageAllUser(map); if(listUser.size()>0){ jsonObject.put("rows",listUser); jsonObject.put("total",page.getTotalCount()); } return jsonObject.toJSONString(jsonObject, SerializerFeature.WriteDateUseDateFormat); } @RequestMapping(value = "/sanye/{uid}",produces = "application/json;charset=UTF-8") public String sanye(Model model, @PathVariable("uid")Long uid){ User u=userService.getByID(uid); model.addAttribute("user",u); model.addAttribute("uid",uid); return "jsps/three"; } @RequestMapping(value = "/updata", produces = "application/json;charset=UTF-8") @ResponseBody public String detupdata(User uu){ JSONObject result = new JSONObject(); Date date = new Date(); result.put("flag",false); if(uu.getUid()!=null){ // 修改方法 uu.setCreatetime(date); userService.updataUser(uu); result.put("flag",true); System.out.println("^^^^^^^^^^^^^^^修改用户"); }else{ // 添加方法 if(StringUtils.isBlank(uu.getFile())){ uu.setFile("暂无上传文档"); } uu.setCreatetime(date); userService.insertUser(uu); System.out.println("^^^^^^^^^^^^^^^添加用户"); result.put("flag",true); } return JSON.toJSONString(result); } @RequestMapping("/diyi") public String diyi(Model model){ return "jsps/one"; } /* 添加数据的方法 */ @RequestMapping(value = "/inertOne",produces = "application/json;charset=UTF-8") public String insertOne(){ return "jsps/three"; } /* 删除数据 */ @RequestMapping(value = "/deleteUser",produces = "application/json;charset=UTF-8") @ResponseBody public String deleteUser(@RequestParam(value = "uids",required = true)List<String> uids, HttpServletRequest request,HttpServletResponse response){ JSONObject jsonObj=new JSONObject(); Map<String,Object> map=new HashMap<String,Object>(); jsonObj.put("flag",false); try { System.out.println("想要删除的id值"+uids); if (uids!=null){ map.put("uids",uids); userService.delUser(map); jsonObj.put("flag",true); } } catch (Exception e) { e.printStackTrace(); } return JSON.toJSONString(jsonObj); } /* 导出文件 */ @RequestMapping(value = "/exportUser",produces = "application/json;charset=UTF-8") @ResponseBody public String exportUser(HttpServletRequest request,HttpServletResponse response){ try { /*Map<String,Object> map=new HashMap<String,Object>();*/ List<User> listUser = userService.myPageAllUser(); System.out.println("=======导出方法走了======"+listUser); if (listUser!=null&&listUser.size()>0){ userService.exportUser(request,response,listUser); System.out.println("=======导出文件了======"); } } catch (Exception e) { e.printStackTrace(); } return null; } /** * 获取详情页 * @param model * @param uid * @return */ @RequestMapping(value = "/details/{uid}",produces = "application/json;charset=UTF-8") public String details(Model model,@PathVariable("uid")Long uid){ User user = userService.getByID(uid); model.addAttribute("user",user); model.addAttribute("uid",uid); return "jsps/four"; } @RequestMapping("/chuan") public String diwu(Model model){ return "jsps/five"; } /** * 上传文档 * @param upload * * @param request * @return */ @RequestMapping(value = "/uploadfile") @ResponseBody public String uploadfile(@RequestParam("upload") MultipartFile upload, HttpServletRequest request) throws Exception{ System.out.println("上传文档走了========================================"+upload); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS"); String res = sdf.format(new Date()); // uploads文件夹位置 String rootPath = request.getSession().getServletContext().getRealPath("resource/uploads/"); // 原始名称 String originalFileName = upload.getOriginalFilename(); // 新文件名 String newFileName = "sliver" + res + originalFileName.substring(originalFileName.lastIndexOf(".")); // 创建年月文件夹 Calendar date = Calendar.getInstance(); File dateDirs = new File(date.get(Calendar.YEAR) + File.separator + (date.get(Calendar.MONTH)+1)); // 新文件 File newFile = new File(rootPath + File.separator + dateDirs + File.separator + newFileName); // 判断目标文件所在目录是否存在 if( !newFile.getParentFile().exists()) { // 如果目标文件所在的目录不存在,则创建父目录 newFile.getParentFile().mkdirs(); } System.out.println(newFile); // 将内存中的数据写入磁盘 upload.transferTo(newFile); // 完整的url String fileUrl = date.get(Calendar.YEAR) + "/" + (date.get(Calendar.MONTH)+1) + "/" + newFileName; return fileUrl; } @RequestMapping(value = "/upload22") @ResponseBody public String upload22(@RequestParam("upload") MultipartFile upload, HttpServletRequest request,HttpServletResponse response) throws Exception{ System.out.println("上传文档走了========================================"+upload); JSONObject result = new JSONObject(); String prefix; String filename; String rootPath = null; try { rootPath = request.getSession().getServletContext().getRealPath("/WEB-INF/resource/upload/");/* 得到上传文件保存地址 */ String filetype = ""; String fileOldName = upload.getOriginalFilename(); /* 得到上传文件的名字 */ System.out.println("——————————————————上传文件名:"+fileOldName); int index = upload.getOriginalFilename().lastIndexOf("."); if (index > -1) { filetype = upload.getOriginalFilename().substring(index + 1); } prefix = "/data/" + filetype + "/" + DateTimeUtils.getNowTimeString(); System.out.println("——————————————————上传文件名前的目录:"+prefix); filename = UUID.randomUUID().toString() + "." + filetype; File copyFile = new File(rootPath + prefix + filename); if (!copyFile.getParentFile().exists()) { /* 判断地址是否存在 */ copyFile.getParentFile().mkdirs(); /* 如果不存在,就创建新的 */ } upload.transferTo(copyFile); if(filetype.toLowerCase().equals("srt")){ /* 当我们不知道文件编码格式,通过如下方法获取 */ String charset = EncodingDetect.getJavaEncode(copyFile.getPath());/* 获得文件编码 */ if(StringUtils.isNotBlank(charset)){ String content = FileUtils.readFileToString(copyFile, charset);/* 根据文件编码获得文件内容 */ FileUtils.writeStringToFile(copyFile, content, "utf-8"); /* 写入一行数据,如果里头有值则会被替换 */ } } System.out.println("最终的文件地址:"+prefix + filename); result.put("relPath", prefix + filename); result.put("filename", filename); result.put("fileOldName", fileOldName); result.put("flag", true); } catch (Exception e) { result.put("flag", false); e.printStackTrace(); } response.setContentType("text/html;charset=UTF-8"); response.getWriter().print(result); return null; } @RequestMapping(value = "/downloadUser/{uid}",produces = "application/json;charset=UTF-8") @ResponseBody public String downloadUser(@PathVariable("uid")Long uid,HttpServletRequest request,HttpServletResponse response) { String rootpath=request.getSession().getServletContext().getRealPath("/WEB-INF/resource/upload/"); try { User user = userService.getByID(uid); userService.download(rootpath+user.getFile(),user.getFileName(),request,response); } catch (IOException e) { e.printStackTrace(); } return null; } /* 实现树状结构 */ @RequestMapping("/shuu") public String shuu(Model model){ return "jsps/sex"; } }
操作 String字符串的工具类:
package com.rdkl.young.utils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Tools { /** * 检测字符串是否不为空(null,"","null") * @param s * @return 不为空则返回true,否则返回false */ public static boolean notEmpty(String s){ return s!=null && !"".equals(s) && !"null".equals(s); } /** * 检测字符串是否为空(null,"","null") * @param s * @return 为空则返回true,不否则返回false */ public static boolean isEmpty(String s){ return s==null || "".equals(s) || "null".equals(s); } /** * 字符串转换为字符串数组 * @param str 字符串 * @param splitRegex 分隔符 * @return */ public static String[] str2StrArray(String str,String splitRegex){ if(isEmpty(str)){ return null; } return str.split(splitRegex); } /** * 用默认的分隔符(,)将字符串转换为字符串数组 * @param str 字符串 * @return */ public static String[] str2StrArray(String str){ return str2StrArray(str,",\s*"); } /** * 按照yyyy-MM-dd HH:mm:ss的格式,日期转字符串 * @param date * @return yyyy-MM-dd HH:mm:ss */ public static String date2Str(Date date){ return date2Str(date,"yyyy-MM-dd HH:mm:ss"); } /** * 按照yyyy-MM-dd HH:mm:ss的格式,字符串转日期 * @param date * @return */ public static Date str2Date(String date){ if(notEmpty(date)){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { return sdf.parse(date); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return new Date(); }else{ return null; } } /** * 按照参数format的格式,日期转字符串 * @param date * @param format * @return */ public static String date2Str(Date date,String format){ if(date!=null){ SimpleDateFormat sdf = new SimpleDateFormat(format); return sdf.format(date); }else{ return ""; } } }
操作数据库的 mysql UserMapper.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.rdkl.young.dao.UserMapper"> <select id="myPageAllUser" resultType="User"> select * from `user` order by createtime desc </select> <select id="listPageAllUser" parameterType="Map" resultType="User"> select * from `user` </select> <select id="getByID" parameterType="user" resultType="User"> select * from `user` where uid=#{uid} </select> <update id="updataUser" parameterType="User"> UPDATE user set uname=#{uname},loginname=#{loginname},password=#{password},createtime=#{createtime},emile=#{emile},file=#{file},fileName=#{fileName} where uid=#{uid} </update> <insert id="insertUser" parameterType="User"> INSERT INTO `user` (uid, uname, loginname, password, emile,createtime,file,fileName) values(#{uid},#{uname},#{loginname},#{password},#{emile},#{createtime},#{file},#{fileName}) </insert> <delete id="delUser" parameterType="Map"> DELETE from `user` where uid in <foreach collection="uids" item="uid" open="(" separator="," close=")"> #{uid} </foreach> </delete> </mapper>
(2)首页; 我使用的是 iframe
one.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@include file="/WEB-INF/views/head/headen.jsp"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>最开始的页面</title> <link rel="stylesheet" type="text/css" href="${ctx}/js/jquery-easyui-1.4.3/themes/gray/easyui.css"/> <link rel="stylesheet" type="text/css" href="${ctx}/js/jquery-easyui-1.4.3/themes/icon.css"/> <script type="text/javascript" src="${ctx}/js/jquery-1.11.1.min.js"></script> <script type="text/javascript" src="${ctx}/js/jquery-easyui-1.4.3/jquery.easyui.min.js"></script> <script type="text/javascript" src="${ctx}/js/jquery-easyui-1.4.3/locale/easyui-lang-zh_CN.js"></script> <script type="text/javascript" src="${ctx}/js/dateFormat.js"></script> <script type="text/javascript" src="${ctx}/js/layer/layer.js"></script> <script type="text/javascript" src="${ctx}/js/jquery.form.js"></script> <script type="text/javascript" src="${ctx}/js/json2.js"></script> <script type="text/javascript" src="${ctx}/js/common.js"></script> </head> <body> <div class="con-page"> <div class="main_base"> <div class="time-base current" id="current_right"> <iframe frameborder="0" width="100%" name="rightContent" id="rightContent" heigth="100%" style="min-height: 775px;overflow:auto" marginwidth="0" scrolling="no" ></iframe> <!-- 预留给一级子页面跳转到父页面url地址 --> <input type="hidden" id="srcUrl"> </div> </div> </div> <script type="text/javascript"> var srcUrl=parent.$("#srcUrl").val();//父页面url地址 $(function () { $("#rightContent").attr("src","${ctx}"+"/test/shouye");//默认加载右侧选中的数据 }) </script> </body> </html>
"src","${ctx}"+"/test/shouye" shouye的后台代码
package com.rdkl.young.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.rdkl.young.entity.Page;
import com.rdkl.young.entity.User;
import com.rdkl.young.service.UserService;
import com.rdkl.young.utils.DateTimeUtils;
import com.rdkl.young.utils.EncodingDetect;
import com.rdkl.young.utils.HttpUtils;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
@RequestMapping("test")
@Controller
public class UserTestController {
private static final Logger logger= LoggerFactory.getLogger(UserTestController.class);
@Autowired
private UserService userService;
@RequestMapping("/shouye")
public String shouye(Model model){
return "jsps/two";
}
}
two.jsp 代码:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@include file="/WEB-INF/views/head/headen.jsp"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>首页</title> <link rel="stylesheet" type="text/css" href="${ctx}/js/jquery-easyui-1.4.3/themes/gray/easyui.css"/> <link rel="stylesheet" type="text/css" href="${ctx}/js/jquery-easyui-1.4.3/themes/icon.css"/> <script type="text/javascript" src="${ctx}/js/jquery-1.11.1.min.js"></script> <script type="text/javascript" src="${ctx}/js/jquery-easyui-1.4.3/jquery.easyui.min.js"></script> <script type="text/javascript" src="${ctx}/js/jquery-easyui-1.4.3/locale/easyui-lang-zh_CN.js"></script> <script type="text/javascript" src="${ctx}/js/dateFormat.js"></script> <script type="text/javascript" src="${ctx}/js/layer/layer.js"></script> <script type="text/javascript" src="${ctx}/js/json2.js"></script> </head> <body> <style> .box{ 800px; padding-left: 300px; padding-top: 300px; display: block; } .work{ border-bottom:1px dotted #000; display:inline; 40px; } .work a{ color: white; cursor:pointer; } #deleteuu{ margin-left: 10px; } #xiangqing{ margin-left: 10px; } </style> <script type="text/javascript"> var totalCount=0; $(function(){ parent.$("#rightContent").css("height",800);//修改iframe高度 showuser(); }); function showuser() { $("#zhanshi").datagrid({ remoteSort:false,// 页面排序 singleSelect:true,// 为true时 单选一行 nowrap:false,//设置为true,当数据长度超出列宽时将会自动截取 striped : true,//设置为true将交替显示行背景。 fitColumns:true,// 自动填满datagrid指定的宽度 url :"${ctx}/test/twouser",// 进入后台的 url 地址 columns : [ [ { field : 'uid', title : 'ID', align : 'center', hidden:true }, { field : 'uname', title : '姓名', width : 250 },{ field : 'loginname', title : '登录名', align : 'center', width : 100 },{ field : 'createtime', title : '创建时间', align : 'center', width : 137, formatter:function(value,row,index) { if(value==null||value==''){ return "--"; }else{ return formatDate(row.createtime); } } },{ field : 'setOperation', title : '操作', align : 'center', width : 146, formatter:function(value,row,index) { var str = "<span class='subOperation'>" + "<a href='javascript:updataUser("+row.uid+");' name='updata' id='updata'>修改</a>" + "<a href='javascript:getDeleteUser("+row.uid+");' name='deleteuu' id='deleteuu'>删除</a>" + "<a href='javascript:xiangqingUser("+row.uid+");' name='xiangqing' id='xiangqing'>详情</a>" + "</span>"; return str; } } ] ], loadMsg : '数据装载中......', singleSelect : false,//为true时只能选择单行 fitColumns : false,// 为true 时允许表格自动缩放,以适应父容器 idField : 'uid',// 当数据表格初始化时 以那一列来排序 remoteSort : false, frozenColumns : [ [ { field : 'ck', checkbox : true } ] ], pagination : true, //分页 rownumbers : false,// 行数 pageSize : 15,//每页显示的记录条数,默认为15 pageList : [ 10, 15, 20, 30 ], onLoadSuccess : function(row) { totalCount = row.total; $(this).datagrid('clearSelections'); //清空选中的行 } }); var userGridPager = $("#zhanshi").datagrid('getPager'); $(userGridPager).pagination({ beforePageText : '第', afterPageText : '页 共 {pages} 页', displayMsg : '当前显示 {from} - {to} 条 共 {total} 条记录' }); } /* 修改用户 */ function updataUser(uid) { //预留给子页面返回当前页面使用 parent.$("#srcUrl").val(parent.$("#rightContent").attr("src")); //跳转子页面-添加左侧栏目 parent.$("#rightContent").attr("src","${ctx}/test/sanye/"+uid); } /* 添加用户 */ function insertUser() { //预留给子页面返回当前页面使用 parent.$("#srcUrl").val(parent.$("#rightContent").attr("src")); //跳转子页面-添加左侧栏目 parent.$("#rightContent").attr("src","${ctx}/test/inertOne"); } /* 删除用户 */ function deleteUser() { var rows=$("#zhanshi").datagrid('getSelections'); var uids = []; if(rows.length==0){ parent.layer.alert("请选择需要删除的记录!",{icon: 0, title:'提示'}); return; }else{ for(var i=0; i<rows.length; i++){ uids.push(rows[i].uid); } getDeleteUser(uids); } } function getDeleteUser(uids) { parent.layer.confirm("确定要删除吗?",{btn: ["确定","取消"],icon: 3, title:"提示"}, function(r) { if (r) { parent.layer.close(r); $.ajax({ url:"${ctx}/test/deleteUser?uids="+uids, dataType:"json", type:"post", /* data:{ "uids":rows.uid },*/ success:function (data) { if(data.flag==true){ parent.layer.alert("删除成功!",{icon: 1, title:'提示'}); /* window.location.href="/test/diyi"; */ }else{ parent.layer.alert("删除失败!",{icon: 2, title:'提示'}); } $("#zhanshi").datagrid('reload'); } }); } }) } /* 导出数据 */ function daoUser() { if(totalCount<0){ parent.layer.alert("暂无数据,无法导出!",{icon: 0, title:'提示'}); } window.location.href="${ctx}/test/exportUser"; } /* 上传文件页面 */ function chuanUser() { //预留给子页面返回当前页面使用 parent.$("#srcUrl").val(parent.$("#rightContent").attr("src")); //跳转子页面-添加左侧栏目 parent.$("#rightContent").attr("src","${ctx}/test/chuan"); } function xiangqingUser(uid) { if(uid==0){ parent.layer.alert("该用户已被删除!",{icon: 0, title:'提示'}); } if(uid!=null&&uid!=0){ //预留给子页面返回当前页面使用 parent.$("#srcUrl").val(parent.$("#rightContent").attr("src")); //跳转子页面-添加左侧栏目 parent.$("#rightContent").attr("src","${ctx}/test/details/"+uid); } } function shu() { //预留给子页面返回当前页面使用 parent.$("#srcUrl").val(parent.$("#rightContent").attr("src")); //跳转子页面-添加左侧栏目 parent.$("#rightContent").attr("src","${ctx}/test/shuu"); } </script> <div class="box" id="my_box"> <div class="work" style="margin-left: 596px;background-color: #2e8ded;" align="center"> <a id="insert" name="insert" onclick="insertUser();" >添加</a> </div> <div class="work" style="margin-left: 10px;background-color: #c9302c;" align="center"> <a id="delete" name="delete" onclick="deleteUser();" >删除</a> </div> <div class="work" style="margin-left: 10px;background-color: #ffab2e;" align="center"> <a id="dao" name="dao" onclick="daoUser();" >导出</a> </div> <div class="work" style="margin-left: 10px;background-color: #ffab2e;" align="center"> <a id="chuan" name="chuan" onclick="chuanUser();" >上传文件</a> </div> <div class="work" style="margin-left: 10px;background-color: #ffab2e;" align="center"> <a id="shuzhuang" name="shuzhuang" onclick="shu();">树状结构</a> </div> <div class="main_1" id="zhanshi"> </div> </div> </body> </html>
url :"${ctx}/test/twouser",// 进入后台的 url 地址 后台代码package com.rdkl.young.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.rdkl.young.entity.Page;
import com.rdkl.young.entity.User;
import com.rdkl.young.service.UserService;
import com.rdkl.young.utils.DateTimeUtils;
import com.rdkl.young.utils.EncodingDetect;
import com.rdkl.young.utils.HttpUtils;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
@RequestMapping("test")
@Controller
public class UserTestController {
private static final Logger logger= LoggerFactory.getLogger(UserTestController.class);
@Autowired
private UserService userService;
@RequestMapping("/shouye")
public String shouye(Model model){
return "jsps/two";
}
@RequestMapping(value="/twouser", produces = "application/json;charset=UTF-8")
@ResponseBody
public String twouser(HttpServletRequest request, HttpServletResponse response,Page page){
JSONObject jsonObject= new JSONObject();
String pageSize = request.getParameter("rows");
if (StringUtils.isBlank(pageSize)){
pageSize="15";
}
String pageNo = request.getParameter("page");
if (StringUtils.isBlank(pageNo)){
pageNo="1";
}
page.setPageSize(Integer.parseInt(pageSize));
page.setPageNo(Integer.parseInt(pageNo));
Map<String,Object> map=new HashMap<String, Object>();
map.put("page",page);
List<User> listUser = userService.listPageAllUser(map);
if(listUser.size()>0){
jsonObject.put("rows",listUser);
jsonObject.put("total",page.getTotalCount());
}
return jsonObject.toJSONString(jsonObject, SerializerFeature.WriteDateUseDateFormat);
}
}
获取用户集合的 sql List<User> listUser = userService.listPageAllUser(map);
<select id="listPageAllUser" parameterType="Map" resultType="User"> select * from `user` </select>
(3) 添加用户:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@include file="/WEB-INF/views/head/headen.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>首页</title>
<link rel="stylesheet" type="text/css" href="${ctx}/js/jquery-easyui-1.4.3/themes/gray/easyui.css"/>
<link rel="stylesheet" type="text/css" href="${ctx}/js/jquery-easyui-1.4.3/themes/icon.css"/>
<script type="text/javascript" src="${ctx}/js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="${ctx}/js/jquery-easyui-1.4.3/jquery.easyui.min.js"></script>
<script type="text/javascript" src="${ctx}/js/jquery-easyui-1.4.3/locale/easyui-lang-zh_CN.js"></script>
<script type="text/javascript" src="${ctx}/js/dateFormat.js"></script>
<script type="text/javascript" src="${ctx}/js/layer/layer.js"></script>
<script type="text/javascript" src="${ctx}/js/json2.js"></script>
</head>
<body>
<style>
.box{
800px;
padding-left: 300px;
padding-top: 300px;
display: block;
}
.work{
border-bottom:1px dotted #000;
display:inline;
40px;
}
.work a{
color: white;
cursor:pointer;
}
#deleteuu{
margin-left: 10px;
}
#xiangqing{
margin-left: 10px;
}
</style>
<script type="text/javascript">
var totalCount=0;
$(function(){
parent.$("#rightContent").css("height",800);//修改iframe高度
showuser();
});
function showuser() {
$("#zhanshi").datagrid({
remoteSort:false,// 页面排序
singleSelect:true,// 为true时 单选一行
nowrap:false,//设置为true,当数据长度超出列宽时将会自动截取
striped : true,//设置为true将交替显示行背景。
fitColumns:true,// 自动填满datagrid指定的宽度
url :"${ctx}/test/twouser",// 进入后台的 url 地址
columns :
[ [
{
field : 'uid',
title : 'ID',
align : 'center',
hidden:true
}, {
field : 'uname',
title : '姓名',
width : 250
},{
field : 'loginname',
title : '登录名',
align : 'center',
width : 100
},{
field : 'createtime',
title : '创建时间',
align : 'center',
width : 137,
formatter:function(value,row,index)
{
if(value==null||value==''){
return "--";
}else{
return formatDate(row.createtime);
}
}
},{
field : 'setOperation',
title : '操作',
align : 'center',
width : 146,
formatter:function(value,row,index)
{
var str = "<span class='subOperation'>" +
"<a href='javascript:updataUser("+row.uid+");' name='updata' id='updata'>修改</a>" +
"<a href='javascript:getDeleteUser("+row.uid+");' name='deleteuu' id='deleteuu'>删除</a>" +
"<a href='javascript:xiangqingUser("+row.uid+");' name='xiangqing' id='xiangqing'>详情</a>" +
"</span>";
return str;
}
}
] ],
loadMsg : '数据装载中......',
singleSelect : false,//为true时只能选择单行
fitColumns : false,// 为true 时允许表格自动缩放,以适应父容器
idField : 'uid',// 当数据表格初始化时 以那一列来排序
remoteSort : false,
frozenColumns : [ [ {
field : 'ck',
checkbox : true
} ] ],
pagination : true, //分页
rownumbers : false,// 行数
pageSize : 15,//每页显示的记录条数,默认为15
pageList : [ 10, 15, 20, 30 ],
onLoadSuccess : function(row) {
totalCount = row.total;
$(this).datagrid('clearSelections'); //清空选中的行
}
});
var userGridPager = $("#zhanshi").datagrid('getPager');
$(userGridPager).pagination({
beforePageText : '第',
afterPageText : '页 共 {pages} 页',
displayMsg : '当前显示 {from} - {to} 条 共 {total} 条记录'
});
}
/* 添加用户 */
function insertUser() {
//预留给子页面返回当前页面使用
parent.$("#srcUrl").val(parent.$("#rightContent").attr("src"));
//跳转子页面-添加左侧栏目
parent.$("#rightContent").attr("src","${ctx}/test/inertOne");
}
</script>
<div class="box" id="my_box">
<div class="work" style="margin-left: 596px;background-color: #2e8ded;" align="center">
<a id="insert" name="insert" onclick="insertUser();" >添加</a>
</div>
<div class="work" style="margin-left: 10px;background-color: #c9302c;" align="center">
<a id="delete" name="delete" onclick="deleteUser();" >删除</a>
</div>
<div class="work" style="margin-left: 10px;background-color: #ffab2e;" align="center">
<a id="dao" name="dao" onclick="daoUser();" >导出</a>
</div>
<div class="work" style="margin-left: 10px;background-color: #ffab2e;" align="center">
<a id="chuan" name="chuan" onclick="chuanUser();" >上传文件</a>
</div>
<div class="work" style="margin-left: 10px;background-color: #ffab2e;" align="center">
<a id="shuzhuang" name="shuzhuang" onclick="shu();">树状结构</a>
</div>
<div class="main_1" id="zhanshi">
</div>
</div>
</body>
</html>
添加用户的后台代码:
/* 添加数据的方法 */ @RequestMapping(value = "/inertOne",produces = "application/json;charset=UTF-8") public String insertOne(){ return "jsps/three"; }
three.jsp 页面 修改 和 添加页面是同一个页面。
在这里把修改的 代码也粘上
/* 修改用户 */
function updataUser(uid) {
//预留给子页面返回当前页面使用
parent.$("#srcUrl").val(parent.$("#rightContent").attr("src"));
//跳转子页面-添加左侧栏目
parent.$("#rightContent").attr("src","${ctx}/test/sanye/"+uid);
}
sanye 这个后台方法
@RequestMapping(value = "/sanye/{uid}",produces = "application/json;charset=UTF-8") public String sanye(Model model, @PathVariable("uid")Long uid){ User u=userService.getByID(uid); model.addAttribute("user",u); model.addAttribute("uid",uid); return "jsps/three"; }
three.jsp 修改 和 添加 页面(一般开发中都会把添加和修改页面做成同一个)
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@include file="/WEB-INF/views/head/headen.jsp"%> <!DOCTYPE html> <html> <head> <title>修改页面</title> <link rel="stylesheet" type="text/css" href="${ctx}/js/jquery-easyui-1.4.3/themes/gray/easyui.css"/> <link rel="stylesheet" type="text/css" href="${ctx}/js/jquery-easyui-1.4.3/themes/icon.css"/> <script type="text/javascript" src="${ctx}/js/jquery-1.11.1.min.js"></script> <script type="text/javascript" src="${ctx}/js/jquery-easyui-1.4.3/jquery.easyui.min.js"></script> <script type="text/javascript" src="${ctx}/js/jquery-easyui-1.4.3/locale/easyui-lang-zh_CN.js"></script> <script src="${ctx}/js/common.js"></script> <script type="text/javascript" src="${ctx}/js/layer/layer.js"></script> <script type="text/javascript" src="${ctx}/js/jquery.form.js"></script> <script type="text/javascript" src="${ctx}/js/validate.js"></script> <script type="text/javascript" src="${ctx}/js/json2.js"></script> <script src="${ctx}/js/dateFormat.js"></script> </head> <body> <style> .main_2{ position: absolute; 400px; margin-left: 300px; margin-top: 300px; height: 400px; z-index:1001; -moz-opacity: 0.8; opacity:.80; filter: alpha(opacity=80); border: dashed; } .main_1{ padding-left: 250px; } #file{ display: none; } </style> <div> <div class="main_1"> <a href="javascript:void(0);" onclick="f_rollback();"> <button class="set_class" style="cursor:pointer;">返回上一级</button> </a> </div> <div class="main_2" id="update_User"> <form method="post" id="userForm" style="background:#fff;"> <div id="index_1"> <input type="hidden" id="uid" name="uid" value="${user.uid}"/> </div> <div id="index_2"> <label>学生姓名*:</label> <div> <input type="text" id="uname" name="uname" value="${user.uname}"/> <%--<textarea id="uname" style=" 99%;">${user.uname}</textarea>--%> </div> </div> <div id="index_3"> <label>登录名*:</label> <div> <input type="text" id="loginname" name="loginname" value="${user.loginname}"/> <%--<textarea id="loginname" style=" 99%;">${user.loginname}</textarea>--%> </div> </div> <div id="index_4"> <label>邮箱*:</label> <div> <input type="text" id="emile" name="emile" value="${user.emile}"/> <%--<textarea id="loginname" style=" 99%;">${user.loginname}</textarea>--%> </div> </div> <div id="index_5"> <label>创建时间:</label> <div > <input type="text" id="createtime" name="createtime" value=" <fmt:formatDate value="${user.createtime}" pattern="yyyy-MM-dd HH:mm:ss" ></fmt:formatDate>"/> </div> </div> </form> <div> <input type="button" class="user-button" value="保存" onclick="xiugai();"/> </div> </div> </div> <%-- js代码块儿 --%> <script type="text/javascript"> var srcUrl=parent.$("#srcUrl").val();//父页面url地址,为了返回上一级使用 $(function () { var uid=$("#uid").val(); if (uid!=null&&uid!=0){ $("#index_4").hide(); }else{ $("#index_5").hide(); } }); function xiugai() { parent.$("#rightContent").css("height",1000);//修改iframe高度 $("#userForm").form("submit", { type:"post", dataType:"json", url:"${ctx}/test/updata", /* data:datas,*/ success:function (da) { var data = eval('('+da+')'); // 把json数据转化为json对象 if(data.flag == true){ parent.layer.alert("添加成功!",{icon: 1, title:'提示'}); parent.$("#rightContent").attr("src",srcUrl);//返回上一级 parent.layer.closeAll(); }else { parent.layer.alert("添加失败!",{icon: 2, title:'提示'}); } } }) } function f_rollback() { parent.$("#rightContent").attr("src",srcUrl); } </script> </body> </html>
updata 后台代码:
@RequestMapping(value = "/updata", produces = "application/json;charset=UTF-8") @ResponseBody public String detupdata(User uu){ JSONObject result = new JSONObject(); Date date = new Date(); result.put("flag",false); if(uu.getUid()!=null){ // 修改方法 uu.setCreatetime(date); userService.updataUser(uu); result.put("flag",true); System.out.println("^^^^^^^^^^^^^^^修改用户"); }else{ // 添加方法 if(StringUtils.isBlank(uu.getFile())){ uu.setFile("暂无上传文档"); } uu.setCreatetime(date); userService.insertUser(uu); System.out.println("^^^^^^^^^^^^^^^添加用户"); result.put("flag",true); } return JSON.toJSONString(result); }
添加 和 修改的 sql 代码
<update id="updataUser" parameterType="User"> UPDATE user set uname=#{uname},loginname=#{loginname},password=#{password},createtime=#{createtime},emile=#{emile},file=#{file},fileName=#{fileName} where uid=#{uid} </update> <insert id="insertUser" parameterType="User"> INSERT INTO `user` (uid, uname, loginname, password, emile,createtime,file,fileName) values(#{uid},#{uname},#{loginname},#{password},#{emile},#{createtime},#{file},#{fileName}) </insert>
(4) 删除功能 (批量删除 和 单个 删除使用同一个sql)
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@include file="/WEB-INF/views/head/headen.jsp"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>首页</title> <link rel="stylesheet" type="text/css" href="${ctx}/js/jquery-easyui-1.4.3/themes/gray/easyui.css"/> <link rel="stylesheet" type="text/css" href="${ctx}/js/jquery-easyui-1.4.3/themes/icon.css"/> <script type="text/javascript" src="${ctx}/js/jquery-1.11.1.min.js"></script> <script type="text/javascript" src="${ctx}/js/jquery-easyui-1.4.3/jquery.easyui.min.js"></script> <script type="text/javascript" src="${ctx}/js/jquery-easyui-1.4.3/locale/easyui-lang-zh_CN.js"></script> <script type="text/javascript" src="${ctx}/js/dateFormat.js"></script> <script type="text/javascript" src="${ctx}/js/layer/layer.js"></script> <script type="text/javascript" src="${ctx}/js/json2.js"></script> </head> <body> <style> .box{ 800px; padding-left: 300px; padding-top: 300px; display: block; } .work{ border-bottom:1px dotted #000; display:inline; 40px; } .work a{ color: white; cursor:pointer; } #deleteuu{ margin-left: 10px; } #xiangqing{ margin-left: 10px; } </style> <script type="text/javascript"> var totalCount=0; $(function(){ parent.$("#rightContent").css("height",800);//修改iframe高度 showuser(); }); function showuser() { $("#zhanshi").datagrid({ remoteSort:false,// 页面排序 singleSelect:true,// 为true时 单选一行 nowrap:false,//设置为true,当数据长度超出列宽时将会自动截取 striped : true,//设置为true将交替显示行背景。 fitColumns:true,// 自动填满datagrid指定的宽度 url :"${ctx}/test/twouser",// 进入后台的 url 地址 columns : [ [ { field : 'uid', title : 'ID', align : 'center', hidden:true }, { field : 'uname', title : '姓名', width : 250 },{ field : 'loginname', title : '登录名', align : 'center', width : 100 },{ field : 'createtime', title : '创建时间', align : 'center', width : 137, formatter:function(value,row,index) { if(value==null||value==''){ return "--"; }else{ return formatDate(row.createtime); } } },{ field : 'setOperation', title : '操作', align : 'center', width : 146, formatter:function(value,row,index) { var str = "<span class='subOperation'>" + "<a href='javascript:updataUser("+row.uid+");' name='updata' id='updata'>修改</a>" + "<a href='javascript:getDeleteUser("+row.uid+");' name='deleteuu' id='deleteuu'>删除</a>" + "<a href='javascript:xiangqingUser("+row.uid+");' name='xiangqing' id='xiangqing'>详情</a>" + "</span>"; return str; } } ] ], loadMsg : '数据装载中......', singleSelect : false,//为true时只能选择单行 fitColumns : false,// 为true 时允许表格自动缩放,以适应父容器 idField : 'uid',// 当数据表格初始化时 以那一列来排序 remoteSort : false, frozenColumns : [ [ { field : 'ck', checkbox : true } ] ], pagination : true, //分页 rownumbers : false,// 行数 pageSize : 15,//每页显示的记录条数,默认为15 pageList : [ 10, 15, 20, 30 ], onLoadSuccess : function(row) { totalCount = row.total; $(this).datagrid('clearSelections'); //清空选中的行 } }); var userGridPager = $("#zhanshi").datagrid('getPager'); $(userGridPager).pagination({ beforePageText : '第', afterPageText : '页 共 {pages} 页', displayMsg : '当前显示 {from} - {to} 条 共 {total} 条记录' }); } /* 修改用户 */ function updataUser(uid) { //预留给子页面返回当前页面使用 parent.$("#srcUrl").val(parent.$("#rightContent").attr("src")); //跳转子页面-添加左侧栏目 parent.$("#rightContent").attr("src","${ctx}/test/sanye/"+uid); } /* 添加用户 */ function insertUser() { //预留给子页面返回当前页面使用 parent.$("#srcUrl").val(parent.$("#rightContent").attr("src")); //跳转子页面-添加左侧栏目 parent.$("#rightContent").attr("src","${ctx}/test/inertOne"); } /* 删除用户 */ function deleteUser() { var rows=$("#zhanshi").datagrid('getSelections'); var uids = []; if(rows.length==0){ parent.layer.alert("请选择需要删除的记录!",{icon: 0, title:'提示'}); return; }else{ for(var i=0; i<rows.length; i++){ uids.push(rows[i].uid); } getDeleteUser(uids); } } function getDeleteUser(uids) { parent.layer.confirm("确定要删除吗?",{btn: ["确定","取消"],icon: 3, title:"提示"}, function(r) { if (r) { parent.layer.close(r); $.ajax({ url:"${ctx}/test/deleteUser?uids="+uids, dataType:"json", type:"post", /* data:{ "uids":rows.uid },*/ success:function (data) { if(data.flag==true){ parent.layer.alert("删除成功!",{icon: 1, title:'提示'}); /* window.location.href="/test/diyi"; */ }else{ parent.layer.alert("删除失败!",{icon: 2, title:'提示'}); } $("#zhanshi").datagrid('reload'); } }); } }) } </script> <div class="box" id="my_box"> <div class="work" style="margin-left: 596px;background-color: #2e8ded;" align="center"> <a id="insert" name="insert" onclick="insertUser();" >添加</a> </div> <div class="work" style="margin-left: 10px;background-color: #c9302c;" align="center"> <a id="delete" name="delete" onclick="deleteUser();" >删除</a> </div> <div class="work" style="margin-left: 10px;background-color: #ffab2e;" align="center"> <a id="dao" name="dao" onclick="daoUser();" >导出</a> </div> <div class="work" style="margin-left: 10px;background-color: #ffab2e;" align="center"> <a id="chuan" name="chuan" onclick="chuanUser();" >上传文件</a> </div> <div class="work" style="margin-left: 10px;background-color: #ffab2e;" align="center"> <a id="shuzhuang" name="shuzhuang" onclick="shu();">树状结构</a> </div> <div class="main_1" id="zhanshi"> </div> </div> </body> </html>
deleteUser 后台代码:
/* 删除数据 */
@RequestMapping(value = "/deleteUser",produces = "application/json;charset=UTF-8")
@ResponseBody
public String deleteUser(@RequestParam(value = "uids",required = true)List<String> uids, HttpServletRequest request,HttpServletResponse response){
JSONObject jsonObj=new JSONObject();
Map<String,Object> map=new HashMap<String,Object>();
jsonObj.put("flag",false);
try {
System.out.println("想要删除的id值"+uids);
if (uids!=null){
map.put("uids",uids);
userService.delUser(map);
jsonObj.put("flag",true);
}
} catch (Exception e) {
e.printStackTrace();
}
return JSON.toJSONString(jsonObj);
}
删除 sql:
<delete id="delUser" parameterType="Map"> DELETE from `user` where uid in <foreach collection="uids" item="uid" open="(" separator="," close=")"> #{uid} </foreach> </delete>
(5) 导出功能
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@include file="/WEB-INF/views/head/headen.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>首页</title>
<link rel="stylesheet" type="text/css" href="${ctx}/js/jquery-easyui-1.4.3/themes/gray/easyui.css"/>
<link rel="stylesheet" type="text/css" href="${ctx}/js/jquery-easyui-1.4.3/themes/icon.css"/>
<script type="text/javascript" src="${ctx}/js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="${ctx}/js/jquery-easyui-1.4.3/jquery.easyui.min.js"></script>
<script type="text/javascript" src="${ctx}/js/jquery-easyui-1.4.3/locale/easyui-lang-zh_CN.js"></script>
<script type="text/javascript" src="${ctx}/js/dateFormat.js"></script>
<script type="text/javascript" src="${ctx}/js/layer/layer.js"></script>
<script type="text/javascript" src="${ctx}/js/json2.js"></script>
</head>
<body>
<style>
.box{
800px;
padding-left: 300px;
padding-top: 300px;
display: block;
}
.work{
border-bottom:1px dotted #000;
display:inline;
40px;
}
.work a{
color: white;
cursor:pointer;
}
#deleteuu{
margin-left: 10px;
}
#xiangqing{
margin-left: 10px;
}
</style>
<script type="text/javascript">
var totalCount=0;
$(function(){
parent.$("#rightContent").css("height",800);//修改iframe高度
showuser();
});
function showuser() {
$("#zhanshi").datagrid({
remoteSort:false,// 页面排序
singleSelect:true,// 为true时 单选一行
nowrap:false,//设置为true,当数据长度超出列宽时将会自动截取
striped : true,//设置为true将交替显示行背景。
fitColumns:true,// 自动填满datagrid指定的宽度
url :"${ctx}/test/twouser",// 进入后台的 url 地址
columns :
[ [
{
field : 'uid',
title : 'ID',
align : 'center',
hidden:true
}, {
field : 'uname',
title : '姓名',
width : 250
},{
field : 'loginname',
title : '登录名',
align : 'center',
width : 100
},{
field : 'createtime',
title : '创建时间',
align : 'center',
width : 137,
formatter:function(value,row,index)
{
if(value==null||value==''){
return "--";
}else{
return formatDate(row.createtime);
}
}
},{
field : 'setOperation',
title : '操作',
align : 'center',
width : 146,
formatter:function(value,row,index)
{
var str = "<span class='subOperation'>" +
"<a href='javascript:updataUser("+row.uid+");' name='updata' id='updata'>修改</a>" +
"<a href='javascript:getDeleteUser("+row.uid+");' name='deleteuu' id='deleteuu'>删除</a>" +
"<a href='javascript:xiangqingUser("+row.uid+");' name='xiangqing' id='xiangqing'>详情</a>" +
"</span>";
return str;
}
}
] ],
loadMsg : '数据装载中......',
singleSelect : false,//为true时只能选择单行
fitColumns : false,// 为true 时允许表格自动缩放,以适应父容器
idField : 'uid',// 当数据表格初始化时 以那一列来排序
remoteSort : false,
frozenColumns : [ [ {
field : 'ck',
checkbox : true
} ] ],
pagination : true, //分页
rownumbers : false,// 行数
pageSize : 15,//每页显示的记录条数,默认为15
pageList : [ 10, 15, 20, 30 ],
onLoadSuccess : function(row) {
totalCount = row.total;
$(this).datagrid('clearSelections'); //清空选中的行
}
});
var userGridPager = $("#zhanshi").datagrid('getPager');
$(userGridPager).pagination({
beforePageText : '第',
afterPageText : '页 共 {pages} 页',
displayMsg : '当前显示 {from} - {to} 条 共 {total} 条记录'
});
}
/* 修改用户 */
function updataUser(uid) {
//预留给子页面返回当前页面使用
parent.$("#srcUrl").val(parent.$("#rightContent").attr("src"));
//跳转子页面-添加左侧栏目
parent.$("#rightContent").attr("src","${ctx}/test/sanye/"+uid);
}
/* 添加用户 */
function insertUser() {
//预留给子页面返回当前页面使用
parent.$("#srcUrl").val(parent.$("#rightContent").attr("src"));
//跳转子页面-添加左侧栏目
parent.$("#rightContent").attr("src","${ctx}/test/inertOne");
}
/* 删除用户 */
function deleteUser() {
var rows=$("#zhanshi").datagrid('getSelections');
var uids = [];
if(rows.length==0){
parent.layer.alert("请选择需要删除的记录!",{icon: 0, title:'提示'});
return;
}else{
for(var i=0; i<rows.length; i++){
uids.push(rows[i].uid);
}
getDeleteUser(uids);
}
}
function getDeleteUser(uids) {
parent.layer.confirm("确定要删除吗?",{btn: ["确定","取消"],icon: 3, title:"提示"}, function(r) {
if (r) {
parent.layer.close(r);
$.ajax({
url:"${ctx}/test/deleteUser?uids="+uids,
dataType:"json",
type:"post",
/* data:{
"uids":rows.uid
},*/
success:function (data) {
if(data.flag==true){
parent.layer.alert("删除成功!",{icon: 1, title:'提示'});
/* window.location.href="/test/diyi"; */
}else{
parent.layer.alert("删除失败!",{icon: 2, title:'提示'});
}
$("#zhanshi").datagrid('reload');
}
});
}
})
}
/* 导出数据 */
function daoUser() {
if(totalCount<0){
parent.layer.alert("暂无数据,无法导出!",{icon: 0, title:'提示'});
}
window.location.href="${ctx}/test/exportUser";
}
</script>
<div class="box" id="my_box">
<div class="work" style="margin-left: 596px;background-color: #2e8ded;" align="center">
<a id="insert" name="insert" onclick="insertUser();" >添加</a>
</div>
<div class="work" style="margin-left: 10px;background-color: #c9302c;" align="center">
<a id="delete" name="delete" onclick="deleteUser();" >删除</a>
</div>
<div class="work" style="margin-left: 10px;background-color: #ffab2e;" align="center">
<a id="dao" name="dao" onclick="daoUser();" >导出</a>
</div>
<div class="work" style="margin-left: 10px;background-color: #ffab2e;" align="center">
<a id="chuan" name="chuan" onclick="chuanUser();" >上传文件</a>
</div>
<div class="work" style="margin-left: 10px;background-color: #ffab2e;" align="center">
<a id="shuzhuang" name="shuzhuang" onclick="shu();">树状结构</a>
</div>
<div class="main_1" id="zhanshi">
</div>
</div>
</body>
</html>
导出数据的 controller
/* 导出文件 */ @RequestMapping(value = "/exportUser",produces = "application/json;charset=UTF-8") @ResponseBody public String exportUser(HttpServletRequest request,HttpServletResponse response){ try { /*Map<String,Object> map=new HashMap<String,Object>();*/ List<User> listUser = userService.myPageAllUser(); System.out.println("=======导出方法走了======"+listUser); if (listUser!=null&&listUser.size()>0){ userService.exportUser(request,response,listUser); System.out.println("=======导出文件了======"); } } catch (Exception e) { e.printStackTrace(); } return null; }
获取数据的 sql
<select id="myPageAllUser" resultType="User"> select * from `user` order by createtime desc </select>
导出 excel 表格的 代码:
/** * 导出数据成excel表格 * @param response * @param listUser * @param */ public void exportUser(HttpServletRequest request,HttpServletResponse response, List<User> listUser) { WritableWorkbook wwb = null; OutputStream os = null; SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); try { os = response.getOutputStream();// 取得输出流 response.reset();// 清空输出流 // excel 文件的 MIME 类型 response.setContentType("application/msexcel"); //在导出前对名称根据浏览器做下处理 String agent = request.getHeader("USER-AGENT").toLowerCase(); response.setContentType("application/vnd.ms-excel"); //***************很重要 String fileName = "问卷调查";//文件名中文乱码 String codedFileName = java.net.URLEncoder.encode(fileName, "UTF-8"); if (agent.contains("firefox")) { response.setCharacterEncoding("utf-8"); response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes(), "ISO8859-1") + ".xls"); } else { response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xls"); } /* response.setHeader("Content-disposition", "attachment; filename=courseStatistics.xls");// 设定输出文件头 response.setContentType("application/msexcel");// 定义输出类型*/ // os = new FileOutputStream(fileName); wwb = jxl.Workbook.createWorkbook(os); WritableSheet ws = wwb.createSheet("课程统计", 10); // 创建一个工作表 // 设置标题单元格的文字格式 WritableFont titleFont = new WritableFont(WritableFont.createFont("宋体"), 12, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE,Colour.BLACK); WritableCellFormat titleFontFormat = new WritableCellFormat(titleFont); titleFontFormat.setVerticalAlignment(VerticalAlignment.CENTRE); titleFontFormat.setAlignment(Alignment.CENTRE); titleFontFormat.setBackground(Colour.LIGHT_TURQUOISE); /*======================================================================第二种标题====================================*/ WritableFont titleFont1 = new WritableFont(WritableFont.createFont("宋体"), 12, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE,Colour.BLACK); WritableCellFormat titleFontFormat1 = new WritableCellFormat(titleFont1); titleFontFormat1.setVerticalAlignment(VerticalAlignment.CENTRE); titleFontFormat1.setAlignment(Alignment.CENTRE); titleFontFormat1.setBackground(Colour.LAVENDER); /*=======================================================================第三种标题===================================*/ WritableFont titleFont2 = new WritableFont(WritableFont.createFont("宋体"), 12, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE,Colour.BLACK); WritableCellFormat titleFontFormat2 = new WritableCellFormat(titleFont2); titleFontFormat2.setVerticalAlignment(VerticalAlignment.CENTRE); titleFontFormat2.setAlignment(Alignment.CENTRE); titleFontFormat2.setBackground(Colour.LIGHT_GREEN); /*=======================================================================第四种标题===================================*/ WritableFont titleFont3 = new WritableFont(WritableFont.createFont("宋体"), 12, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE,Colour.BLACK); WritableCellFormat titleFontFormat3 = new WritableCellFormat(titleFont3); titleFontFormat3.setVerticalAlignment(VerticalAlignment.CENTRE); titleFontFormat3.setAlignment(Alignment.CENTRE); titleFontFormat3.setBackground(Colour.LIGHT_ORANGE); /*=======================================================================第五种标题===================================*/ WritableFont titleFont4 = new WritableFont(WritableFont.createFont("宋体"), 12, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE,Colour.BLACK); WritableCellFormat titleFontFormat4 = new WritableCellFormat(titleFont4); titleFontFormat4.setVerticalAlignment(VerticalAlignment.CENTRE); titleFontFormat4.setAlignment(Alignment.CENTRE); titleFontFormat4.setBackground(Colour.YELLOW); // 设置内容数据单元格的文字格式 WritableFont cellFont = new WritableFont(WritableFont.createFont("宋体"), 12, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE,Colour.BLACK); WritableCellFormat cellFontFormat = new WritableCellFormat(cellFont); cellFontFormat.setVerticalAlignment(VerticalAlignment.CENTRE);//垂直居中 cellFontFormat.setAlignment(Alignment.CENTRE);//文字对齐方式 WritableFont firstCellFont = new WritableFont(WritableFont.createFont("宋体"), 12, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE,Colour.BLACK); WritableCellFormat firstCellFontFormat = new WritableCellFormat(firstCellFont); ws.getSettings().setDefaultColumnWidth(18); ws.getSettings().setDefaultRowHeight(300); ws.setColumnView(0, 26); ws.setColumnView(1, 26); ws.setColumnView(2, 24); ws.setColumnView(3, 24); ws.setColumnView(12, 24); ws.setColumnView(13, 24); ws.setColumnView(14, 24); ws.setColumnView(15, 24); ws.setColumnView(16, 24); ws.setColumnView(17, 24); ws.setColumnView(18, 24); // 填充标题 //ws.addCell(new Label(0, 0, "课程知识点规划", titleFontFormat)); //ws.mergeCells(0, 0, 3, 0);//合并单元格 第一个参数从哪个列开始合并,第二个参数为第几行,第三个参数为到那一列结束,第四个参数为合并几行 ws.addCell(new Label(0, 0, "用户名", titleFontFormat)); ws.mergeCells(0, 0, 0, 1); for (int j = 0; j < listUser.size(); j++) { User entity = listUser.get(j); ws.addCell(new Label(0, j + 2, "" + entity.getUname(), firstCellFontFormat)); } ws.addCell(new Label(1, 0, "可以登录", titleFontFormat)); ws.addCell(new Label(1, 1, "登录名", titleFontFormat)); for (int j = 0; j < listUser.size(); j++) { User entity = listUser.get(j); ws.addCell(new Label(1, j + 2, "" + entity.getLoginname(), firstCellFontFormat)); } ws.addCell(new Label(2, 1, "邮箱", titleFontFormat)); for (int j = 0; j < listUser.size(); j++) { User entity = listUser.get(j); ws.addCell(new Label(2, j + 2, "" + entity.getEmile(), firstCellFontFormat)); } ws.mergeCells(1, 0, 2, 0); // 向右合并6列单元格 ws.addCell(new Label(3, 0, "创建时间", titleFontFormat)); ws.mergeCells(3, 0, 0, 1); for (int j = 0; j < listUser.size(); j++) { User entity = listUser.get(j); ws.addCell(new Label(3, j + 2, "" + df.format(entity.getCreatetime()), cellFontFormat)); } ws.toString(); wwb.write(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (wwb != null) { wwb.close(); } if (os != null) { os.close(); } } catch (Exception e) { e.printStackTrace(); } } }
(6)上传文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@include file="/WEB-INF/views/head/headen.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>首页</title>
<link rel="stylesheet" type="text/css" href="${ctx}/js/jquery-easyui-1.4.3/themes/gray/easyui.css"/>
<link rel="stylesheet" type="text/css" href="${ctx}/js/jquery-easyui-1.4.3/themes/icon.css"/>
<script type="text/javascript" src="${ctx}/js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="${ctx}/js/jquery-easyui-1.4.3/jquery.easyui.min.js"></script>
<script type="text/javascript" src="${ctx}/js/jquery-easyui-1.4.3/locale/easyui-lang-zh_CN.js"></script>
<script type="text/javascript" src="${ctx}/js/dateFormat.js"></script>
<script type="text/javascript" src="${ctx}/js/layer/layer.js"></script>
<script type="text/javascript" src="${ctx}/js/json2.js"></script>
</head>
<body>
<style>
.box{
800px;
padding-left: 300px;
padding-top: 300px;
display: block;
}
.work{
border-bottom:1px dotted #000;
display:inline;
40px;
}
.work a{
color: white;
cursor:pointer;
}
#deleteuu{
margin-left: 10px;
}
#xiangqing{
margin-left: 10px;
}
</style>
<script type="text/javascript">
var totalCount=0;
$(function(){
parent.$("#rightContent").css("height",800);//修改iframe高度
showuser();
});
function showuser() {
$("#zhanshi").datagrid({
remoteSort:false,// 页面排序
singleSelect:true,// 为true时 单选一行
nowrap:false,//设置为true,当数据长度超出列宽时将会自动截取
striped : true,//设置为true将交替显示行背景。
fitColumns:true,// 自动填满datagrid指定的宽度
url :"${ctx}/test/twouser",// 进入后台的 url 地址
columns :
[ [
{
field : 'uid',
title : 'ID',
align : 'center',
hidden:true
}, {
field : 'uname',
title : '姓名',
width : 250
},{
field : 'loginname',
title : '登录名',
align : 'center',
width : 100
},{
field : 'createtime',
title : '创建时间',
align : 'center',
width : 137,
formatter:function(value,row,index)
{
if(value==null||value==''){
return "--";
}else{
return formatDate(row.createtime);
}
}
},{
field : 'setOperation',
title : '操作',
align : 'center',
width : 146,
formatter:function(value,row,index)
{
var str = "<span class='subOperation'>" +
"<a href='javascript:updataUser("+row.uid+");' name='updata' id='updata'>修改</a>" +
"<a href='javascript:getDeleteUser("+row.uid+");' name='deleteuu' id='deleteuu'>删除</a>" +
"<a href='javascript:xiangqingUser("+row.uid+");' name='xiangqing' id='xiangqing'>详情</a>" +
"</span>";
return str;
}
}
] ],
loadMsg : '数据装载中......',
singleSelect : false,//为true时只能选择单行
fitColumns : false,// 为true 时允许表格自动缩放,以适应父容器
idField : 'uid',// 当数据表格初始化时 以那一列来排序
remoteSort : false,
frozenColumns : [ [ {
field : 'ck',
checkbox : true
} ] ],
pagination : true, //分页
rownumbers : false,// 行数
pageSize : 15,//每页显示的记录条数,默认为15
pageList : [ 10, 15, 20, 30 ],
onLoadSuccess : function(row) {
totalCount = row.total;
$(this).datagrid('clearSelections'); //清空选中的行
}
});
var userGridPager = $("#zhanshi").datagrid('getPager');
$(userGridPager).pagination({
beforePageText : '第',
afterPageText : '页 共 {pages} 页',
displayMsg : '当前显示 {from} - {to} 条 共 {total} 条记录'
});
}
/* 修改用户 */
function updataUser(uid) {
//预留给子页面返回当前页面使用
parent.$("#srcUrl").val(parent.$("#rightContent").attr("src"));
//跳转子页面-添加左侧栏目
parent.$("#rightContent").attr("src","${ctx}/test/sanye/"+uid);
}
/* 添加用户 */
function insertUser() {
//预留给子页面返回当前页面使用
parent.$("#srcUrl").val(parent.$("#rightContent").attr("src"));
//跳转子页面-添加左侧栏目
parent.$("#rightContent").attr("src","${ctx}/test/inertOne");
}
/* 删除用户 */
function deleteUser() {
var rows=$("#zhanshi").datagrid('getSelections');
var uids = [];
if(rows.length==0){
parent.layer.alert("请选择需要删除的记录!",{icon: 0, title:'提示'});
return;
}else{
for(var i=0; i<rows.length; i++){
uids.push(rows[i].uid);
}
getDeleteUser(uids);
}
}
function getDeleteUser(uids) {
parent.layer.confirm("确定要删除吗?",{btn: ["确定","取消"],icon: 3, title:"提示"}, function(r) {
if (r) {
parent.layer.close(r);
$.ajax({
url:"${ctx}/test/deleteUser?uids="+uids,
dataType:"json",
type:"post",
/* data:{
"uids":rows.uid
},*/
success:function (data) {
if(data.flag==true){
parent.layer.alert("删除成功!",{icon: 1, title:'提示'});
/* window.location.href="/test/diyi"; */
}else{
parent.layer.alert("删除失败!",{icon: 2, title:'提示'});
}
$("#zhanshi").datagrid('reload');
}
});
}
})
}
/* 导出数据 */
function daoUser() {
if(totalCount<0){
parent.layer.alert("暂无数据,无法导出!",{icon: 0, title:'提示'});
}
window.location.href="${ctx}/test/exportUser";
}
/* 上传文件页面 */
function chuanUser() {
//预留给子页面返回当前页面使用
parent.$("#srcUrl").val(parent.$("#rightContent").attr("src"));
//跳转子页面-添加左侧栏目
parent.$("#rightContent").attr("src","${ctx}/test/chuan");
}
</script>
<div class="box" id="my_box">
<div class="work" style="margin-left: 596px;background-color: #2e8ded;" align="center">
<a id="insert" name="insert" onclick="insertUser();" >添加</a>
</div>
<div class="work" style="margin-left: 10px;background-color: #c9302c;" align="center">
<a id="delete" name="delete" onclick="deleteUser();" >删除</a>
</div>
<div class="work" style="margin-left: 10px;background-color: #ffab2e;" align="center">
<a id="dao" name="dao" onclick="daoUser();" >导出</a>
</div>
<div class="work" style="margin-left: 10px;background-color: #ffab2e;" align="center">
<a id="chuan" name="chuan" onclick="chuanUser();" >上传文件</a>
</div>
<div class="work" style="margin-left: 10px;background-color: #ffab2e;" align="center">
<a id="shuzhuang" name="shuzhuang" onclick="shu();">树状结构</a>
</div>
<div class="main_1" id="zhanshi">
</div>
</div>
</body>
</html>
后台代码:
@RequestMapping("/chuan") public String diwu(Model model){ return "jsps/five"; }
five.jsp 页面 上传文件到本地项目指定目录下,然后写入数据库中
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@include file="/WEB-INF/views/head/headen.jsp"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>文件上传页面</title> <link rel="stylesheet" type="text/css" href="${ctx}/js/jquery-easyui-1.4.3/themes/gray/easyui.css"/> <link rel="stylesheet" type="text/css" href="${ctx}/js/jquery-easyui-1.4.3/themes/icon.css"/> <script type="text/javascript" src="${ctx}/js/jquery-1.11.1.min.js"></script> <script type="text/javascript" src="${ctx}/js/jquery-easyui-1.4.3/jquery.easyui.min.js"></script> <script type="text/javascript" src="${ctx}/js/jquery-easyui-1.4.3/locale/easyui-lang-zh_CN.js"></script> <%-- <script type="text/javascript" src="${ctx}/js/ajaxfileupload.js"></script>--%> <script type="text/javascript" src="${ctx}/js/ajaxupload.3.6.js"></script> <script type="text/javascript" src="${ctx}/js/dateFormat.js"></script> <script type="text/javascript" src="${ctx}/js/layer/layer.js"></script> <script type="text/javascript" src="${ctx}/js/json2.js"></script> </head> <> <style> .wenjian_shangchaun{ 185px; height: 45px; background-color: #00a2e8; color: #fff; margin-left: 12px; font-size: 18px; cursor:pointer; } #sub{ 100px; height:35px; background-color:#00a2e8; color:#fff; cursor:pointer; margin-right: 20px; } .xiazai{ 185px; height: 45px; background-color: #00a2e8; color: #fff; margin-left: 12px; font-size: 18px; cursor:pointer; } /*#mydiv+input{ 100%!important; height:100%!important; }*/ </style> <div id="box_one" style="margin:200px"> <div id="index_1"> <input type="hidden" id="uid" name="uid" value=""/> </div> <div id="index_2"> <label>学生姓名*:</label> <div> <input type="text" id="uname" name="uname" value=""/> <%--<textarea id="uname" style=" 99%;">${user.uname}</textarea>--%> </div> </div> <div id="index_3"> <label>登录名*:</label> <div> <input type="text" id="loginname" name="loginname" value=""/> <%--<textarea id="loginname" style=" 99%;">${user.loginname}</textarea>--%> </div> </div> <div id="index_4"> <label>邮箱*:</label> <div> <input type="text" id="emile" name="emile" value=""/> <%--<textarea id="loginname" style=" 99%;">${user.loginname}</textarea>--%> </div> </div> <%--上传文件--%> <div id="index_5"> <div style="clear:both;padding-bottom:15px;margin-top: 10px;"> <label>上传文档*:</label> <button id="file1" class="wenjian_shangchaun" onclick="uploadFile(this)">上传文档</button> <span id="upshow" class="upload-show" style="left: 20px;display: none"> </span> </div> <div id="up-loading" class="upload-loading" style="display: none;padding-top: 10px;"> <div style="float: left"><img src='${ctx}/images/show.gif'/></div> <div class="upload-answer-loading"><span>正在上传,请稍后...</span></div> </div> <input id="file" name="file" type="hidden" value=""/> <input id="fileName" name="fileName" type="hidden" value=""/> </div> </div> <div style="margin:196px" id="mydiv"> <input type="button" id="sub" name="sub" onclick="submi()" value="保存"/> </div> <%-- js部分 --%> <script type="text/javascript"> var srcUrl=parent.$("#srcUrl").val();//父页面url地址,为了返回上一级使用 var fileName; //后台传过来的上传文件名 var fName=""; var uid; /* 上传文档 */ function uploadFile(button){ new AjaxUpload(button,{ action:"${ctx}/test/upload22", id:'file1', name:'upload', onSubmit : function(file, ext,size){ if (!(ext && /^(pdf|pdfx|doc|docx)$/.test(ext))) { parent.layer.alert("您上传的文件格式不对,请重新选择!",{icon: 0, title:'提示'}); return false; } var fileMaxSize = 4 * 1024 * 1000; if (size > fileMaxSize) { parent.layer.alert("您上传的文件大小过大,请重新选择!",{icon: 0, title:'提示'}); return false; } $("#up-loading").show(); $("#upshow").hide(); this.disable(); }, onComplete:function (file,response) { var result=eval("("+response+")"); if(result.flag == true){ parent.layer.alert("上传成功",{icon: 1, title:'提示'}); fileName = result.fileOldName; fName = "<span>"+fileName+"</span>"; $("#file").val(result.relPath);// 上传文件地址 $("#upshow").html(fName);// 上传文件名 $("#fileName").val(fileName);// 上传文件名 $("#up-loading").hide(); $("#upshow").show(); }else{ parent.layer.alert("上传失败",{icon: 2, title:'提示'}); } this.enable(); } }); } function submi() { var uname=$("#uname").val(); var loginname=$("#loginname").val(); var emile=$("#emile").val(); var file=$("#file").val(); var fileName=$("#fileName").val(); var datas={ 'uname': uname, 'loginname': loginname, 'emile': emile, 'file': file, 'fileName':fileName }; parent.$("#rightContent").css("height",1000);//修改iframe高度 $.ajax({ type:'post', dataType:'json', url:"${ctx}/test/updata", data:datas, success:function (data) { if(data.flag == true){ parent.layer.alert("添加成功!",{icon: 1, title:'提示'}); /* parent.$("#rightContent").attr("src",srcUrl);//返回上一级*/ parent.layer.closeAll(); $("#index_5").hide(); $("#index_6").show(); $("#mydiv").hide(); $("#xiazaixianshi").html( $("#upshow").html()); }else { parent.layer.alert("添加失败!",{icon: 2, title:'提示'}); } } }) } </script> </body> </html>
upload22 上传文档 后台代码:
@RequestMapping(value = "/upload22") @ResponseBody public String upload22(@RequestParam("upload") MultipartFile upload, HttpServletRequest request,HttpServletResponse response) throws Exception{ System.out.println("上传文档走了========================================"+upload); JSONObject result = new JSONObject(); String prefix; String filename; String rootPath = null; try { rootPath = request.getSession().getServletContext().getRealPath("/WEB-INF/resource/upload/");/* 得到上传文件保存地址 */ String filetype = ""; String fileOldName = upload.getOriginalFilename(); /* 得到上传文件的名字 */ System.out.println("——————————————————上传文件名:"+fileOldName); int index = upload.getOriginalFilename().lastIndexOf("."); if (index > -1) { filetype = upload.getOriginalFilename().substring(index + 1); } prefix = "/data/" + filetype + "/" + DateTimeUtils.getNowTimeString(); System.out.println("——————————————————上传文件名前的目录:"+prefix); filename = UUID.randomUUID().toString() + "." + filetype; File copyFile = new File(rootPath + prefix + filename); if (!copyFile.getParentFile().exists()) { /* 判断地址是否存在 */ copyFile.getParentFile().mkdirs(); /* 如果不存在,就创建新的 */ } upload.transferTo(copyFile); if(filetype.toLowerCase().equals("srt")){ /* 当我们不知道文件编码格式,通过如下方法获取 */ String charset = EncodingDetect.getJavaEncode(copyFile.getPath());/* 获得文件编码 */ if(StringUtils.isNotBlank(charset)){ String content = FileUtils.readFileToString(copyFile, charset);/* 根据文件编码获得文件内容 */ FileUtils.writeStringToFile(copyFile, content, "utf-8"); /* 写入一行数据,如果里头有值则会被替换 */ } } System.out.println("最终的文件地址:"+prefix + filename); result.put("relPath", prefix + filename); result.put("filename", filename); result.put("fileOldName", fileOldName); result.put("flag", true); } catch (Exception e) { result.put("flag", false); e.printStackTrace(); } response.setContentType("text/html;charset=UTF-8"); response.getWriter().print(result); return null; }
上传文件完成 保存 文件(相当于添加数据到数据库)
@RequestMapping(value = "/updata", produces = "application/json;charset=UTF-8")
@ResponseBody
public String detupdata(User uu){
JSONObject result = new JSONObject();
Date date = new Date();
result.put("flag",false);
if(uu.getUid()!=null){ // 修改方法
uu.setCreatetime(date);
userService.updataUser(uu);
result.put("flag",true);
System.out.println("^^^^^^^^^^^^^^^修改用户");
}else{ // 添加方法
if(StringUtils.isBlank(uu.getFile())){
uu.setFile("暂无上传文档");
}
uu.setCreatetime(date);
userService.insertUser(uu);
System.out.println("^^^^^^^^^^^^^^^添加用户");
result.put("flag",true);
}
return JSON.toJSONString(result);
}
sql
<insert id="insertUser" parameterType="User"> INSERT INTO `user` (uid, uname, loginname, password, emile,createtime,file,fileName) values(#{uid},#{uname},#{loginname},#{password},#{emile},#{createtime},#{file},#{fileName}) </insert>
sasyui tree 树状结构功能 我只做了 静态的。等我做完 动态的 在来粘贴。
欢迎来我的评论区吐槽。。。。。。。。。。。。。。。。。。。