说明:三大框架全部基于注解实现,用eclipse开发,maven管理(maven的安装配置这里不做讲解)
1. 新建maven项目:
2. 先构建一下项目的目录:
src/main下新建resources(放配置文件)和webapp两个文件夹,在webapp目录下新建WEB-INF,在WEB-INF目下新建content(struts2用到,文件名可以修改,但修改后需要配置)文件夹和web.xml文件。
(1)web.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>SSH</display-name>
<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 ApplicationContext配置文件的路径,可使用通配符,多个路径用,号分隔
此参数用于后面的Spring Context Loader ,配置spring上下文(可选)-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:/applicationContext.xml</param-value>
</context-param>
<!--加入spring支持-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-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.properties</value>
</list>
</property>
</bean>
<!-- 持久化用到springJDBC,涉及到长文章类型字段的操作 -->
<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>
<!-- 使用annotation 自动注册bean(需要用到的包),并保证@Required,@Autowired的属性被注入 -->
<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>
<!-- Hibernate配置 -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<!-- 配置Hibernate拦截器,用于同步索引-->
<!--<property name="entityInterceptor" ref="luceneEntityInterceptor" />-->
<property name="dataSource" ref="dataSource" />
<property name="lobHandler" ref="lobHandler" />
<property name="namingStrategy">
<bean class="org.hibernate.cfg.ImprovedNamingStrategy" />
</property>
<property name="hibernateProperties">
<props>
<!-- 配置Hibernate SQL方言,可以根据版本,下面的通用 -->
<!-- <prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop> -->
<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.EhCacheProvider</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
</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>
<!-- 使用annotation定义事务,这句不加貌似也可以 -->
<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.ssh</groupId>
<artifactId>test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
要改成
<groupId>com.syz.ssh</groupId>
<artifactId>test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
就是把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.0</modelVersion>
<groupId>com.syz.ssh</groupId>
<artifactId>test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>test</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-convention-plugin</artifactId>
<version>2.1.8</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-spring-plugin</artifactId>
<version>2.0.9</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.8.0.GA</version>
<type>pom</type>
</dependency>
<!-- struts2需要用到的包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.0.0.RELEASE</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>2.5.6.SEC03</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.0.0.RELEASE</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.0.0.RELEASE</version>
<scope>runtime</scope>
</dependency>
<!-- spring需要用到的包 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.3.0.ga</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.3.0.ga</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
<version>3.5.4-Final</version>
<type>pom</type>
<scope>compile</scope>
</dependency>
<!-- hibernate需要用到的包 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-nop</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>classes12</artifactId>
<version>10.2.0.2.0</version>
</dependency>
<!—-数据库需要用到的包,自行选择一个 -->
</dependencies>
</project>
(7)新建各个包(action,service,dao,entity等)
目录结构如下:
至此,项目的目录构建完毕。
然后把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;
//实体类的id,id生成策略是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<Person> list=new ArrayList<Person>();
@Action(value = "person-list")
public String list() throws Exception {
list =personService.list();
return SUCCESS;
}
public List<Person> getList() {
return list;
}
public void setList(List<Person> 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<Person> 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<Person> list() {
List<Person> 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<Person> 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<Person> list() {
return (List<Person>) getHibernateTemplate().executeWithNativeSession(
new HibernateCallback<Object>() {
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项目全部完成。