idea:ssh整合小例子:读取数据库信息显示到jsp上面

1.idea创建项目:很方便,在下面添加各自的jar包,注意点:hibernate和struts2都有一个javassiste的jar包,把低级的删掉即可,因为有两个的时候,会有转换异常

idea会帮你配置好基本的信息。

jar包一览:

2.首先,在大佬web.xml配置好加载各小弟的配置信息:idea帮忙生成的


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

<?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">

    <!--读取spring配置-->

    <context-param>

        <param-name>contextConfigLocation</param-name>

        <param-value>classpath:applicationContext.xml,classpath:applicationContext-beans.xml</param-value>

    </context-param>

    <!--struts2配置-->

    <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>

    <!--listener-->

    <listener>

        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

    </listener>

</web-app>

3.把hibernate搞到spring的容器中去......(已经写过这一方面的内容,就不详细了,直接贴代码  )

applicationContext.xml这个文件是配置hibernate与spring的整合信息的


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

<?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:aop="http://www.springframework.org/schema/aop"

       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/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">

    <context:property-placeholder location="classpath:db.properties"/>

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">

        <property name="user" value="${user}"/>

        <property name="password" value="${password}"/>

        <property name="driverClass" value="${driveClass}"/>

        <property name="jdbcUrl" value="${url}"/>

    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">

        <property name="dataSource" ref="dataSource"/>

        <property name="mappingLocations" value="classpath:*.hbm.xml"/>

        <property name="hibernateProperties">

            <props>

                <prop key="hibernate.format_sql">true</prop>

                <prop key="hibernate.show_sql">true</prop>

                <prop key="hibernate.hbm2ddl.auto">update</prop>

                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>

            </props>

        </property>

    </bean>

    <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">

        <property name="sessionFactory" ref="sessionFactory"/>

    </bean>

    <aop:config>

        <aop:pointcut id="pointCut" expression="execution(* com.service.*.*(..))"/>

        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointCut"/>

    </aop:config>

    <tx:advice id="txAdvice" transaction-manager="transactionManager">

        <tx:attributes>

            <tx:method name="get*" read-only="true"/>

            <tx:method name="*"/>

        </tx:attributes>

    </tx:advice>

</beans>

db.properties


1

2

3

4

user=root

password=

driveClass=com.mysql.jdbc.Driver

url=jdbc:mysql://localhost:3306/ssh?useUnicode=true&characterEncoding=UTF-8

为完善上面这个配置文件,需要生产bean类和mapping映射文件:

Department.java

Employee.java

Department.hbm.xml

Employee.hbm.xml


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

package com.entities;

import javax.persistence.Basic;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.Id;

@Entity

public class Department {

    private int id;

    private String departmentname;

    @Id

    @Column(name = " ID", nullable = false)

    public int getId() {

        return id;

    }

    public void setId(int id) {

        this.id = id;

    }

    @Basic

    @Column(name = "DEPARTMENTNAME", nullable = true, length = 255)

    public String getDepartmentname() {

        return departmentname;

    }

    public void setDepartmentname(String departmentname) {

        this.departmentname = departmentname;

    }

    

}


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

package com.entities;

import javax.persistence.*;

import java.util.Date;

@Entity

public class Employee {

    private int id;

    private String lastname;

    private String email;

    private Date birth;

    private Date createtime;

    private Department department;

    @Id

    @Column(name = "ID", nullable = false)

    public int getId() {

        return id;

    }

    public void setId(int id) {

        this.id = id;

    }

    @Basic

    @Column(name = "LASTNAME", nullable = true, length = 255)

    public String getLastname() {

        return lastname;

    }

    public void setLastname(String lastname) {

        this.lastname = lastname;

    }

    @Basic

    @Column(name = "EMAIL", nullable = true, length = 255)

    public String getEmail() {

        return email;

    }

    public void setEmail(String email) {

        this.email = email;

    }

    @Basic

    @Column(name = "BIRTH", nullable = true)

    public Date getBirth() {

        return birth;

    }

    public void setBirth(Date birth) {

        this.birth = birth;

    }

    @Basic

    @Column(name = "CREATETIME", nullable = true)

    public Date getCreatetime() {

        return createtime;

    }

    public void setCreatetime(Date createtime) {

        this.createtime = createtime;

    }

    @Basic

    @Column(name = "DEPARTMENT_ID", nullable = true)

    public Department getDepartment() {

        return department;

    }

    public void setDepartment(Department department) {

        this.department = department;

    }

}


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

<?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="com.entities.Department" table="department" schema="ssh">

        <id name="id">

            <column name=" ID" sql-type="int(11)"/>

            <generator class="native"/>

        </id>

        <property name="departmentname">

            <column name="DEPARTMENTNAME" sql-type="varchar(255)" not-null="true"/>

        </property>

    </class>

</hibernate-mapping>


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

