本来我是懒得写了的,毕竟觉得ssh现在相对前景好像不怎么好了,但老是有人来问我这个框架怎么搭,而且学校课程教的也还是这个,就花了点功夫配置了下,如果有写的不好或者有问题的地方,欢迎提出。
嗯,先附上一个最后完整版的目录结构,大家可以先把缺少的文件、包新建:
新建好后,在java文件夹右键->Mark Directory as->Sources Root:
嗯,然后开始配置。
这里用 maven 来管理包,自动下载jar包
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>me.asherligroupId>
<artifactId>test_sshartifactId>
<packaging>warpackaging>
<version>1.0-SNAPSHOTversion>
<name>test_ssh Maven Webappname>
<url>http://maven.apache.orgurl>
<properties>
<spring.version>4.1.7.RELEASEspring.version>
<hibernate.version>4.3.11.Finalhibernate.version>
<struts2.version>2.3.24.1struts2.version>
<slf4j.version>1.6.6slf4j.version>
<log4j.version>1.2.12log4j.version>
<junit.version>4.10junit.version>
properties>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.11version>
<scope>testscope>
dependency>
<dependency>
<groupId>taglibsgroupId>
<artifactId>standardartifactId>
<version>1.1.2version>
dependency>
<dependency>
<groupId>jstlgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.5.4version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.1.0version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-beansartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.apache.strutsgroupId>
<artifactId>struts2-coreartifactId>
<version>${struts2.version}version>
<exclusions>
<exclusion>
<artifactId>javassistartifactId>
<groupId>javassistgroupId>
exclusion>
exclusions>
dependency>
<dependency>
<groupId>org.apache.strutsgroupId>
<artifactId>struts2-spring-pluginartifactId>
<version>${struts2.version}version>
dependency>
<dependency>
<groupId>org.apache.strutsgroupId>
<artifactId>struts2-junit-pluginartifactId>
<version>${struts2.version}version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.hibernategroupId>
<artifactId>hibernate-entitymanagerartifactId>
<version>${hibernate.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-ormartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.9version>
<scope>runtimescope>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.6version>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.8.13version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>${log4j.version}version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-apiartifactId>
<version>${slf4j.version}version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-log4j12artifactId>
<version>${slf4j.version}version>
dependency>
dependencies>
<build>
<finalName>test_sshfinalName>
build>
project>
### set log levels ###
log4j.rootLogger = INFO,D
###输出到控制台###
log4j.logger.toConsole=debug,stdout
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern =%d{yyyy-MM-dd HH\:mm\:ss} [%5p] - %c -%F(%L) -%m%n
### 输出到日志文件 ###
## 其中File 可以采用绝对路径 亦可以采用相对路径 catalina.home 是tomcat目录 如果没有logs文件夹 将会报错 ##
## 更加倾向于将日志文件放在 tomcat的日志目录下${catalina.home}/logs/salesmanb2bError.log ##
## 绝对路径如:e:/salesmanb2bError.log ##
log4j.logger.daily=INFO,D
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = ${catalina.home}/logs/test_ssh.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = INFO
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern =%d{yyyy-MM-dd HH\:mm\:ss} [%5p] - %c -%F(%L) -%m%n
##log4j.logger.org.apache.ibatis=debug,stdout
##log4j.logger.java.sql=debug,stdout
注意: 以上代码里的 ${catalina.home}/logs/test_ssh.log 就是日志生成的地方,是本tomcat的logs文件夹下,这里是以后自己配置项目的时候需要修改的地方
#hibernate.dialect=org.hibernate.dialect.OracleDialect
#driverClassName=oracle.jdbc.driver.OracleDriver
#validationQuery=SELECT 1 FROM DUAL
#jdbc_url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
#jdbc_username=gacl
#jdbc_password=xdp
hibernate.dialect=org.hibernate.dialect.MySQLDialect
driverClassName=com.mysql.jdbc.Driver
validationQuery=SELECT 1
jdbc_url=jdbc:mysql://localhost:3306/test_ssh?useUnicode=true&characterEncoding=UTF-8
jdbc_username=***********************************************
jdbc_password=***********************************************
#hibernate.dialect=org.hibernate.dialect.SQLServerDialect
#driverClassName=net.sourceforge.jtds.jdbc.Driver
#validationQuery=SELECT 1
#jdbc_url=jdbc:jtds:sqlserver://127.0.0.1:1433/sshe
#jdbc_username=sa
#jdbc_password=123456
#jndiName=java:comp/env/dataSourceName
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.use_sql_commants=true
注意: 以上代码里有三处是需要大家自己修改的
如果还不存在该数据库,可以按如下操作新建:
create database test_ssh;
ok,数据库创建完成,下一步。
<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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:config.propertiesvalue>
list>
property>
bean>
<context:component-scan base-package="me.asherli"/>
<bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${jdbc_url}"/>
<property name="username" value="${jdbc_username}"/>
<property name="password" value="${jdbc_password}"/>
<property name="driverClassName" value="${driverClassName}"/>
<property name="initialSize" value="1"/>
<property name="minIdle" value="1"/>
<property name="maxActive" value="20"/>
<property name="maxWait" value="60000"/>
<property name="timeBetweenEvictionRunsMillis" value="60000"/>
<property name="minEvictableIdleTimeMillis" value="300000"/>
<property name="validationQuery" value="SELECT 'x'"/>
<property name="testWhileIdle" value="true"/>
<property name="testOnBorrow" value="false"/>
<property name="testOnReturn" value="false"/>
<property name="poolPreparedStatements" value="true"/>
<property name="maxPoolPreparedStatementPerConnectionSize" value="20"/>
<property name="filters" value="stat"/>
bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="druidDataSource"/>
<property name="packagesToScan">
<list>
<value>me.asherli.*.modelvalue>
list>
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.use_sql_commants">${hibernate.use_sql_commants}prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}prop>
props>
property>
bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="*" read-only="true"/>
tx:attributes>
tx:advice>
<aop:config proxy-target-class="true">
<aop:pointcut id="allManagerMethod" expression="execution(* me.asherli.*.dao.impl.*.*(..))"/>
<aop:advisor pointcut-ref="allManagerMethod" advice-ref="txAdvice"/>
aop:config>
beans>
这里要注意的一点是,我直接将hibernate的配置和spring糅合在一起,省掉了传统的 Hibernate.cfg.xml 这些hibernate文件
<struts>
<constant name="struts.objectFactory" value="spring" />
<constant name="struts.i18n.encoding" value="UTF-8" />
<constant name="struts.enable.SlashesInActionNames" value="true"/>
<package name="common" extends="struts-default" namespace="/">
<action name="*/*/*" class="me.asherli.{1}.action.{2}Action" method="{3}" >
<result type="dispatcher">${url}result>
<result name="redirect" type="redirect">${url}result>
action>
package>
struts>
这里要讲的一点是,使用通配符匹配url,文件命名要规范(注意阅读代码里的注释)
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>test_sshdisplay-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring.xmlparam-value>
context-param>
<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>
<welcome-file-list>
<welcome-file>/index.jspwelcome-file>
welcome-file-list>
web-app>
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<a href="/test/main/login">登录a>
<a href="/test/main/register">注册a><br>
信息 : ${tipMessage eq null ? "无" : tipMessage}
body>
html>
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Titletitle>
head>
<body>
登录界面<br>
<form action="/test/main/login" method="post">
姓名: <input name="name" type="text"> <br>
<input type="submit" value="登录">
form>
body>
html>
register.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Titletitle>
head>
<body>
注册界面<br>
<form action="/test/main/register" method="post">
姓名: <input name="name" type="text"> <br>
性别: <input name="sex" type="radio" value="1">男 <input name="sex" type="radio" value="0">女
<input type="submit" value="注册">
form>
body>
html>
User.java
package me.asherli.test.model;
import javax.persistence.*;
@Entity
@Table(name = "ssh_user")
public class User {
@Id
@GeneratedValue
@Column
private int id;
@Column
private String name;
@Column
private Integer sex;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", sex=" + sex +
'}';
}
}
注: 对应的数据库的表会由hbernate自动生成,所以我们刚开始就新建一个空的数据库就好,剩下的由项目自己完成
package me.asherli.test.dao;
import me.asherli.test.model.User;
import java.util.List;
public interface UserDao {
public void insertBean(User user);
public void deleteBean(User user);
public void updateBean(User user);
public List selectBean(User user);
public int selectBeanCount(User user);
}
package me.asherli.test.dao.impl;
import me.asherli.test.dao.UserDao;
import me.asherli.test.model.User;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
@Autowired
public void setSessionFactory0(SessionFactory sessionFactory) {
super.setSessionFactory(sessionFactory);
}
public void insertBean(User user) {
this.getHibernateTemplate().save(user);
}
public void deleteBean(User user) {
this.getHibernateTemplate().delete(user);
}
public void updateBean(User user) {
this.getHibernateTemplate().update(user);
}
public List selectBean(User user) {
return this.getHibernateTemplate().findByExample(user);
}
public int selectBeanCount(User user) {
long count = this.getHibernateTemplate().findByExample(user).size();
return (int) count;
}
}
package me.asherli.test.action;
import com.opensymphony.xwork2.ActionSupport;
import me.asherli.test.dao.impl.UserDaoImpl;
import me.asherli.test.model.User;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@Controller
public class mainAction extends ActionSupport {
private String url = "./";
private void setUrl(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
@Autowired
private UserDaoImpl userDao;
public String index() {
HttpServletRequest request = ServletActionContext.getRequest();
this.setUrl("/index.jsp");
request.setAttribute("tipMessage", "无");
return this.SUCCESS;
}
public String login() {
HttpServletRequest request = ServletActionContext.getRequest();
String method = request.getMethod();
if (method.equals("GET")) {
this.setUrl("/login.jsp");
}
if (method.equals("POST")) {
User user = new User();
user.setName(request.getParameter("name"));
List list = userDao.selectBean(user);
if (list.size() != 0) {
request.setAttribute("tipMessage", "欢迎您," + list.get(0).getName() + (list.get(0).getSex() == 0 ? "女士" : "先生"));
} else {
request.setAttribute("tipMessage", "无");
}
this.setUrl("/index.jsp");
}
return this.SUCCESS;
}
public String register() {
HttpServletRequest request = ServletActionContext.getRequest();
String method = request.getMethod();
if (method.equals("GET")) {
this.setUrl("/register.jsp");
}
if (method.equals("POST")) {
User user = new User();
user.setName(request.getParameter("name"));
user.setSex(Integer.parseInt(request.getParameter("sex")));
userDao.insertBean(user);
this.setUrl("/index.jsp");
request.setAttribute("tipMessage", "无");
}
return this.SUCCESS;
}
}
注:页面跳转设定好对应的 setUrl 就好,方法名字就跟对应的url有关,这里有疑惑的,请看之前的struts.xml通配符配置
配置步骤请参考这篇博客:http://blog.csdn.net/lxfhahaha/article/details/57078994 的第6部分-tomcat配置
代码已上传至csdn: http://download.csdn.net/download/lxfhahaha/10257949
写的有点仓促,写的不太好的地方,敬请谅解,欢迎评论~