struts2+hibernate+spring注解实现

说明:三大框架全部基于注解实现,用eclipse开发,maven管理(maven的安装配置这里不做讲解)

1. 新建maven项目:


2. 先构建一下项目的目录:

src/main下新建resources(放配置文件)和webapp两个文件夹,在webapp目录下新建WEB-INF,在WEB-INF目下新建contentstruts2用到,文件名可以修改,但修改后需要配置)文件夹和web.xml文件。 

1web.xml代码如下:

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

<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

  <display-name>SSHdisplay-name>

 

  <filter>

        <filter-name>struts2filter-name>

<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilterfilter-class>

 filter>

<filter-mapping>

        <filter-name>struts2filter-name>

        <url-pattern>/*url-pattern>

filter-mapping>  

    

 

<context-param>

<param-name>contextConfigLocationparam-name>

<param-value>classpath*:/applicationContext.xmlparam-value>

context-param>

<listener>

<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>

listener> 

web-app>

2)看到上面红色字没,就要在resources目录下新建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:context="http://www.springframework.org/schema/context"

    xmlns:util="http://www.springframework.org/schema/util"

    xmlns:aop="http://www.springframework.org/schema/aop"

    xmlns:tx="http://www.springframework.org/schema/tx"

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

              http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd

              http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd

              http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd

              http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"

default-autowire=byName defaule-lazy-init=true>这句不加会出问题-->

<description>Spring公共配置文件 description>  

 <bean

class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />

<property name="ignoreResourceNotFound" value="true" />

<property name="locations">

<list>

<value>classpath*:/application.propertiesvalue> 

list>

property>

bean>   

<bean id="nativeJdbcExtractor"

class="org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor" lazy-init="true" />

<bean id="lobHandler" class="org.springframework.jdbc.support.lob.OracleLobHandler"

lazy-init="true">

<property name="nativeJdbcExtractor">

<ref local="nativeJdbcExtractor" />

property>

bean>

    <context:component-scan base-package="com.syz.ssh.entity,com.syz.ssh.action,com.syz.ssh.service.*,com.syz.ssh.dao.*" />  

    

    

    <bean id="dataSource"

class="org.springframework.jdbc.datasource.DriverManagerDataSource">

<property name="driverClassName" value="${jdbc.driver}" /> 

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

<property name="username" value="${jdbc.username}" />

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

bean>

 

<bean id="sessionFactory"

class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">

      

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

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

<property name="namingStrategy">

<bean class="org.hibernate.cfg.ImprovedNamingStrategy" />

property>

<property name="hibernateProperties">

<props>

<prop key="hibernate.dialect">${hibernate.dialect}prop>  

<prop key="hibernate.show_sql">${hibernate.show_sql}prop>

<prop key="hibernate.format_sql">${hibernate.format_sql}prop>

<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProviderprop>   

 <prop key="hibernate.cache.use_query_cache">trueprop>

 props>

property>

<property name="packagesToScan" value=" com.syz.ssh.entity" />

bean> 

 

     

    <bean id="transactionManager"

class="org.springframework.orm.hibernate3.HibernateTransactionManager">

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

   bean>

  

 <tx:annotation-driven transaction-manager="transactionManager" />

beans>

3)看到上面红色字体没,就要在resources目录下新建application.properties文件,代码如下:

#jdbc settings

#jdbc.driver=oracle.jdbc.driver.OracleDriver

#jdbc.url=jdbc:oracle:thin:@192.168.3.216:1522:orcl

#jdbc.username=suqiutest

#jdbc.password=suqiutest

#hibernate settings

#hibernate.show_sql=true

#hibernate.format_sql=false

#hibernate.generate_statistics=true

#vhibernate.dialect=org.hibernate.dialect.Oracle10gDialect

 

 

#jdbc settings

jdbc.driver=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://localhost:3306/test

jdbc.username=root

jdbc.password=1111

#hibernate settings

hibernate.dialect=org.hibernate.dialect.MySQLDialect

hibernate.show_sql=true

hibernate.format_sql=false

其中橙色部分是oracle的连接,根据需要选择相应的数据库。

4)在resources目录下新建log4j.properties

# Output pattern : date [thread] priority category - message

log4j.rootLogger=debug,stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=%d [%t] %-5p %c - %m%n

log4j.logger.org.springframework.beans.factory.annotation=debug,stdout

 

log4j.appender.F = org.apache.log4j.DailyRollingFileAppender

log4j.appender.F.file=d:\\login.log

log4j.appender.F.DatePattern='.'yyyy-MM-dd

log4j.appender.F.layout=org.apache.log4j.PatternLayout

log4j.appender.F.layout.ConversionPattern= %5r %-5p %c{2} - %m%n

文件内容根据需要自行修改

5)在resources目录下新建struts.xml (配置一些struts2的拦截器之类的,先可以什么都不配)代码如下:

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

DOCTYPE struts PUBLIC

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

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

<struts>

  下面配置就会可以用appcontact_list来访问appcontact-list这个action,默认是用一横appcontact-list来访问-->

<constant name="struts.convention.action.name.separator" value="_"/>

struts>

其他公共的返回页面或者注解的配置可以自行参考资料加上去

6)接下来就把项目需要的包通过maven下载过来

配置pom.xml文件,头部的

<groupId>com.syz.sshgroupId>

  <artifactId>testartifactId>

  <version>0.0.1-SNAPSHOTversion>

  <packaging>jarpackaging>

要改成

<groupId>com.syz.sshgroupId>

  <artifactId>testartifactId>

  <version>0.0.1-SNAPSHOTversion>

  <packaging>warpackaging>

就是把jar改成war这样就打包成war包,才能变成web项目。

具体代码如下:

<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.0modelVersion>

  <groupId>com.syz.sshgroupId>

  <artifactId>testartifactId>

  <version>0.0.1-SNAPSHOTversion>

  <packaging>warpackaging>

  <name>testname>

  <url>http://maven.apache.orgurl>

  <properties>

    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>

  properties>

  <dependencies>

    <dependency>

      <groupId>junitgroupId>

      <artifactId>junitartifactId>

      <version>3.8.1version>

      <scope>testscope>

    dependency>

    

      

       org.apache.struts

       struts2-core

       2.2.1

      

      

        org.apache.struts

        struts2-convention-plugin

        2.1.8

      

      

        org.apache.struts

        struts2-spring-plugin

        2.0.9

      

      

    javax.persistence

    persistence-api

    1.0

      

      

   javassist

   javassist

   3.8.0.GA

   pom

      

    

      org.springframework

      spring-orm

      3.0.0.RELEASE

      jar

         compile

      

      

   org.springframework

   spring

   2.5.6.SEC03

      

      

      org.springframework

      spring-test

      3.0.0.RELEASE

      jar

      compile

      

      

   org.springframework

   spring-context

   3.0.0.RELEASE

   runtime

      

 

 

      org.hibernate

      hibernate-annotations

      3.3.0.ga

      jar

      compile

      

      

      org.hibernate

      hibernate-commons-annotations

      3.3.0.ga

      jar

      compile

      

      

        org.hibernate

        hibernate

        3.5.4-Final

        pom

        compile

      

   

   

 <dependency> 

          <groupId>log4jgroupId> 

          <artifactId>log4jartifactId> 

          <version>1.2.14version> 

      dependency> 

      <dependency> 

          <groupId>org.slf4jgroupId> 

          <artifactId>slf4j-apiartifactId> 

          <version>1.6.1version> 

      dependency> 

      <dependency> 

          <groupId>org.slf4jgroupId> 

          <artifactId>slf4j-log4j12artifactId> 

          <version>1.6.1version> 

      dependency> 

      <dependency> 

          <groupId>org.slf4jgroupId> 

          <artifactId>slf4j-nopartifactId> 

          <version>1.6.1version> 

      dependency>

      

         mysql

         mysql-connector-java

         5.1.9

      

      

  com.oracle

  classes12

  10.2.0.2.0

    

  -数据库需要用到的包,自行选择一个 -->

dependencies>

project>

7)新建各个包(actionservicedaoentity等)

目录结构如下:

至此,项目的目录构建完毕。

然后把maven变成web项目,在黑窗口中进入项目目录,执行一下命令行:

mvn eclipse:clean 

mvn -Dwtpversion=2.0 eclipse:eclipse

3.接下来进行编码(目的是在页面上输出数据库person表里的数据)

1)先在数据库里创建person

CREATE TABLE `person1` (

  `Id` varchar(11) NOT NULL DEFAULT '',

  `name` varchar(255) DEFAULT NULL,

  `age` int(11) DEFAULT NULL,

  PRIMARY KEY (`Id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2)编写Person.java,代码如下:

package com.syz.ssh.entity;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.Id;

import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

@Entity

//注意不是hibernate

@Table(name = "PERSON")

//注意不是hibernate

public class Person {

public String pid;

public String name;

public Integer age;

 //实体类的idid生成策略是uuid

@Id

@Column(name = "ID", unique = true, nullable = false, length = 32)

@GeneratedValue(generator = "paymentableGenerator")

@GenericGenerator(name = "paymentableGenerator", strategy = "uuid")

public String getPid() {

return pid;

}

public void setPid(String pid) {

this.pid = pid;

}

@Column(name = "name", length = 255)

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

@Column(name = "age", precision = 11, scale = 0)

public Integer getAge() {

return age;

}

public void setAge(Integer age) {

this.age = age;

}

}

3)编写PersonAction.java

package com.syz.ssh.action;

import java.util.ArrayList;

import java.util.List;

import org.apache.struts2.convention.annotation.Action;

import org.apache.struts2.convention.annotation.Result;

import org.apache.struts2.convention.annotation.Results;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Qualifier;

import org.springframework.context.annotation.Scope;

import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;

import com.syz.ssh.entity.Person;

import com.syz.ssh.service.PersonService;

@Controller

@Scope("prototype")

@Results( {

@Result(name = "sucess", type = "dispatcher", location = "person-list.jsp"),

     }

)

public class PersonAction extends ActionSupport {

private static final long serialVersionUID = 1L;

//Service接口接入

@Autowired

@Qualifier("personServiceImpl")

private PersonService personService

 List list=new ArrayList();

 

@Action(value = "person-list")

public String list() throws Exception {

        list =personService.list();

return SUCCESS;

}

  public List getList() {

return list;

}

      public void setList(List list) {

this.list = list;

}

}

PersonService.java

package com.syz.ssh.service;

import java.util.List;

import com.syz.ssh.entity.Person;

public interface PersonService {

List list();

}

PersonServiceImpl.java

package com.syz.ssh.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Qualifier;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

import com.syz.ssh.dao.PersonDao;

import com.syz.ssh.entity.Person;

import com.syz.ssh.service.PersonService;

@Service

@Transactional

public class PersonServiceImpl implements PersonService{

 @Autowired

 @Qualifier("personDaoImpl"

public PersonDao personDao;

  

public List list() {

List ll = personDao.list();

return ll;

}

}

PersonDao.java

package com.syz.ssh.dao;

import java.util.List;

import com.syz.ssh.entity.Person;

public interface PersonDao {

   public List list();

}

PersonDaoImpl.java

package com.syz.ssh.dao.impl;

import java.util.List;

import org.hibernate.HibernateException;

import org.hibernate.Query;

import org.hibernate.Session;

import org.springframework.orm.hibernate3.HibernateCallback;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

import com.syz.ssh.dao.PersonDao;

import com.syz.ssh.entity.Person;

@Service("personDaoImpl")

@Transactional

public class PersonDaoImpl extends HibernateDaoSupport implements PersonDao{

    @SuppressWarnings("unchecked")

@Transactional(readOnly = true)

public List list() {

return (List) getHibernateTemplate().executeWithNativeSession(

new HibernateCallback() {

public Object doInHibernate(Session session)

throws HibernateException {

Query query = session.createQuery("from Person  as obj");

return query.list();

  }

     });

 }

}

最后在content目录下新建person-list.jsp代码如下:

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

pageEncoding="utf-8"%>

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

DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<title>Hello World!title>

head>

<body>

<s:iterator value="list">

 <s:property value="name"/>

s:iterator>

     

body>

html>

最终循环输出数据库中person表中的name字段。

至此ssh项目全部完成。




你可能感兴趣的:(SSH,hibernate,struts,spring,autowired,resources,maven)