<?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="com.entities.Employee" table="employee" schema="ssh">

        <id name="id">

            <column name="ID" sql-type="int(11)"/>

            <generator class="native"/>

        </id>

        <property name="lastname">

            <column name="LASTNAME" sql-type="varchar(255)" not-null="true"/>

        </property>

        <property name="email">

            <column name="EMAIL" sql-type="varchar(255)" not-null="true"/>

        </property>

        <property name="birth">

            <column name="BIRTH" sql-type="date" not-null="true"/>

        </property>

        <property name="createtime">

            <column name="CREATETIME" sql-type="date" not-null="true"/>

        </property>

        <many-to-one name="department" class="com.entities.Department">

            <column name="DEPARTMENT_ID"/>

        </many-to-one>

    </class>

</hibernate-mapping>

至此:打开Tomcat来运行,如果各方面配置没问题,就可以自动生成数据表了。

3.开始操作数据:写一个业务获取数据(数据由自己填充 )

EmployeeDao.java

这里的sessionfactory通过set的方法获取.....  set方法把该类注入到bean管理器,获得sessionfactory


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

package com.service;

import com.entities.Employee;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import java.util.List;

public class EmployeeDao {

    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {

        this.sessionFactory = sessionFactory;

    }

    public Session getSession() {

        return sessionFactory.getCurrentSession();

    }

    public List<Employee> getAll() {

        //      左向外联获取department信息,fetch获取单一信息,不用获取一大堆

        String hql = "from Employee e left outer join fetch e.department";

        return getSession().createQuery(hql).list();

    }

}

再写一个service把上面的业务结果中转(自己形象地 理解 )

EmployeeService.java


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

package com.service;

import com.entities.Employee;

import java.util.List;

public class EmployeeService {

    private EmployeeDao employeeDao;

    public void setEmployeeDao(EmployeeDao employeeDao) {

        this.employeeDao = employeeDao;

    }

    public List<Employee> getAll() {

        return employeeDao.getAll();

    }

}

4.到了这里,就需要写struts2的东西了,首先    在web的开始页面写一个action超链接


1

2

3

4

5

6

7

8

9

10

11

12

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>

<head>

    <title>$Title$</title>

</head>

<body>

<a href="emp-list">List all Employees</a>

</body>

</html>

实现这个效果,点击后就出现查询结果:

接着需要实现这个挑战的action,需要在struts.xml中注册这个action的信息,这里用通配符共用这个action

struts.xml

这里的employeeAction就是spring中已经注入的bean的id


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC

        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"

        "http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

    <!--打开开发者模式,如有bug会显示之类,不过也消耗性能-->

    <constant name="struts.devMode" value="true"/>

    <!--关闭动态方法调用,这样就不能在浏览器通过调用类方法来调用action了-->

    <constant name="struts.enable.DynamicMethodInvocation" value="false"/>

    <!--引用默认配置-->

    <package name="default" extends="struts-default">

        <!--通配符表示多种类似的方法共用一个模块,这里就是数据交互出,自己的理解-->

        <action name="emp-*" class="employeeAction" method="{1}">

            <result name="list">/WEB-INF/pages/emp-list.jsp</result>

        </action>

    </package>

</struts>

再写一个关于处理与struts相关bean的spring容器文件,其实是一个样的

applicationContext-beans.xml


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--通过set方法把emplayDao注入到bean中,在EmployeeDao使用到sessionFactory-->

    <bean id="employeeDao" class="com.service.EmployeeDao">

        <property name="sessionFactory" ref="sessionFactory"/>

    </bean>

    <!--同上-->

    <bean id="employeeService" class="com.service.EmployeeService">

        <property name="employeeDao" ref="employeeDao"/>

    </bean>

    <!--配置action,这里在struts.xml的action会与此绑定,进行数据交互,scope="prototype"确保每个请求都是一个新的action,不能使用单例,那样的话,就会出现信息错乱-->

    <bean id="employeeAction" class="com.actions.EmployeeAction" scope="prototype">

        <property name="employeeService" ref="employeeService"/>

    </bean>

</beans>

最后,就需要写数据的交汇点,EmployeeAction.java了

这里就把EmployeeService.java查询得来的数据写入到值栈中,一边在jsp中读取并且显示..


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

package com.actions;

import com.opensymphony.xwork2.ActionSupport;

import com.service.EmployeeService;

import org.apache.struts2.interceptor.RequestAware;

import java.util.Map;

public class EmployeeAction extends ActionSupport implements RequestAware {

    private EmployeeService employeeService;

    public void setEmployeeService(EmployeeService employeeService) {

        this.employeeService = employeeService;

    }

    public String list() {

        request.put("employee", employeeService.getAll());

        return "list";

    }

    private Map<String, Object> request;

    @Override

    public void setRequest(Map<String, Object> map) {

        this.request = map;

    }

}

最后完善显示结果的jsp文件:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%@taglib prefix="s" uri="/struts-tags" %>

<html>

<head>

    <title>Title</title>

</head>

<body>

<h4>Employee List Page</h4>

<s:if test="#request.employee==null||request.employee.size()==0">

    没有任何员工信息

</s:if>

