Spring+Hibernate+struts2+JPA 注解+跨域//完成手机端点击加载更多 下拉加载更多
一、使用IDEA新建一个maven项目(student)
1.1.0编写pom文件,添加项目所需要的包
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.spring</groupId> <artifactId>parent</artifactId> <version>1.0-SNAPSHOT</version> <relativePath>../pom.xml</relativePath> </parent> <artifactId>student</artifactId> <packaging>war</packaging> <properties> <struts2.version>2.5.8</struts2.version> <hibernate.version>5.2.8.Final</hibernate.version> </properties> <!-- 配置打包插件 --> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.2</version> <configuration> <warSourceDirectory>web</warSourceDirectory> <webXml>web\WEB-INF\web.xml</webXml> </configuration> </plugin> </plugins> </build> <dependencies> <!-- struts2 --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>${struts2.version}</version> </dependency> <!-- struts2整合spring的插件 --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-spring-plugin</artifactId> <version>${struts2.version}</version> <!-- 排除整合插件自动依赖的spring核心包, 不然可能会引起版本不一致或冲突的情况。所以使用exclusion 排除循环依赖--> <exclusions> <!-- 排除struts自动依赖的spring-core版本 --> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> </exclusion> <!-- 排除struts自动依赖的spring-beans版本 --> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> </exclusion> </exclusions> </dependency> <!-- JSON插件 --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-json-plugin</artifactId> <version>${struts2.version}</version> </dependency> <!-- 引入aspectj的依赖模块 --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.9</version> </dependency> <!-- 引入spring web模块 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.3.6.RELEASE</version> </dependency> <!-- 引入spring orm 整合hibernate--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>4.3.6.RELEASE</version> </dependency> <!-- 引入Spring tx事务管理模块--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.3.6.RELEASE</version> </dependency> <!-- Hibernate依赖 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <!-- JPA依赖支持,添加实体管理器 --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>${hibernate.version}</version> </dependency> <!-- DBCP连接池 --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <!-- mysql驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.35</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> </dependency> </dependencies> </project>
在这里我用的是MySql数据库,所以在这里添加MySql的驱动包,其他的数据库添加相应的驱包就行了
在这里我继承了父类的pom文件
父类的pom文件如下:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.spring</groupId> <artifactId>parent</artifactId> <version>1.0-SNAPSHOT</version> <packaging>pom</packaging> <!-- 配置maven的常规属性 --> <properties> <!-- 设置整个maven项目的编码格式 --> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <!-- 设置控制台输出参数的编码格式, 解决乱码 --> <orgLine>-Dfile.encoding=UTF-8</orgLine> </properties> <build> <plugins> <!-- 配置maven编译插件,指定maven编译版本 --> <plugin> <!-- 插件名称 --> <artifactId>maven-compiler-plugin</artifactId> <!-- 插件配置信息 --> <configuration> <target>1.8</target> <source>1.8</source> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>4.3.6.RELEASE</version> </dependency> </dependencies> </project>
添加进来的包如下
二、给项目添加Spring支持 以及Web 支持
三、给项目新建好相应的包
在这里没有写建表语句 自动建表 容器在启动的时候会把所需要的表建出来(在ApplicationContext.xml 里面)
<!-- 是否自动执行DDL语句,(自动建表)--> <property name="generateDdl" value="true"/>
实体类(entity)
3.0.1(Student)
package org.student.entity; import javax.persistence.*; /** * Created by YongLin on 17/3/14. */ @Entity @Table(name="STU_INFO") public class Student { private int sid; private String stuName; private int age; private Team team; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "STU_ID") public int getSid() { return sid; } public void setSid(int sid) { this.sid = sid; } @Column(name = "STU_NAME") public String getStuName() { return stuName; } public void setStuName(String stuName) { this.stuName = stuName; } @Column(name = "STU_AGE") public int getAge() { return age; } public void setAge(int age) { this.age = age; } @ManyToOne @JoinColumn(name = "TEAM_ID") public Team getTeam() { return team; } public void setTeam(Team team) { this.team = team; } }
3.0.2(Team)
package org.student.entity; import javax.persistence.*; /** * Created by YongLin on 17/3/15. */ @Entity @Table(name = "TEAM_INFO") public class Team { private int tid; private String teamName; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "TEAM_ID") public int getTid() { return tid; } public void setTid(int tid) { this.tid = tid; } @Column(name = "TEAM_NAME") public String getTeamName() { return teamName; } public void setTeamName(String teamName) { this.teamName = teamName; } }
3.1.1(dao)里面有2个接口 对应2个实现类
3.1.2StuDao
package org.student.dao; import org.student.entity.Student; import java.util.List; /** * Created by wangl on 2017/2/27. */ public interface StuDao { //查询所有学生 public List<Student> findStudents(); public void save(Student student); public List<Student> findByTeam(int tid); public Student findById(int sid); public List<Student> findStudents(int first, int max); }
3.1.3 StuDaoImpl
package org.student.dao.impl; import org.springframework.stereotype.Repository; import org.student.dao.StuDao; import org.student.entity.Student; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import java.util.List; /** * Created by YongLin on 17/3/14. */ @Repository("stuDao") public class StuDaoImpl implements StuDao { @PersistenceContext private EntityManager em; @Override public List<Student> findStudents() { String jpql = "from Student s"; return em.createQuery(jpql).getResultList(); } @Override public void save(Student student) { em.persist(student); } @Override public List<Student> findByTeam(int tid) { String jpql = "from Student s where s.team.tid=?1"; Query query = em.createQuery(jpql); query.setParameter(1,tid); return query.getResultList(); /*String jqpl = "from Student s where s.team.tid=?1"; Query query = em.createQuery(jqpl); query.setParameter(1,tid); return query.getResultList();*/ } @Override public Student findById(int sid) { return null; } @Override public List<Student> findStudents(int first, int max) { String jpql = "from Student s"; Query query = em.createQuery(jpql); //分页 query.setFirstResult(first); query.setMaxResults(max); return query.getResultList(); } }
四、给项目配置好 所以需的配置文件
3.2.1TeamDao
package org.student.dao; import org.student.entity.Team; import java.util.List; /** * Created by YongLin on 17/3/15. */ public interface TeamDao { public List<Team> findTeams(); public void save(Team team); }
3.2.2TeamDaoImpl
package org.student.dao.impl; import org.springframework.stereotype.Repository; import org.student.dao.TeamDao; import org.student.entity.Team; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.List; /** * Created by YongLin on 17/3/15. */ @Repository("teamDao") public class TeamDaoImpl implements TeamDao { @PersistenceContext private EntityManager em; @Override public List<Team> findTeams() { String hql="from Team t"; return em.createQuery(hql).getResultList(); } @Override public void save(Team team) { em.persist(team); } }
3.3.1StuService
package org.student.service; import org.springframework.stereotype.Service; import org.student.entity.Student; import java.util.List; /** * Created by YongLin on 17/3/14. */ @Service("stuService") public interface StuService { public List<Student> findStudent(); public void add(Student student); public List<Student> findByTeam(int tid); public List<Student> findStudents(int first, int max); }
3.3.2StuServiceImpl
package org.student.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.student.dao.StuDao; import org.student.entity.Student; import org.student.service.StuService; import java.util.List; /** * Created by YongLin on 17/3/14. */ @Service("stuService") @Transactional public class StuServiceImpl implements StuService { @Autowired private StuDao stuDao; @Override public List<Student> findStudent() { return stuDao.findStudents(); } @Override public void add(Student student) { stuDao.save(student); } @Override public List<Student> findByTeam(int tid) { return stuDao.findByTeam(tid); } @Override public List<Student> findStudents(int first, int max) { return stuDao.findStudents(first,max); } }
3.3.3TeamService
package org.student.service; import org.student.entity.Team; import java.util.List; /** * Created by YongLin on 17/3/15. */ public interface TeamSevice { public List<Team> findTeams(); public void save(Team team); }
3.3.4TeamServiceImpl
package org.student.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.student.dao.TeamDao; import org.student.entity.Team; import org.student.service.TeamSevice; import java.util.List; /** * Created by YongLin on 17/3/15. */ @Service("teamService") @Transactional public class TeamService implements TeamSevice { @Autowired private TeamDao teamDao; @Override public List<Team> findTeams() { return teamDao.findTeams(); } @Override public void save(Team team) { teamDao.save(team); } }
Action(StuAction)
package org.student.action; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.student.entity.Student; import org.student.entity.Team; import org.student.service.StuService; import org.student.service.TeamSevice; import java.util.List; /** * Created by YongLin on 17/3/14. */ @Controller("stuAction") public class StuAction { private Student student; private String message; private List<Student> studentList; private List<Team> teamList; private Team team; private int pageNum; public int getPageNum() { return pageNum; } public void setPageNum(int pageNum) { this.pageNum = pageNum; } //注入一个Service @Autowired private StuService stuService; @Autowired private TeamSevice teamSevice; public Student getStudent() { return student; } public void setStudent(Student student) { this.student = student; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public List<Student> getStudentList() { return studentList; } public void setStudentList(List<Student> studentList) { this.studentList = studentList; } public List<Team> getTeamList() { return teamList; } public void setTeamList(List<Team> teamList) { this.teamList = teamList; } public StuService getStuService() { return stuService; } public void setStuService(StuService stuService) { this.stuService = stuService; } public TeamSevice getTeamSevice() { return teamSevice; } public void setTeamSevice(TeamSevice teamSevice) { this.teamSevice = teamSevice; } public Team getTeam() { return team; } public void setTeam(Team team) { this.team = team; } public String find(){ studentList = stuService.findStudent(); return "success"; } public String findByPage(){ //第一个参数表示从第几条开始查MySql的0表示第一条 第二个参数表示查询几条 System.out.println(pageNum); studentList=stuService.findStudents(pageNum,5); return "page"; } public String findStusByTeam(){ studentList = stuService.findByTeam(team.getTid()); return "byTeamList"; } public String findTeams(){ teamList = teamSevice.findTeams(); return "teams"; } }
编写CorsFilter(跨域用的 设置响应头部) 实现了Filter
package org.student.filter; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class CrosFilter implements Filter{ @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException { //相应之前设置响应的头部,授权跨域访问 HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Access-Control-Allow-Origin", "*"); response.setDateHeader("Expires", 0); //放行 filterChain.doFilter(req,res); } @Override public void destroy() { } }
4.0.1在resource 下面新建applicantionContext.xml struts.xml如下:
4.1.2applicantionContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" 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.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 启用相应的注解处理器,扫描指定的包 --> <context:component-scan base-package="org.student"/> <!-- 配置数据源,使用DBCP连接池 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <!-- 数据源以及连接池属性 --> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mydate"/> <property name="username" value="root"/> <property name="password" value="root"/> <property name="initialSize" value="5"/> <property name="maxIdle" value="50"/> <property name="maxActive" value="60"/> <property name="minIdle" value="10"/> <property name="maxWait" value="2000"/> </bean> <!-- 配置JPA实现方的适配器,因为JPA实现方有很多, Hibernate也是JPA标准的一种实现,因此这里指定为Hibernate的JPA实现适配器--> <bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> <!-- 配置JPA的属性 --> <!-- 使用的数据库类型,这里使用的是MYSQL --> <property name="database" value="MYSQL"/> <!-- 指定数据库方言--> <property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect"/> <!-- 在控制台显示sql语句--> <property name="showSql" value="true"/> <!-- 是否自动执行DDL语句,(自动建表)--> <property name="generateDdl" value="true"/> </bean> <!-- 配置实体管理器工厂,Spring会依据这个工厂创建并注入一个实体管理器EntityManager, 创建出来的EntityManager是由Spring容器管理的,并且会参与到Spring的事务当中,它是线程安全的--> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <!-- 需要注入一个数据源和JPA的适配器 --> <property name="dataSource" ref="dataSource"/> <property name="jpaVendorAdapter" ref="jpaVendorAdapter"/> <!-- 指定实体的扫描路径 --> <property name="packagesToScan" value="org.student.entity"/> </bean> <!-- 配置JPA事务管理器--> <bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <!-- 需要注入一个实体管理器工厂 --> <property name="entityManagerFactory" ref="entityManagerFactory"/> </bean> <!-- 启用注解事务管理,transaction-manager引用上面的事务管理器--> <tx:annotation-driven transaction-manager="txManager"/> </beans>
4.0.3 struts.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd"> <struts> <package name="struts" extends="json-default"> <action name="find" class="stuAction" method="find"> <result type="json"> <param name="root">studentList</param> </result> </action> <action name="findByPage" class="stuAction" method="findByPage"> <result type="json" name="page"> <param name="root">studentList</param> </result> </action> <action name="findStusByTeam" class="stuAction" method="findStusByTeam"> <result type="json" name="byTeamList"> <param name="root">studentList</param> </result> </action> <action name="findTeams" class="stuAction" method="findTeams"> <result type="json" name="teams"> <param name="root">teamList</param> </result> </action> </package> </struts>
以及在Web下添加相应的文件
Web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <!-- 配置监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 指定spring核心配置文件所在的目录 --> <context-param> <param-name>contextConfigLocation</param-name> <!-- 默认会从WEB—INF下查找applicationContext.xml --> <param-value>classpath*:applicationContext.xml</param-value> </context-param> <filter> <filter-name>crosFilter</filter-name> <filter-class>org.student.filter.CrosFilter</filter-class> </filter> <filter-mapping> <filter-name>crosFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- struts2核心控制器 --> <filter> <filter-name>dispatcher</filter-name> <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>dispatcher</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
在前端页面这边,发起Ajax请求 跨域拿到后台查出的数据
5.0.1 (点击加载更多 clickmore.html)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no"> <title>Title</title> <script src="myjs/jquery-1.11.0.js"></script> <style> #box .box{ width: 100%; height: 100px; padding: 10px 0; border: 1px slateblue solid; border-left:none; border-right: none; font-family: "Microsoft YaHei"; } h4{ text-align: center; color: red; cursor: pointer; } </style> <script type="text/javascript"> $(function(){ //定义一个成员变量 //从第一条开始查 var pageNum = 0; //页面一加载 从第0 条数据开始加载 MySql的第0 条是第一条 $.get("http://localhost:8080/findByPage",{"pageNum":pageNum}, function (date) { //查出来的数据填充到div中 addBox(date); }); //点击“点击加载更多”的时候 $("#divAdd").click(function() { //发起一个跨域的请求 每次请求5条数据 每次从当前条数的后5条数据开始查(Hibernate提供的分页查询的方法) $.get("http://localhost:8080/findByPage",{"pageNum":pageNum+=5}, function (date) { addBox(date); }); }); function addBox(date){ $.each(date,function(index,obj){ $("#box").append("<div class='box'>"+ "<div class='div2'>ID:"+obj.sid+"</div>"+ "<div class='div1'>姓名:"+obj.stuName+"</div>"+ "<div class='div1'>班级:"+obj.team.teamName+"</div>"+ "</div>"); }); } }); </script> </head> <body> <div id="box"> </div> <h4 id="divAdd">点击加载更多。。。</h4> </body> </html>
运行效果:
初始化先查出5条数据
点击"加载更多时",又从后台查出5条数据
5.0.2(下滑加载更多 upmore.html)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no"> <title>Title</title> <script src="myjs/jquery-1.11.0.js"></script> <style> #box .box { width: 100%; height: 100px; padding: 10px 0; border: 1px slateblue solid; border-left:none; border-right: none; font-family: "Microsoft YaHei"; } .div2 { margin-top: -1px } </style> <script type="text/javascript"> $(function () { //定义一个成员变量 //从第一条开始查 var pageNum = 0; //页面一加载 从第0 条数据开始加载 MySql的第0 条是第一条 $.get("http://localhost:8080/findByPage", {"pageNum": pageNum}, function (date) { //查出来的数据填充到div中 addBox(date); }); //鼠标滚动事件 $(window).scroll(function () { if ($(document).scrollTop() >= $(document).height() - $(window).height()) { //当页面移动到最底部的时候 //发起一个请求 ,每一次请求查询3条记录 $.get("http://localhost:8080/findByPage", {"pageNum": pageNum += 3}, function (date) { addBox(date); }); } }); function addBox(date) { $.each(date, function (index, obj) { $("#box").append("<div class='box'>" + "<div class='div2'>ID:" + obj.sid + "</div>" + "<div class='div1'>姓名:" + obj.stuName + "</div>"+ "</div>"); }); } }); </script> </head> <body> <div id="box"> </div> </body> </html>
运行效果:
页面加载 查出5条数据显示在页面上:
当滚动条滑到最底端的时候,又发起一个请求 去查询出5条数据
项目整体结构如下: