SSH框架实现添删改查的详细步骤及其原理(傻瓜教程)

SSH : Spring+Struts+Hibernate

简单原理:

Struts:负责MVC的分离,控制业务跳转,即连接jsp和java文件的核心

Hibernate:持久层提供支持

Spring:管理struts和hibernate

程序框架结构(后台):

实验步骤:

1.导入pom.xml文件中的依赖

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.sdau.ssh1</groupId>
  <artifactId>ssh1</artifactId>
  <version>0.0.1-SNAPSHOT</version>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<!-- 统一各个框架版本 -->
		<struts.version>6.0.3</struts.version>
		<spring.version>5.3.23</spring.version>
		<hibernate.version>5.6.12.Final</hibernate.version>
	</properties>
	<dependencies>
		<!-- Spring 核心依赖 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<!-- Spring web依赖 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<!-- Spring整合ORM框架依赖 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<!-- Struts2 核心依赖 -->
		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-core</artifactId>
			<version>${struts.version}</version>
		</dependency>
		<!-- Struts2和Spring整合依赖 -->
		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts2-spring-plugin</artifactId>
			<version>${struts.version}</version>
		</dependency>
		<!-- Hibernate 核心依赖 -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>${hibernate.version}</version>
		</dependency>
		<!-- MySQL 依赖 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.28</version>
		</dependency>
		<!-- C3P0 依赖 -->
		<dependency>
			<groupId>com.mchange</groupId>
			<artifactId>c3p0</artifactId>
			<version>0.9.5.5</version>
		</dependency>
		<!-- AspectJ依赖 -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.9.9</version>
		</dependency>
		<!-- 日志管理 -->
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
			<version>2.9.1</version>
		</dependency>
		<!--javax.servlet-api -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>4.0.1</version>
			<scope>provided</scope>
		</dependency>
		
	</dependencies>  
</project>

2.将maven依赖导入lib

 

注意: <param-value>classpath:applicationContext.xml</param-value>这一行的路径

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_4_0.xsd" version="4.0">
  <display-name>ssh1</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
      <!-- 配置Struts2过滤器 -->
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- 配置Spring的监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- 指定Spring配置文件所在路径 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
</web-app>

3.struts.xml(提前构思想好要写的功能):
 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts SYSTEM "http://struts.apache.org/dtds/struts-6.0.dtd" >
<struts>
	<package name="default" namespace="/" extends="struts-default">
		<action name="login" class="action.LoginAction" method="login">
			<result name="success">login_success.jsp</result>
			<result name="fail">login_failure.jsp</result>
		</action>
		<action name="registerAction" class="action.registerAction"  method="add">
			<result name="success">register_success.jsp</result>
			<result name="fail">register_failure.jsp</result>
			<result name="exit">register_failure_user.jsp</result>
		</action>
		<action name="deleeteAction" class="action.deleteAction"  method="delete">
			<result name="success">deletes.jsp</result>
			</action>
			<action name="updateAction" class="action.updateAction"  method="update">
			<result name="success">updates.jsp</result>
			</action>
			<action name="sel" class="action.selectAction"  method="select">
			<result name="result">result.jsp</result>
			</action>
</package>
</struts>

4.db.properties(数据库信息)放入

5.applicationContext.xml:作用数据库连接和spring管理

<import resource="classpath:applicationContext_Student.xml"/>    

指明了第10步  applicationContext_Student.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:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
	<!-- 引入属性文件 -->
	<context:property-placeholder location="classpath:db.properties" />
	<!-- 配置C3P0连接池 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<!-- 数据库连接相关信息 -->
		<property name="jdbcUrl" value="${url}" />
		<property name="driverClass" value="${driver}" />
		<property name="user" value="${user}" />
		<property name="password" value="${password}"></property>
	</bean>
	<!-- 配置Hibernate的SessionFactory -->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<!-- 配置Hibernate属性 -->
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.show_sql">true</prop><!-- 是否展示SQL -->
				<prop key="hibernate.hbm2ddl.auto">update</prop><!-- 是否自动创建表结构 -->
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</prop>
			</props>
		</property>
		<property name="mappingLocations" value="classpath:hibernate_map/*.hbm.xml"></property>
	</bean>	
	<!-- 配置事务管理器 -->
	<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
		<!-- 注入SessionFactory -->
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<!-- 配置事务增强 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<!-- 配置需要进行事务管理的方法,和事务传播行为 -->
			<tx:method name="*" propagation="REQUIRED" />
		</tx:attributes>
	</tx:advice>

	<!-- 配置切面 -->
	<aop:config>
		<aop:pointcut id="pointcut" expression="execution(* service.*+.*(..))" />
		<!-- 适配切入点和事务增强 -->
		<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" />
	</aop:config>
	<import resource="classpath:applicationContext_Student.xml"/>	
