基于注解的简单SSH保存用户小案例
需求:搭建SSH框架环境,使用注解进行相关的注入(实体类的注解,AOP注解、DI注入),保存用户信息
效果:

一、导依赖包

二、项目的目录结构

三、web.xml配置
<?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"> <!--懒加载过滤器,解决懒加载问题-->
<filter>
<filter-name>openSession</filter-name>
<filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>openSession</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping> <!-- struts2的前端控制器 -->
<filter>
<filter-name>struts</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <!-- spring 创建监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param> </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:tx="http://www.springframework.org/schema/tx"
xmlns:contex="http://www.springframework.org/schema/context"
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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 打开注解扫描开关 -->
<contex:component-scan base-package="com.pri"/> <!-- 以下是属于hibernate的配置 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql:///ssh_demo1?useSSL=false"/>
<property name="user" value="root"/>
<property name="password" value=""/>
</bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<!--1、核心配置-->
<property name="dataSource" ref="dataSource"/> <!-- 2、可选配置-->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<!-- 3、扫描映射文件 -->
<property name="packagesToScan" value="com.pri.domain"></property>
</bean> <!--开启事务控制-->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:annotation-driven transaction-manager= "transactionManager"/>
</beans>
五、log4j.properties配置
#设置日志记录到控制台的方式
log4j.appender.std=org.apache.log4j.ConsoleAppender
#out以黑色字体输出,err以红色字体输出
log4j.appender.std.Target=System.err
log4j.appender.std.layout=org.apache.log4j.PatternLayout
log4j.appender.std.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p %c{1}:%L - %m%n
#设置日志记录到文件的方式
log4j.appender.file=org.apache.log4j.FileAppender
#日志文件路径文件名
log4j.appender.file.File=mylog.log
#日志输出的格式
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
#日志输出的级别,以及配置记录方案,级别:error > warn > info>debug>trace
log4j.rootLogger=info, std, file
六、页面代码
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<h3>添加客户</h3>
<form action="${ pageContext.request.contextPath }/customerAction_save" method="post">
姓名:<input type="text" name="name" /><br/>
年龄:<input type="text" name="age" /><br/>
<input type="submit" value="提交"/><br/>
</form>
</body>
</html>
success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页</title>
</head>
<body>
<h1>保存成功!</h1>
</body>
</html>
七、实体层代码
package com.pri.domain; import javax.persistence.*; @Entity
@Table(name = "customer")
public class Customer {
@Id
@Column(name = "userId")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer userId; @Column(name = "name")
private String name;
@Column(name = "age")
private Integer age; public Integer getUserId() {return userId; } public void setUserId(Integer userId) {this.userId = userId;} public String getName() {return name;} public void setName(String name) {this.name = name;} public Integer getAge() {return age;} public void setAge(Integer age) {this.age = age;}
}
八、action层代码
package com.pri.action; import com.pri.domain.Customer;
import com.pri.service.CustomerService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import javax.annotation.Resource; @Controller("customerAction")
@ParentPackage(value = "struts-default")
@Scope("prototype")
@Namespace(value = "/")
public class CustomerAction extends ActionSupport implements ModelDriven<Customer>{ private Customer customer; @Resource(name = "customerService")
private CustomerService customerService; @Override
public Customer getModel() {
if (customer == null ){
customer = new Customer();
}
return customer;
} @Action(value = "customerAction_save",
results = {@Result(name = SUCCESS,type = "redirect",location = "/success.jsp")})
public String save(){
customerService.save(customer);
return SUCCESS;
}
}
九、service层代码
package com.pri.service;
import com.pri.domain.Customer;
public interface CustomerService {
void save(Customer user);
}
//=======================================
package com.pri.service.impl;
import com.pri.domain.Customer;
import com.pri.dao.CustomerDao;
import com.pri.service.CustomerService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
@Service("customerService")
@Transactional
public class CustomerServiceImpl implements CustomerService {
@Resource(name = "customerDao")
private CustomerDao customerDao;
@Override
public void save(Customer customer) {
customerDao.save(customer);
}
}
十、dao层代码
package com.pri.dao;
import com.pri.domain.Customer;
public interface CustomerDao {
void save(Customer customer);
}
//==================================================================
package com.pri.dao.impl;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
@Component("myHibernateDaoSupport")
public class MyHibernateDaoSupport extends HibernateDaoSupport {
@Resource(name = "sessionFactory")
public void setSuperSessionFactory(SessionFactory sessionFactory){
super.setSessionFactory(sessionFactory);
}
}
//=================================================
package com.pri.dao.impl;
import com.pri.dao.CustomerDao;
import com.pri.domain.Customer;
import org.springframework.stereotype.Repository;
@Repository("customerDao")
public class CustomerDaoImpl extends MyHibernateDaoSupport implements CustomerDao {
@Override
public void save(Customer customer) {
getHibernateTemplate().save(customer);
}
}
十一、Spring Beans Dependencies