<s:else>

    <table border="1" cellpadding="2" cellspacing="0">

        <tr>

            <td>ID</td>

            <td>LAST_NAME</td>

            <td>E_MAIL</td>

            <td>BIRTH</td>

            <td>CREATE_TIME</td>

            <td>DEPARTMENT</td>

        </tr>

        <s:iterator value="#request.employee">

            <tr>

                <td>${id}</td>

                <td>${lastname}</td>

                <td>${email}</td>

                <td>${birth}</td>

                <td>${createtime}</td>

                <td>${department.departmentname}</td>

            </tr>

        </s:iterator>

    </table>

</s:else>

</body>

</html>

6.文件一览:

运行结果:

来自为知笔记(Wiz)

时间: 2024-10-10 06:11:07

idea:ssh整合小例子:读取数据库信息显示到jsp上面的相关文章

SpringMVC+hibernate整合小例子,用户的增删查改

SpringMVC+hibernate整合小例子,用户的增删查改 对于使用框架写项目,我的第一反应的把所有需要的jar文件引入. 因为我用的是JDK1.8,当使用spring3.2 注解的时候会出现问题,所以最终使用的spring4.0.  hibernate使用的版本为4.0 .至于一些依赖包的版本就是看别人的资料拿的. 然后看下整体的项目结构 第一步写的是web.xml配置文件,当然有写东西是后面加上去的,不是一步到位的,比如说控制post方式的乱码.以及无法时候JS文件等一些静态文件,后面

SSH整合简单例子

说明:简单SSH整合,struts版本2.3.32,spring版本3.2.9,hibernate版本3.6.10 一.开发步骤 1 引jar包,创建用户library.使用的包和之前博文相同,可以参考spring和hibernate整合,事务管理,struts和spring整合 jar包如下 //struts_core Struts2.3.32core\commons-fileupload-1.3.2.jar Struts2.3.32core\commons-io-2.2.jar Struts

web学习:Spring2.5+Hibernate3.3+Struts1.3整合小例子

写android有段时间了,感觉思维越写越狭窄,考虑问题越来越局限了,看不到一个项目整体的设计和构架,觉得很有必要多多写一些大型的框架性的东西来提高自己的视野. 从接触java到现在一年多了,在我的印象里,struts好像是用来接收请求然后处理,将处理结果在跳转到jsp上显示的:spring就是 一个大型的工厂,专门生产业务的类:hibernate就是负责和数据库勾结,然后提供数据的.惭愧啊,我居然从来都没有用过SSH三大框架,居然我也能 鬼使神差的工作了,而且工作了这么长时间了,趁现在空暇和还

JSP慕课网阶段用户登录小例子(不用数据库)

getAttribute和setAttribute一起使用,而getParameter用于取得如request传来的参数. Web是请求/响应架构的使用,而request和response就是在服务器端生成的相应的两个对象,request能够获取客户端传递的参数及相关的一些信息,而response就是给客户端响应相关的页面及信息. request.getRequestDispatcher().forward(request.response)这个语句意思是将客户端的请求转向(forward)到g

spring小例子-springMVC+mybits整合的小例子

这段时间没更博,找房去了...   吐槽一下,自如太坑了...承诺的三年不涨房租,结果今年一看北京房租都在涨也跟着涨了... 而且自如太贵了,租不起了.. 突然有点理解女生找对象要房了..   搬家太受罪了... 今天更一下springMVC整合mybits形成最简单的网站demo. 大概效果就是这样的:左边是数据库查询结果,右边是页面访问结果: 首先,一个简单的springMVC小例子可以看这个http://www.cnblogs.com/xuejupo/p/5236448.html 这是在这

ssh整合例子

今天给大家介绍一下最新版本的SSH(struts2.2.1+ hibernate3.6+spring3.0.5)组合.注意本讲解为手工搭建! 一.为SSH做好准备 struts2-2.2.1-all.zip       hibernate-distribution-3.6.0.Final-dist.zip spring-framework-3.0.5.RELEASE.zip spring-framework-2.5.6-with-dependencies.zip slf4j-1.6.1.zip 

laravel 数据库操作小例子

public function demo() { $res = null; //insert数据插入 //$user=array('username'=>'joy','password'=>'123456','age'=>23); //$res = DB::table('users')->insert($user); /* 数据查询 $res = DB::table('users')->where('username','joy')->get(); $res = DB:

mysql+ssh整合例子,附源码下载

项目引用jar下载:http://download.csdn.net/detail/adam_zs/7262727 项目源码下载地址:http://download.csdn.net/detail/adam_zs/7262749 今天花时间把ssh整合了一下,重新再学习一下,希望对大家有所帮助! 我用的是mysql数据库,建表语句比较简单就不贴出来了,建表的时候记的设置id为自动增加哦. 项目文件位置,项目引用jar包 项目配置文件 web.xml <?xml version="1.0&q

JAVA数据库应用的一个小例子

自己随便写的,以炉石为背景,写一个参考用的小例子,先上SQL表: if OBJECT_ID('card_pool') is not null drop table card_pool; create table card_pool( card_id int identity(1,1) not null, card_name varchar(32), card_occupation varchar(32), --卡牌职业:中立.德鲁伊.猎人.法师.圣骑士.牧师.潜伏者.萨满祭司.术士.战士 car