</beans>

6.实体类的创建

UserInf.java

package model;

public class UserInf {

	public String getUserid() {
		return userid;
	}
	public void setUserid(String userid) {
		this.userid = userid;
	}
	public String getUserpwd() {
		return userpwd;
	}
	public void setUserpwd(String userpwd) {
		this.userpwd = userpwd;
	}
	public String getRealname() {
		return realname;
	}
	public void setRealname(String realname) {
		this.realname = realname;
	}
	private String userid;
	private String userpwd;
	private String realname;
	

}

7.数据库与实体类映射文件userinf.hbm.xml

注意与自己的数据库名对应

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping SYSTEM "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
	<class name="model.UserInf" table="userinf">
		<id name="userid" column="userid">
			<generator class="assigned"></generator>
		</id>
		<property name="userpwd" column="userpwd"></property>
		<property name="realname" column="realname"></property>
	</class>
</hibernate-mapping>

8.先写dao层:

接口定义省略

dao方法:

package dao;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.NativeQuery;
import org.springframework.ui.Model;

import model.UserInf;

public class UserInfDao implements UserInfDaoInterface {
	private SessionFactory sessionFactory;


	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	@Override
	public int selectByIdPwd(UserInf ui) {
		Session session = sessionFactory.getCurrentSession();
		int n = 0;
		try {
			String sql = "select * from userinf where userid=? and userpwd=? and realname=?";
			NativeQuery<UserInf> query = session.createNativeQuery(sql, UserInf.class);
			query.setParameter(1, ui.getUserid());
			query.setParameter(2, ui.getUserpwd());
			query.setParameter(3, ui.getRealname());
			List<UserInf> list = query.getResultList();
			if (!list.isEmpty())
				n = 1;
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return n;
	}
	@Override
	
	public UserInf selectById(UserInf ui){
		
		
		Session session = sessionFactory.getCurrentSession();
		String n = "";
		UserInf uu=null;
		try {
			
			uu=session.get(UserInf.class,ui.getUserid());
			
			System.out.println(uu.getRealname());
			
			
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return uu;
	}
	@Override
	public void add(UserInf ui) {
		Session session = sessionFactory.getCurrentSession();
		try {
			session.save(ui);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void delete(UserInf ui) {
		Session session = sessionFactory.getCurrentSession();

		try {

			session.delete(ui);

		} catch (Exception e) {

			e.printStackTrace();

		}

	}

	@Override
	public void update(UserInf ui) {
		Session session = sessionFactory.getCurrentSession();

		try {
            
			session.update(ui);

		} catch (Exception e) {

			e.printStackTrace();

		}

	}

	@Override
	public void jia(UserInf ui) {
		Session session = sessionFactory.getCurrentSession();

		try {

			session.save(ui);

		} catch (Exception e) {

			e.printStackTrace();

		}

	}


	
}

9.Service层:

接口定义省略

作用调用dao中的方法:

package service;

import dao.UserInfDaoInterface;
import model.UserInf;

public class UserInfService implements UserInfServiceInterface {
	private static final String UserInf = null;
	private UserInfDaoInterface userInfDao;
	public void setUserInfDao(UserInfDaoInterface userInfDao) {
		this.userInfDao = userInfDao;
	}
	@Override
	public int login(UserInf ui) {
		
		return userInfDao.selectByIdPwd(ui);
	}
	@Override
public void register(UserInf ui) {
		
	userInfDao.add(ui);
	}@Override
	public void delete(UserInf ui) {
		
		 userInfDao.delete(ui);
		}@Override
	public void update(UserInf ui) {
		
		 userInfDao.update(ui);
		}@Override
		public void jia(UserInf ui) {
			
			 userInfDao.jia(ui);
			}
		@Override
		public UserInf sel(UserInf ui) {
			
			 return userInfDao.selectById(ui);
			}
}

10.applicationContext_Student.xml

大致原理:利用spring管理添、删、改、查方法

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
	<bean id="userInfDao" class="dao.UserInfDao">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	
	<bean id="userInfService" class="service.UserInfService">
		<property name="userInfDao" ref="userInfDao"></property>
	</bean>
	
	<bean id="loginAction" class="action.LoginAction">
		<property name="userInfService" ref="userInfService"></property>
	</bean>
	<bean id="registerAction" class="action.registerAction">
		<property name="userInfService" ref="userInfService"></property>
	</bean>
	<bean id="deleteAction" class="action.deleteAction">
		<property name="userInfService" ref="userInfService"></property>
	</bean>
	<bean id="updateAction" class="action.updateAction">
		<property name="userInfService" ref="userInfService"></property>
	</bean>
	<bean id="jiaAction" class="action.jiaAction">
		<property name="userInfService" ref="userInfService"></property>
	</bean>
	<bean id="selectAction" class="action.selectAction">
		<property name="userInfService" ref="userInfService"></property>
	</bean>
</beans>

11.Action层:

调用方法并将返回值与struts连接

添:

package action;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import dao.UserInfDao;
import model.UserInf;
import service.UserInfServiceInterface;

public class registerAction  extends ActionSupport implements ModelDriven<UserInf> {
	private UserInf ui;
	private static final long serialVersionUID = 1L;
	private UserInfServiceInterface userInfService;

	public void setUserInfService(UserInfServiceInterface userInfService) {
		this.userInfService = userInfService;
	}


	@Override
	public UserInf getModel() {
		ui=new UserInf();
		return ui;
	}
	
	
	public String add(){
		
	
		if(userInfService.login(ui)==1)
		{return "exit";}
		else 	
		{userInfService.register(ui);
	    return "success";}
	}


}

删:

package action;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import model.UserInf;
import service.UserInfServiceInterface;

public class deleteAction extends ActionSupport implements ModelDriven<UserInf> {
	private UserInf ui;
	private static final long serialVersionUID = 1L;
	private UserInfServiceInterface userInfService;

	public void setUserInfService(UserInfServiceInterface userInfService) {
		this.userInfService = userInfService;
	}

	@Override
	public UserInf getModel() {
		ui=new UserInf();
		return ui;
	}
	public String delete()
	{
		userInfService.delete(ui);
			return "success";
			
		
	}

}

改:

package action;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import model.UserInf;
import service.UserInfServiceInterface;

public class updateAction extends ActionSupport implements ModelDriven<UserInf> {
	private UserInf ui;
	private static final long serialVersionUID = 1L;
	private UserInfServiceInterface userInfService;

	public void setUserInfService(UserInfServiceInterface userInfService) {
		this.userInfService = userInfService;
	}

	@Override
	public UserInf getModel() {
		ui=new UserInf();
		return ui;
	}
	public String update()
	{
		userInfService.update(ui);
			return "success";
		
	}

}

查:

重点:map的作用是把查询结果返还给前台。

package action;

import java.net.http.HttpRequest;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import org.springframework.ui.Model;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import dao.UserInfDao;
import model.UserInf;
import service.UserInfServiceInterface;

public class selectAction extends ActionSupport implements ModelDriven<UserInf> {
	private UserInf ui;
	private static final long serialVersionUID = 1L;
	private UserInfServiceInterface userInfService;
	
	
	public void setUserInfService(UserInfServiceInterface userInfService) {
		this.userInfService = userInfService;
	}

	@Override
	public UserInf getModel() {
		ui=new UserInf();
		return ui;
	}
	
	public String select()
	{   UserInf ui1=userInfService.sel(ui);
		ActionContext actionContext = ActionContext.getContext(); 
		Map<String, Object> session = actionContext.getSession(); 
		session.put("ui", ui1); 
		return "result";
	}

}

然后是前台页面的书写,只需要谨记:让input文本框名与你想传递到的数据库列名一致即可。

以上就是SSH框架的简单原理及其实现。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值