基于注解的简单SSH保存用户小案例的更多相关文章
- Netty学习——基于netty实现简单的客户端聊天小程序
Netty学习——基于netty实现简单的客户端聊天小程序 效果图,聊天程序展示 (TCP编程实现) 后端代码: package com.dawa.netty.chatexample; import ...
- springboot+ehcache 基于注解实现简单缓存demo
1.加入maven依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactI ...
- jackson基于注解的简单使用
Jackson提供了一系列注解,方便对JSON序列化和反序列化进行控制,下面介绍一些常用的注解. 1.@JsonIgnore 此注解用于属性上,作用是进行JSON操作时忽略该属性. 2.@JsonFo ...
- 10 Spring框架--基于注解和xml的配置的应用案例
1.项目结构 2.基于xml配置的项目 <1>账户的业务层接口及其实现类 IAccountService.java package lucky.service; import lucky. ...
- Spring中基于注解的IOC(二):案例与总结
2.Spring的IOC案例 创建maven项目 导入依赖 pom.xml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ...
- Hibernate基于注解annotation的配置
Annotation在框架中是越来越受欢迎了,因为annotation的配置比起XML的配置来说方便了很多,不需要大量的XML来书写,方便简单了很多,只要几个annotation的配置,就可以完成我们 ...
- 菜鸟学SSH(十七)——基于注解的SSH将配置精简到极致
很早之前就想写一篇关于SSH整合的博客了,但是一直觉得使用SSH的时候那么多的配置文件,严重破坏了我们代码整体性,比如你要看两个实体的关系还得对照*.hbm.xml文件,要屡清一个Action可能需要 ...
- Servlet之保存用户偏好设置简单功能的实现
写在前面: 先来陈述一下为什么会有这样一个需求和这篇博文. 这是公司的一个项目,我们负责前端,后台服务由其他公司负责.该系统有一个系统偏好设置模块,用户可以设置系统的背景图片等系统样式,因为这是一个比 ...
- 8 -- 深入使用Spring -- 4...5 AOP代理:基于注解的“零配置”方式
8.4.5 基于注解的“零配置”方式 AspectJ允许使用注解定义切面.切入点和增强处理,而Spring框架则可识别并根据这些注解来生成AOP代理.Spring只是使用了和AspectJ 5 一样的 ...
随机推荐
- 如何到python模块路径linux
执行命令whereis python即可显示出python相关的所有的路径,包括可执行文件路径,安装路径等,该方法适用于大部分类似的场景抄自百度知道
- 查看inux系统类型和版本
当我们使用一台新的linux服务器的时候,为了区分他们的命令,我们首先第一步就是要搞清楚这个系统的类型和版本号,据此再来使用对应的命令. 下面来看看可以使用以下基本命令来查看 Linux 发行版名称和 ...
- 部署LVS-NAT群集
案例环境 LVS调度器作为Web服务器池的网关,LVS两块网卡,分别连接内外网,外网地址172.16.16.172.24,同时也作为整个群集的VIP,内网地址为192.168.7.21-24/24,是 ...
- declare命令
还是围绕以下几个问题进行学习; 1.declare是什么? 2.问什么要用declare? 3.怎样使用declare? 1.declare是什么? ♦declare应用的很多,向我们各种语言都会有声 ...
- (一)Python装饰器的通俗理解
在学习Python的过程中,我相信有很多人和我一样,对Python的装饰器一直觉得很困惑,我也是困惑了好久,并通过思考和查阅才能略有领悟,我希望以下的内容会对你有帮助,我也努力通过通俗的方式使得对Py ...
- Spring Boot 中使用 jpa
本文原文版权归 CSDN Hgihness 所有,此处为转载+技术收藏,如有再转请自觉于篇头处标明原文作者及出处,这是大家对作者劳动成果的自觉尊重!! 作者:Hgihness 原文:http://bl ...
- C#-WebForm-LinQ-条件精确查询、高级查询
前台界面,并在后台绑定数据 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Ca ...
- xshell本地上传文件至服务器
今天本地写了个项目,想传到服务器部署起来.就上网百度了一下挺多的,一个个记录下,如有雷同,纯属抄袭. lrzsz方法 rz # 检查是否安装 yum -y install lrzsz # 安装 rpm ...
- Scrapyd-Client的安装
1. pip安装 这里推荐使用pip安装,相关命令如下: pip3 install scrapyd-client 2.验证安装 安装成功后会有一个可用命令,叫作scrapyd-deploy,即部署命令 ...
- Flask基本知识
@app.route('/')def hello_world(): return 'Hello World!' #route动态Route,支持字符串.整数.浮点数,/user/<int:id& ...