项目搭建工具:eclipse
项目开发环境:①Windows10-64位 ②Tomcat 8.5 ③jdk1.8.0_91 ④MySql 8.0.11
jar包准备:这里不详说,自己准备不不冲突能跑起来就没啥问题。
(1)新建一个Dynamic Web Project,可命名为SSH_Template,直接点击finish按钮
(2)将选择的jar包导入到lib(/WebContent/WEB-INF/lib)中,其中包括hibernate、mysql-connector-java、spring、struts2
(3)将导入的jar包添加到项目Libraries中,项目右键==》Properties==》Java Build Path==》Libraries==》选中导入的所有jar包添加到进Libraries中
(4)在/WebContent/WEB-INF/下新建一个web.xml,配置过滤器和监听器
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>ssh</display-name> <welcome-file-list> <welcome-file>index.action</welcome-file> </welcome-file-list> <!-- struts 过滤器 --> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 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> </web-app>
开始搭建
(1)创建用于分层的四个基础包,并分别添加BookCard的操作类
(2)根据数据库表的字段编写BookCard(实体类)和BookCard.hbm.xml(映射文件)放到ssh.entity包里
package ssh.entity; import java.math.BigDecimal; import java.sql.Date; public class BookCard { private int cid; private String name; private String sex; private Date cardDate; private BigDecimal deposit; //押金 //get set方法 public int getCid() { return cid; } public void setCid(int cid) { this.cid = cid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getCardDate() { return cardDate; } public void setCardDate(Date cardDate) { this.cardDate = cardDate; } public BigDecimal getDeposit() { return deposit; } public void setDeposit(BigDecimal deposit) { this.deposit = deposit; } }
BookCard.hbm.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="ssh.entity.BookCard" table="BookCard"> <id name="cid" column="cid"> <generator class="native"></generator> </id> <property name="name" column="name"></property> <property name="sex" column="sex"></property> <property name="cardDate" column="cardDate"></property> <property name="deposit" column="deposit"></property> </class> </hibernate-mapping>
(3)在ssh.dao包里编写BookCardDao(接口类)和BookCardDaoImpl(实现类)。
BookCardDao.java
package ssh.dao; import java.util.List; import ssh.entity.BookCard; public interface BookCardDao { public List<BookCard> getAllBookCard(); }
BookCardDaoImpl.java
package ssh.dao; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import ssh.entity.BookCard; public class BookCardDaoImpl implements BookCardDao { //在SSH的设计理念:要使用某个实例,那么就定义声明一个对象,然后 //给它添加set方法(用于spring注入进来) //实现不要关注这个实例来自于那里,以及怎么创建,或者它是谁 private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Override public List<BookCard> getAllBookCard() { //sessionFactory这个实例可以自己按常规的hibernate传统写法创建 //也可以交给spring去托管 Configuration cfg = new Configuration().configure(); sessionFactory = cfg.buildSessionFactory(); //获取session Session session = sessionFactory.openSession(); //后面当使用JPA的时候,EntityManager 类似于 Session Query query = session.createQuery("from BookCard"); //将所有的数据查询出来并放到List集合里 List<BookCard> list = query.list(); //将集合遍历循环 for(BookCard bookCard:list){ //打印输出到控制台 System.out.println(bookCard); } //关闭session session.close(); //关闭sessionFactory sessionFactory.close(); //返回list集合 return list; } }
(4)在ssh.service包里编写BookCardService(接口类)和BookCardServiceImpl(实现类)。
BookCardService.javapackage ssh.service; import java.util.List; import ssh.entity.BookCard; public interface BookCardService { public List<BookCard> getAllBookCard(); }
BookCardServiceImpl.java
package ssh.service; import java.util.List; import ssh.dao.BookCardDao; import ssh.entity.BookCard; public class BookCardServiceImpl implements BookCardService{ //dao实例使用注入方式 private BookCardDao id; //用于注入使用 public void setId(BookCardDao id) { this.id = id; } @Override public List<BookCard> getAllBookCard() { //本类应该编写业务逻辑的代码, //但本例没有业务逻辑,就不用写。 //访问数据库的代码,不会出现在service这一层 //交给dao来操作数据库 List<BookCard> myBookCardList = id.getAllBookCard(); //进行其它的业务逻辑操作,比如增加多一个选项,是否过期 //本例不需要 //.... return myBookCardList; } }
(5)在ssh.action包里编写IndexAction(action类)。
IndexAction.java
package ssh.action; import java.text.DecimalFormat; import java.util.List; import ssh.entity.BookCard; import ssh.service.BookCardService; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; //创建IndexAction(action类)继承ActionSupport接口 public class IndexAction extends ActionSupport { private static final long serialVersionUID = 1L; //声明service,但不给它创建具体的实现类的实例, private BookCardService is = null; //添加set()方法 public void setIs(BookCardService is) { this.is = is; } //编写execute()方法 public String execute() { //获取IndexService实例,调用getAllBookCard()方法 //将结果保存到List集合里 List<BookCard> myBookCardList = is.getAllBookCard(); //将查询出来的结构集打印到控制台 System.out.println("结果集:"+myBookCardList.size()); //获取Context上下文对象 ActionContext ac = ActionContext.getContext(); //将myBookCardList集合添加到上下文对象里 ac.put("myBookCardList", myBookCardList); //返回一个字符串 return "success"; } //金额格式转换 public String formatDouble(double s){ DecimalFormat fmat=new DecimalFormat("u00A4##.0"); return fmat.format(s); } }
(6)在/src/目录下新建配置文件struts.xml、applicationContext.xml、hibernate.cfg.xml
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"> <!-- 上面的头,注意版本,从样例里复制过来 showcase.warWEB-INFsrcjavastruts.xml --> <struts> <!-- 告知Struts2运行时使用Spring来创建对象 --> <constant name="struts.objectFactory" value="spring" /> <package name="default" namespace="/" extends="struts-default"> <action name="Index" class="myIndexAction"> <result name="success">/jsp/index.jsp</result> </action> </package> </struts>
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:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd 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/jee http://www.springframework.org/schema/jee/spring-jee.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="configLocation" value="classpath:hibernate.cfg.xml"></property> <property name="mappingLocations" value="classpath:ssh/entity/BookCard.hbm.xml"></property> </bean> <bean id="myIndexDao" class="ssh.dao.BookCardDaoImpl" scope="prototype"> <!-- 把sessionFactory 注入给IndexDao --> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- myIndexService = new ssh_01.service.IndexServiceImpl() --> <bean id="myIndexService" class="ssh.service.BookCardServiceImpl" scope="prototype"> <property name="id" ref="myIndexDao"/> </bean> <!-- 类似于财务部门一样,类就是钱,所有需要类的实例都由spring去管理 --> <bean id="myIndexAction" class="ssh.action.IndexAction" scope="prototype"> <!-- setIs(myIndexService) --> <property name="is" ref="myIndexService"/> </bean> </beans>
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- 第一部分:配置数据库信息,必须的 --> <property name="hibernate.connection.driver_class"> com.mysql.jdbc.Driver </property> <property name="hibernate.connection.url"> jdbc:mysql://localhost:3306/book </property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <!-- 配置当前session上下文 --> <property name="current_session_context_class">thread</property> <!-- 第二部分:配置hibernate的信息,可选的 --> <!-- 输出底层sql语句 --> <property name="hibernate.show_sql">true</property> <!-- 输出底层sql语句格式 --> <property name="hibernate.format_sql">true</property> <!-- hibernate帮创建表,需要配置之后 update:如果表已经存在,更新;如果不存在,就创建 --> <property name="hibernate.hbm2ddl.auto">update</property> <property name="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </property> <!-- 第三部分:把映射文件放在核心配置文件中 必须的 --> <mapping resource="ssh/entity/BookCard.hbm.xml" /> </session-factory> </hibernate-configuration>
(6)最后还有一个页面文件,页面文件根据习惯放哪里都行。
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="/struts-tags" prefix="s" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <table border="1"> <tr> <td>卡号</td> <td>姓名</td> <td>性别</td> <td>办卡日期</td> <td>押金</td> </tr> <s:iterator value="#myBookCardList" status="bcs"> <tr> <td><s:property value="cid"></s:property></td> <td><s:property value="name"></s:property></td> <td><s:property value="sex"></s:property></td> <td><s:date name="cardDate" format="yyyy年MM月dd日"></s:date></td> <%-- <td><s:property value="deposit"></s:property></td> --%> <td><s:property value="%{formatDouble(deposit)}"></s:property></td> </tr> </s:iterator> <!-- 如果查询出来没有数据 --> <s:if test="myBookCardList.size()==0"> <tr> <td colspan="7">没有查询到数据</td> </tr> </s:if> </table> </body> </html>
大功告成效果图
此案例根据简书上(地址如下)修改而成非常感谢。
链接:https://www.jianshu.com/p/69030f8f5437
最后编辑时间:2018.12.20 21:04:10
作者:周老一员
至于为什么修改,原因是按照他的我没跑出来。错误如下:
替换jar以及修改部分东西运行成功。现在看来应该是jar问题。