jar包:链接:https://pan.baidu.com/s/167HHmKHiItw3t2DkjAgLNQ 密码:j4z5
一:框架目录树结构:(注意config文件创建为Java——>Source Folder,否则相应的配置文件访问不到)
二、入口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>myssh</display-name>
<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>
<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>*.action</url-pattern>
</filter-mapping>
</web-app>
三、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: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-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 隐式的注册了AutowiredAnnotationBeanPostProcessor、RequiredAnnotationBeanPostProcessor、
CommonAnnotationBeanPostProcessor以及PersistenceAnnotationBeanPostProcessor这4个BeanPostProcessor -->
<context:annotation-config />
<!-- 开启注解扫描 -->
<context:component-scan base-package="com.pmm" />
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置数据源 数据源开始 --> <!-- 连接数据库,配置连接池。如配置从c3p0连接池 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
</bean>
<!-- hibernate的相关信息 spring把数据源注入LocalSessionFactoryBean类 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<!-- 注入连接池对象 -->
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" >
<list>
<value>com.pmm.model</value>
</list>
</property>
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
</bean>
<!-- 配置Spring的声明式实务 -->
<!-- 配置新的事务 -->
<tx:annotation-driven transaction-manager="txManager" />
<!-- 1.配置hibernate的事务管理器 -->
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 2.配置事务属性 -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="find*" read-only="true" />
<tx:method name="get*" read-only="true" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="alter*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="insert*" propagation="REQUIRED" /><!-- insertAndUdpateIntoDB的前缀 -->
<tx:method name="test*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
<!-- 3.配置事务切入点 -->
<aop:config>
<!-- 切入点 -->
<aop:pointcut id="txPointcut"
expression="execution(public * com.pmm.service.imp..*.*(..))" />
<aop:advisor pointcut-ref="txPointcut"
advice-ref="txAdvice" />
</aop:config>
</beans>
对应的db.properties以及hibernate.cfg.xml
jdbc.username=root
jdbc.password=123456
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc\:mysql\://localhost\:3306/test
<?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>
<!-- hibernate基本属性 -->
<!-- 方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 显示及格式化sql -->
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<!-- 生成数据表策略 -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 二级缓存相关 -->
</session-factory>
</hibernate-configuration>
四、struts.xml配置
<?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>
<!-- Add packages here -->
<constant name="struts.enable.DynamicMethodInvocation" value="true" />
<constant name="struts.devMode" value="true" /><!-- 开发模式 -->
<!--配置struts请求后缀名 -->
<constant name="struts.action.extension" value="action" />
<constant name="struts.multipart.maxSize" value="104857600" />
<!--存放临时文件 -->
<constant name="struts.multipart.saveDir" value="/tmp" />
<!-- 当指定struts.objectFactory为spring时,struts2框架就会把bean转发给spring来创建,装配,注入 -->
<constant name="struts.objectFactory" value="spring" />
<constant name="struts.i18n.encoding" value="utf-8" />
<constant name="struts.ui.theme" value="simple" />
<package name="default" namespace="/" extends="struts-default">
<global-results>
<result name="loginUI">
/WEB-INF/jsp/user/loginUI.jsp
</result>
<result name="privilegeError">
/WEB-INF/jsp/user/privilegeError.jsp
</result>
<result name="exceptionError">
/WEB-INF/jsp/user/exceptionError.jsp
</result>
<result name="noSession">
/error/noSession.jsp
</result>
</global-results>
</package>
<package name="other" namespace="/" extends="default">
<action name="item" class="itemAction" method="{1}">
</action>
<action name="user" class="userHome"></action>
</package>
</struts>
log4j.properties
log4j.rootLogger=INFO,A1,R
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.Target=System.out
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=[%c]%m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=sshe.log
log4j.appender.R.MaxFileSize=10MB
log4j.appender.R.Threshold=ALL
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=[%p][%d{yyyy-MM-dd HH\:mm\:ss,SSS}][%c]%m%n
五、实现代码
action类
package com.pmm.action;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSONObject;
import com.opensymphony.xwork2.ModelDriven;
import com.pmm.action.base.BaseAction;
import com.pmm.dao.UserDao;
@Component("userHome")
@Scope("prototype")
public class UserAction extends BaseAction implements ModelDriven<UserDao>{
private static final long serialVersionUID = 1L;
private UserDao bv = new UserDao();
@Override
public UserDao getModel() {
return bv;
}
public void addUser(){
JSONObject obj = new JSONObject();
String username = bv.getUserName();
String password = bv.getPassWord();
int result = userService.addUser(username,password);
if(1 == result){
obj.put("result", "成功!");
}else{
obj.put("result", "失败!");
}
writeJson(obj);
}
}
baseAction类
package com.pmm.action.base;
import java.io.IOException;
import javax.annotation.Resource;
import org.apache.struts2.ServletActionContext;
import com.pmm.service.UserService;
import com.alibaba.fastjson.JSON;
import com.opensymphony.xwork2.ActionSupport;
public class BaseAction extends ActionSupport {
/**
* @ Resource默认是按照名称来装配注入的,只有当找不到与名称匹配的bean才会按照类型来装配注入;
*/
private static final long serialVersionUID = 1L;
//BgAction
@Resource(name="userServiceImp")
protected UserService userService;
public void writeJson(Object object) {
try {
String json = JSON.toJSONStringWithDateFormat(object, "yyyy-MM-dd HH:mm:ss");
ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
ServletActionContext.getResponse().getWriter().write(json);
ServletActionContext.getResponse().getWriter().flush();
} catch (IOException e) {
System.out.println("jsonת���쳣");
}
}
}
Service层接口(接口类可以定义相应的增删改方法)
package com.pmm.service;
public interface UserService {
int addUser(String username, String password);
}
ServiceImp层(实现类)
package com.pmm.service.imp;
import org.springframework.stereotype.Component;
import com.pmm.dao.base.imp.BaseDaoImp;
import com.pmm.service.UserService;
@Component("userServiceImp")
public class UserServiceImp extends BaseDaoImp<Object> implements UserService {
@Override
public int addUser(String username, String password) {
String sql = "INSERT INTO ssh (username,PASSWORD)VALUES(?,?)";
return super.insertOrUpdate_sqlserver(sql, username,password);
}
}
Dao层
package com.pmm.dao;
import java.io.Serializable;
public class UserDao implements Serializable{
private static final long serialVersionUID = 1L;
private String userName;
private String passWord;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
}
BaseDao
package com.pmm.dao.base;
import java.util.List;
import java.util.Map;
public interface BaseDao<E> {
public List<Map<String, Object>> find_sqlserver_toMapobject46(String queryString,Object...params);
public int insertOrUpdate_sqlserver(String sql,Object...params);
public Map<String,Object> find_sqlserver_toJustMap(String sql,Object...params);
public abstract List<E> findByHql(String paramString);
}
BaseDaoImp
package com.pmm.dao.base.imp;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import com.pmm.dao.base.BaseDao;
public class BaseDaoImp<E> implements BaseDao<E> {
//SessionFactroy接口负责初始化Hibernate。它充当数据存储源的代理,并负责创建Session对象。
/*@Resource(name = "sessionFactory_sql")
protected SessionFactory sql_SessionFactory;*/
//@Resource默认按 byName自动注入bean
@Resource(name = "sessionFactory")
protected SessionFactory sessionFactory;
private Class<E> clazz = null;
public Session getSession(){
return sessionFactory.getCurrentSession();
}
public BaseDaoImp() {
ParameterizedType pt = (ParameterizedType) this.getClass()
.getGenericSuperclass();
this.clazz = (Class<E>) pt.getActualTypeArguments()[0];
}
//查询数据库
@Override
public List<Map<String, Object>> find_sqlserver_toMapobject46(
String queryString, Object... params) {
Query query = this.getSession().createSQLQuery(queryString);
//把查询结果转换成map
query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
if(null!=params){
for(int i=0;i<params.length;i++){
query.setParameter(i, params[i]);
}
}
//把map排进list
List<java.util.Map<String,Object>> list = query.list();
return list;
}
public Map<String,Object> find_sqlserver_toJustMap(String sql,Object...params){
Query query = this.getSession().createQuery(sql);
query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
if(null!=params){
for(int i=0;i<params.length;i++){
query.setParameter(i, params[i]);
}
}
java.util.Map<String, Object> map = (Map<String, Object>) query.list();
return map;
}
//插入数据或更新数据 到数据库
@Override
public int insertOrUpdate_sqlserver(String sql, Object... params) {
Query query = this.getSession().createSQLQuery(sql);
if(null!=params){
for(int i=0;i<params.length;i++){
query.setParameter(i, params[i]);
}
}
return query.executeUpdate();
}
@SuppressWarnings("unchecked")
public List<E> findByHql(String hql)
{
return this.getSession().createQuery(hql).list();
}
}
前端html代码(login.html 通过ajax请求)
<!DOCTYPE html>
<html>
<head>
<title>login.html</title>
<meta charset="utf-8">
<meta name="keywords" content="keyword1,keyword2,keyword3">
<meta name="description" content="this is my page">
<meta name="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<iframe allowtransparency="true" frameborder="0" width="385" height="96" scrolling="no"
src="//tianqi.2345.com/plugin/widget/index.htm?s=1&z=1&t=0&v=0&d=3&bd=0&k=&f=<f=009944&htf=cc0000&q=1&e=1&a=1&c=54511&w=385&h=96&align=center">
</iframe>
<iframe width="214" scrolling="no" height="54" frameborder="0" allowtransparency="true"
src="http://i.tianqi.com/index.php?c=code&id=42&icon=1&num=3"></iframe>
用户名<input id = 'username' type="text" value=""><br>
密码<input id = 'password' type="password" value=""><br>
<input id='but' type="submit" value='登录'>
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$("#but").click(function(){
var username = $("#username").val();
var password = $("#password").val();
$.ajax({
url : "${pageContext.request.contextPath}/user!addUser.action",
data : {userName:username,passWord:password},
dataType : "json",
type : "post",
async : "false", //同步
success:function(jo){
alert(jo.result);
}
});
});
</script>
</body>
</html>
六、测试结果: