【SSH 框架项目的搭建--简化版】使用注解代替xml中的<bean>,减少代码量

SSH框架整合实践:全注解配置方式 SSH框架是指Spring、Struts2和Hibernate这三个主流Java开发框架的整合。Spring主要负责业务逻辑层的事务管理与依赖注入;Struts2作为表现层框架,主要处理用户请求;Hibernate则作为数据持久层框架,进行数据库操作。此整合模式起源于Java EE开发的历史,因其强大的功能组合,一度成为企业级应用开发的首选方案。在Struts2中,@Action注解是最为核心的注解之一。它用于标记一个方法或类作为Struts2的Action。 阅读详情

之前的《图书信息管理系统》项目中(http://blog.youkuaiyun.com/ssh159/article/details/52439676),

Spring的配置太繁琐。考虑开发大项目上,假设项目的action层会有成百上千 个Class类,不简化代码的

情况下就要在Spring的配置中装配上千个actionClass的<bean>,applicationContext.xml 的代码太多了。


改进代码:

1、使用注解 代替applicationContext.xml中的 <bean> 标签,添加 注解扫描器,解析器。

简化 xml处的配置信息。

2、使用Aop,只保留事务处理的代码(只保留 核心关注点 和 横切关注点 ),删掉多余的动作;

(这是面向切面的知识,不懂可以看看我之前写的 

【java初学者】理解,从面向过程 到 面向对象,面向接口,面向切面 例子。) 

简化 各层的代码。


(之前的博客:【JAVA】理解MVC模式,IOC , AOP, orm框架,SOA,ERP管理系统

AOP:将应用程序中的商业逻辑及对其提供支持的 应用服务 进行分离。
商业逻辑:

   核心关注点(主要是带入对象和对象的特殊事务),

   横切关注点(经常发生在核心关注点的各处,各处都基本相似,用以:权限认证,日志,事务处理)。
通用服务:做记录,日记。)

)


之前的写法:

因为不想new 对象,所以在application中,

1、一个类和2个接口(IndexAction , IndexServiceImpl , IndexDaoImpl)都要标明非单例;

2、用<bean> <prototype>标签 取代那些私有属性(is ,id ,sessionFactory )new对象;

3、私有属性(is ,id ,sessionFactory )还要设置属性和方法;


IndexAction 控制层 的代码:

private IndexService is = null;  
    public void setIs(IndexService is) {  
        this.is = is; 

IndexServiceImpl 业务逻辑处理层接口 的代码:

 private IndexDao id;  
//用于注入使用 
    public void setId(IndexDao id) {  
        System.out.println("有人给我注入了一个dao实例:"+id);  
        this.id = id;  
    }  

IndexDaoImpl 数据库访问层接口 的代码:

private SessionFactory sessionFactory;  
    public void setSessionFactory(SessionFactory sf) {  
        this.sessionFactory = sf;  
    } 

applicationContext.xml 中的代码 

 <bean id="myIndexAction" class="ssh.action.IndexAction" scope="prototype">  
        <!-- setIs(myIndexService) -->  
        <property name="is" ref="myIndexService"/>  
    </bean>  
      
    <!-- myIndexService = new ssh.service.IndexServiceImpl() -->  
    <bean id="myIndexService" class="ssh.service.IndexServiceImpl" scope="prototype">  
        <property name="id" ref="myIndexDao"/>  
    </bean>  
      
    <bean id="myIndexDao" class="ssh.dao.IndexDaoImpl" scope="prototype">  
<!-- 晚点再注入能用的seesionFactory --> 
        <property name="sessionFactory" ref="mySessionFactory"></property>  
    </bean>  


感觉代码实在是太多了,所以 现在用注解的方式,减少代码!


现在解决方案:

 

1、 在项目中加入注解:

    让Spring自动的为Class类定义的属性装配bean以及让Spring自动的扫描程序包中的类,隐式的在配置文件中

添加Class类的bean。

  注解分为两种,一是类的注解,二是类中属性的注解

  注解功能的提供也有两者,一是Spring,二是Jdk   (PS:类的注解只有springframework提供的)

2、使用事务处理,删除多余的信息,

不必每次 写方法都得 标明:(方法.开始;方法.进行ing;方法.提交;方法.结束)

3、增加四个aop 的jar包:解耦

百度云-ssh框架包-aop:http://pan.baidu.com/s/1pL4d3R1 



-------------------------------------------------------------

温馨提示:

1、已经注释的注解为:jdk注解;

正在使用的注解为:spring的注解。

2、2种注解都可以,只是规范代码。

3、使用注解就需要打包,这里已经删除了jdk注解带来的包。

例如:

@Controller //控制层action的注解,与打包

import org.springframework.stereotype.Controller; 

--------------------------------------------------------------

 一、项目分析



二、mysql建表

<span style="font-size:18px;color:#999999;">---------------新闻信息表
create database News; --建立数据库News;

</span>
<span style="font-size:18px;color:#999999;">--建立表 news;
create table news(
id int primary key auto_increment, 
title varchar(50),
content varchar(30),
begintime datetime,
username varchar(20)
);</span>

<span style="font-size:18px;color:#999999;">--插入数据
insert into news(title,content,begintime,username) values
('IT市场分析', '各门编程语言优势分析','2016-10-01','tom'),
('如何不用加班', '提高效率,减少上班时间','2016-10-02','tom2'),
('如何实现加工资','提升自我价值与跳槽','2016-10-03','tom3');

use news1;
select * form news; --查询表</span>



三、java代码:

news.action控制层:NewsAction 

@Controller 和 @Scope("prototype") 2个注解取代xml处的代码:

<bena id ="" class="" scope="">

<prototype id="" red="" />

</bean>

package news.action;


import java.util.List;
import javax.annotation.Resource;
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 news.entity.News;
import news.service.NewsService;


//@Controller("myNewsAction")
@SuppressWarnings("serial")
@Controller               //默认就是类的首字母小写newsAction
@Scope("prototype")
public class NewsAction extends ActionSupport {

private String message;

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}


//获取从客户端传递过来的值,strtus自动的赋值
private Integer id;

public Integer getId(){
return this.id;
}
public void setId(Integer id) {
this.id = id;
}

@Autowired
//@Qualifier("myNewsService")
//@Resource(name="myNewsService")
private NewsService ns;

//定义1个list用于前端jsp显示
private List<News> allNewList;


public List<News> getAllNewList() {
return allNewList;
}


//显示首页所有数据
public String showAllNews(){
//调用service 中的showAllNews,获取所有的数据,
//然后保存到
allNewList = ns.showAllNews();
return "success";
}

//显示首页所有数据(查询使用的。PS:本例没用到)
public String findNews(){
return "";
}

public String deleteSingleNews(){
System.out.println("从客户端传递过来的ID:"+id);
String returnValue = ns.deleteSingleNews(id);
return returnValue;
}

}
news.dao sql访问层的NewsDao 

package news.dao;

import java.util.List;

public interface NewsDao {
	public List showAllNews();
//显示首页所有数据(查询使用的。PS:本例没用到)
	public String findNews();
	public String deleteSingleNews(Integer id);
}


news.dao sql访问层的NewsDaoImpl接口
package news.dao;

import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;


import news.entity.News;


//@Repository("myNewsDao") //jdk注解
@Repository    <span style="white-space:pre">		</span>  //sql访问层注解,规范
@Scope("prototype")      //非单例
public class NewsDaoImpl implements NewsDao {

//@Qualifier("mySessionFactory")  
//@Resource(name="mySessionFactory")
@Autowired
private SessionFactory sf;


@Override
public List showAllNews() {

Session session = sf.getCurrentSession();
Query query = session.createQuery("from News");
 allNewList  = query.getResultList();

return allNewList;
}


@Override
public String findNews() {
return null;
}


@Override
public String deleteSingleNews(Integer id) {
Session session = sf.openSession();
Query query = session.createQuery("from News where id=:myid");

query.setParameter("myid", id);
List<News> deleteList  = query.getResultList();


//如果搜索出来是1条,就删除,如果是0条就不管了
if ( deleteList.size()==1 ) {
News news = deleteList.get(0);
System.out.println("删除对象:"+news.getTitle()+ " Id:"+news.getId());
session.getTransaction().begin();
session.delete(news);
session.getTransaction().commit();
session.close();
//sessionFactory关闭策略
//1.坚持使用数据库连接池(例如C3P0)
//2.sessionFactory就不关闭,而使用hibernate事务自动关闭功能
// 说明:sf.openSession();  必须关闭
//    sf.openSession(); 改为:sf.getCurrentSession();
//getCurrentSession创建的线程会在事务提交或者事务回滚后自动关闭
//sf.close();			
}

return "deleteOK";
}


}

news.entity 实体类层的 News 实体类

package news.entity;

import java.util.Date;

public class News {
	private Integer id;
	private String title;
	private String content;
	private Date begintime;
	private String username;
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public Date getBegintime() {
		return begintime;
	}
	public void setBegintime(Date begintime) {
		this.begintime = begintime;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	

}
news.entity包的 News.hbm.xml  sql信息配置
<?xml version="1.0" encoding="UTF-8"?>
<hibernate-mapping xmlns="http://www.hibernate.org/xsd/hibernate-mapping">
  
     <class name="news.entity.News" table="news">
        <id name="id" column="id">
        	<generator class="native"></generator>
        </id>
        <property name="title" type="string" length="50" column="title" not-null="true"></property>
        <property name="content" type="text" length="1000" column="content" not-null="true"></property>
        <property name="begintime" type="date" column="begintime" not-null="true"></property>
        <property name="username" type="string" length="20" column="username" not-null="true"></property>
    </class>
</hibernate-mapping>

news.service 业务逻辑处理层的 NewsService 
package news.service;

import java.util.List;

public interface NewsService {
	public List showAllNews();
//显示首页所有数据(查询使用的。PS:本例没用到)
	public String findNews();
	public String deleteSingleNews(Integer id);
}
news.service 层的NewsServiceImpl业务逻辑处理层接口

package news.service;


import java.util.List;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import news.dao.NewsDao;
import news.entity.News;


//@Service("myNewsService") //jdk注解
@Service<span style="white-space:pre">	</span>      //业务逻辑处理层 注解,规范
@Scope("prototype")   //非单例
public class NewsServiceImpl implements NewsService {


//Autowired和Qualifier 属于spring的注解,

//jdk自带注解resource可以替代Autowired
/*
 * 用resource的好处:
 * 1. 代码与spring 解耦,不依赖于spring
 * 2. 代码中没有spring的存在,可以随时切换任意一套类似spring的框架
 */

//@Qualifier("myNewsDao")
//@Resource(name="myNewsDao") 
@Autowired
private NewsDao nd;

<pre name="code" class="java">@Override
@Transactional(readOnly=true)  //事务处理=只读
 
public List showAllNews() {
//可以增加一个业务逻辑,比如:把文章的内容进行截取为20字符
//通过DAO获取数据

List<News> allNewList = nd.showAllNews();
//在return 之间,可以进行各种业务逻辑操作

return allNewList;
}


@Override
public String findNews() {
return null;
}

<pre name="code" class="java">@Override
@Transactional  //事务管理
 
public String deleteSingleNews(Integer id) {
//需要做以下判断,例如有没有权限删除,又或者判断下面是否有级联子子记录

//当可以删除时,调用DAO给直接删除
String returnValue = "deleteFailed";
returnValue = nd.deleteSingleNews(id);
return returnValue;
}


}

重点来了:applicationContext.xml

这里,之前<bean>的代码已经不要了,直接删除,写一个注解类的扫描器即可

<?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:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="    
			http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd  
			http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd  
			http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
			http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.2.xsd  
			http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">

<!-- 原理:自动注入processor解析器,用来解析注解 -->
<!--  <context:annotation-config/>   -->
	
<!-- 自动扫描包,也会自动注入解释器,所以不需要 context:annotation-config -->
<context:component-scan base-package="news"></context:component-scan>


<!-- 引入外部属性文件 -->
	<context:property-placeholder location="classpath:jdbc.properties" />

	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<!-- 注入连接池,包含了数据库用户名,密码等等信息 -->
		<property name="dataSource" ref="myDataSource" />

<!-- 配置Hibernate的其他的属性 -->
		<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.connection.autocommit">false</prop>
<!-- 开机自动生成表 -->
				<prop key="hibernate.hbm2ddl.auto">update</prop>
			</props>
		</property>
		<property name="mappingResources">
			<list>
				<value>news/entity/News.hbm.xml</value>
			</list>
		</property>

	</bean>

	<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="${jdbc.driver}" />
		<property name="jdbcUrl" value="${jdbc.url}" />
		<property name="user" value="${jdbc.user}" />
		<property name="password" value="${jdbc.password}" />
<!-- 每300秒检查所有连接池中的空闲连接 -->
		<property name="idleConnectionTestPeriod" value="300"></property>
<!-- 最大空闲时间,900秒内未使用则连接被丢弃。若为0则永不丢弃 -->
		<property name="maxIdleTime" value="900"></property>
<!-- 最大连接数 -->
		<property name="maxPoolSize" value="2"></property>

	</bean>
<!-- 加载一个事务管理驱动包 -->
<span style="white-space:pre">	</span><bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<span style="white-space:pre">		</span><property name="sessionFactory" ref="sessionFactory"></property>
<span style="white-space:pre">	</span></bean>
<span style="white-space:pre">	</span>
<!-- 注解驱动 --><span style="white-space:pre">	</span>
<span style="white-space:pre">	</span><tx:annotation-driven transaction-manager="transactionManager"/>

</beans>
		
jdbc.properties sql表信息,这个是需要修改sql 的时候给其他不懂代码的人 修改配置的

这里支持mysql 和 oracle ,密码为空

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/news
jdbc.user=root
jdbc.password=


#oracle
jdbc_oracle.driver=oracle.jdbc.driver.OracleDriver
jdbc_oracle.url=jdbc:oracle:thin@127.0.0.1:1521:orcl
jdbc_oracle.user=news
jdbc_oracle.password=
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>
	<constant name="struts.objectFactory" value="spring" />

<!-- 第1步:先定义一个包 -->
	<package name="mypck001" extends="struts-default">
		<action name="NewsAction_*" class="newsAction" method="{1}">
			<result name="success">/WEB-INF/jsp/index.jsp</result>
<!-- 希望删除成功后,重新执行1次首页显示内容 -->
			<result name="deleteOK" type="redirectAction">NewsAction_showAllNews.action?message=deleteOk&id=${id}</result>
		</action>
		
	</package>
</struts>


jsp页面:index.jsp 主页

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@	taglib uri="/struts-tags" prefix="s" %>       
<!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>Insert title here</title>
<style>
	table{width:200px;border:1px solid black;text-align: center;}
	td{border:1px solid black;}
</style>
</head>
<body>

<center>
提示信息:<s:property value="message"/>
删除ID:<s:property value="id"/>	

<table>
<s:iterator value="allNewList">
<tr>	
 <td>	<s:property value="id"/> </td>

  <td>	<s:property value="title"/> </td>
	
  <td> <s:a value="NewsAction_deleteSingleNews?id=%{id}">删除</s:a> </td>
</tr>
	<br>
</s:iterator>

</table>
<hr>
<h3>共有多少条记录:<s:property value="allNewList.size()"></s:property> </h3>

</center>

</body>
</html>

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>news1</display-name>
  <welcome-file-list>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <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>
  <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>
</web-app> 

default.jsp 重定向跳转主页面,隐藏主页面

NewsAction_showAllNews.action :调用NewsAction类 中的showAllNews的方法,

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	response.sendRedirect("NewsAction_showAllNews.action");
%>

lib目录下ssh框架配置jar包没有改变,还是之前的。

(参考网盘)







SSH整合与Hibernate注解实战指导 Struts框架是Apache软件基金会的一个项目,是一个基于MVC设计模式的Web应用框架。在SSH(Struts+Spring+Hibernate)框架组合中,Struts作为表现层(View)的主要组成部分,负责接收用户请求并将响应返回给客户端。Struts通过XML配置文件和JavaBean组件来处理Web应用中的业务逻辑,简化了基于Java的Web应用开发。Struts的核心是ActionServlet,它作为整个Struts框架的控制器,负责调用应用的业务逻辑组件。 阅读详情

相关推荐

注解驱动的SSH框架登录功能实现

SSH框架,即Struts2 + Spring + Hibernate的组合,起源于Java EE开发的传统三层架构模型:表现层、业务层和持久层。随着互联网技术的迭代升级,传统模型逐渐暴露出代码冗余和耦合度高的问题。为了优化这些不足,SSH框架应运而生,它将这三个组件整合起来,旨在简化开发流程、提高代码可维护性和系统性能。Struts2允许开发者创建自定义注解来满足特定需求。创建自定义注解涉及注解定义、注解处理器等步骤。

weixin_34456923的博客 590

Spring context:component-scan使用说明

在xml配置了这个标签后,spring可以自动去扫描base-pack下面或者子包下面的java文件,如果扫描到有@Component @Controller@Service等这些注解的类,则把这些类注册为bean 注意:如果配置了那么标签就可以不用再xml中配置了,因为前者包含了后者。另外还提供了两个子标签 1. 2. 在说明这两个子标签前,先说一下有一个u

菜鸟博客 32万+

SSH注解整合与所需jar包清单

SSH框架,即Struts2 + Spring + Hibernate的集成框架,是企业级Java应用开发中广泛采用的解决方案。它结合了三个框架的优势:Struts2的Web层处理能力、Spring的企业级服务管理、Hibernate的ORM数据持久化技术,为开发复杂的业务系统提供了一个高效、稳定且可维护的平台。

weixin_35871529的博客 662

搭建SSH项目注意

搭建SSH项目注意: 1 SSH中各个配置文件的意义 web.xml:用来配置spring监听器,设置监听,加载上下文; applicationContext.xml:为数据源注入session工厂,配置一些action里面的常类等的属性; hibernate.cfg.xml:hibernate对jdbc进行了简单的对象封装,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库,这里设定...

zpr5554321的博客 350

SSM注解式框架:Struts-Spring-Mybatis的现代演变

本文还有配套的精品资源,点击获取 简介:SSM(Struts2-Spring-Mybatis)注解式框架通过在类和方法上使用注解来简化SSH(Struts-Spring-Mybatis)传统XML配置,提高开发效率和代码可读性。本课程设计项目详细介绍了Spring、Struts2和Mybatis的关键注解,并探讨了其在实际项目中的应用,以及如何通过IDE工具自动化配置和代码...

weixin_34438187的博客 838

SSH Oracle 框架实战教程与项目源码下载

SSH框架是一种流行的Java EE应用程序开发框架,它将Struts、Spring和Hibernate三个开源框架整合在一起,提供了一种简单而有效的解决方案。它结合了三个框架的优点:Struts的MVC架构、Spring的依赖注入和面向切面编程(AOP)、以及Hibernate的ORM映射。通过这种整合,开发者可以更加专注于业务逻辑的实现,而不是底层的实现细节。

weixin_36001279的博客 956

SSH所有注解 +注解整合

SSH注解(不用死记硬背,有个印象就好) ----------Spring----------- ---创建对象--- @Component(美 [kəm'ponənt]啃破门特) 作用:相当于bean.xml文件中,bean标签使用&lt;bean id=”” class=”” /&gt; 属性:value:给bean取一个名称,相当于bean标签的id属性。 细节:如果不指定,默认...

龚道松 1399

h5简单汤姆猫

h5,简单实现了汤姆猫,可以在手机上运行。

详解SSH注解配置,bean注解、事物注解等

今天屌丝跟大家来评论评论SSH注解配置中的几种注解模式,切入正题: 使用过SSH注解的屌丝们都知道,要想使用注解需要在applicationContext.xml配置文件里面开启注解配置,开启方式如下: 1.头部声明需加入 xmlns:context="http://www.springframework.org/schema/context" http://www.springfra

RSun 1万+

Win11/Win10系统下,Proe5.0 M280终极版保姆级安装与激活指南(含SSQ补丁避坑)

本文提供Win11/Win10系统下Pro/E 5.0 M280终极版的详细安装与激活指南,涵盖环境配置、SSQ补丁应用及常见问题解决方案。通过系统调整、分步安装和性能优化,确保软件在现代操作系统上的稳定运行,特别适合机械设计用户参考。

weixin_30895059的博客 447

立创EDA开源足轮机器人:基于STM32F407与ESP32的LQR自平衡与FOC驱动设计全解析

本文详细解析了基于立创EDA平台的开源足轮机器人项目。该项目采用STM32F407作为主控,ESP32负责无线通信,并应用LQR自平衡算法与FOC驱动技术,实现了机器人的稳定站立、移动转向及复杂地形适应能力。文章深入剖析了其硬件架构、软件设计及调试经验,为机器人运动控制学习提供了宝贵参考。

weixin_42608299的博客 234

spring 3.0注解完全取代XML文件

spring 3.0新注解,可以完全取代XML文件

yu的博客 1425

【MNE脑电信号处理学习笔记1】数据的读取、可视化、剪裁、滤波和保存

MNE之读取原始数据、可视化数据、剪裁数据、滤波和保存 Reading & visualizaing raw data, cropping, filtering, and saving 原视频教程:Pybrain: M/EEG analysis with MNE Python 原笔记和材料:pybrain_mne 本文根据视频和个人理解对原笔记进行细微修改。 Import the few packages we’ll need import matplotlib import pathlib i

小白家 4218

SSH三大框架常用注解大全

注解与XML配置的区别注解:是一种分散式的元数据,与源代码耦合。 xml :是一种集中式的元数据,与源代码解耦。因此注解和XML的选择上可以从两个角度来看:分散还是集中,源代码耦合/解耦。注释配置相对于 XML 配置具有很多的优势:   它可以充分利用 Java 的反射机制获取类结构信息,这些信息可以有效减少配置的工作。如使用 JPA 注释配置 ORM 映射时,我们就不需要指定 PO 的属性名、类...

loveyouluobin的博客 1538

稚晖君Dummy机械臂CAN总线控制详解:从代码到实战(附常见问题排查)

本文深入解析了稚晖君Dummy机械臂的CAN总线控制技术,从协议设计到代码实现,详细介绍了CAN总线在机械臂控制中的核心价值、通信协议栈设计、运动控制指令实现及常见问题排查方法。通过实战案例和代码示例,帮助开发者快速掌握机械臂CAN总线控制的关键技术。

uuu88的博客 296

计算机网络Wireshark实验(西安交通大学)

实验名称 计算机网络Wireshark实验 实验日期 2021 年 5 月 17 日 实验地点 XJTU

沉鱼叶的博客 1817

使用注解简化SSH框架

在我们使用ssh框架搭建项目时,之前我会使用hibernate.cfg.xml来进行Hibernate配置信息的写入 现在,我们将hibernate交给spring来管理、配置 这样,我们就可以将我们的hibernate.cfg.xml文件删除掉了。 我们再使用注解简化我们的实体类 再在我们的application.xml配置一下属性 然后,我们便可以去掉我们的news.h

Or1n_559的博客 543

实战避坑:示波器测量非隔离开关电源的炸机风险与隔离方案

本文详细分析了使用示波器测量非隔离开关电源时的炸机风险,揭示了地线环路导致的短路问题,并对比了四种防炸机解决方案,包括示波器隔离供电、拔掉电源地线、使用差分探头和被测板隔离供电。重点推荐使用隔离变压器方案,确保测量安全与精度,同时提供了实操建议与经验分享,帮助工程师避免常见测量事故。

weixin_29224309的博客 564

Springboot,SSM及SSH的概念和区别

Springboot的概念: 是提供的全新框架,使用来简化Spring的初始搭建和开发过程,使用了特定的方式来进行配置,让开发人员不在需要定义样板化的配置。此框架不需要配置xml,依赖于想MAVEN这样的构建系统。 Springboot的优点: 1.减少了大量的开发时间并提高了生产力。 2.避免了编写大量的样板代码,注释和XML配置。 3.解决了Spring的弊端。 4.快速整合第三方框架,无需配置文件。 5.代码少了、配置文件少了、不需要对第三方框架烦恼了、项目精简了,对整个团队的开发及维护来说,更大的

匆匆过客的博客 767

做cellchat画图时自环的角度颠倒,如何解决?

🏆本文收录于 《全栈 Bug 调优(实战版)》 专栏。专栏聚焦真实项目中的各类疑难 Bug,从成因剖析 → 排查路径 → 解决方案 → 预防优化全链路拆解,形成一套可复用、可沉淀的实战知识体系。无论你是初入职场的开发者,还是负责复杂项目的资深工程师,都可以在这里构建一套属于自己的「问题诊断与性能调优」方法论,助你稳步进阶、放大技术价值 。

**My Coding Family** 467

uniapp [全端兼容] - 详细实现人脸识别和活体检测功能,实时监测人脸是否进入区域及动作是否正确播报,免费自动提示引导动作及语音,提供提供实名认证、身份证识别、人脸信息采集、刷脸扫脸认证示例代码

uniapp,h5移动端网页,微信小程序,支付宝小程序,Android安卓,苹果ios,app,nvue,人脸识别,扫脸认证,人脸认证,活体认证,身份认证,uni-app人脸识别详细教程,如何在app端实现免费人脸识别教程,如何在小程序端做,最好用的插件,安卓ios百度人脸识别、活体检测、人脸采集APP,H5人脸识别带前后摄像头,适合新手看的人脸识别功能教程,详细示例代码源码,有没有免费的,接入百度,阿里云人脸识别,百度,api,活体检测,数据采集,动作提示指引,语音提示指引,报错,无法核验一直出错,根本用

🏆 前端领域优质创作者 1万+

SSH框架使用注解后的简化

注释的优势:     1.最简单直接的优势就是减少了配置文件的代码量。     2.注释和Java代码位于一个文件中,而XML 配置采用独立的配置文件。配置信息和 Java 代码放在一起,有助于增强程序的内聚性。而采用独立的XML 配置文件,程序员在编写一个功能时,往往需要在程序文件和配置文件中不停切换,这种思维上的不连贯会降低开发效率。  SSH注解组合使用:       这里我推荐...

weixin_30721899的博客 123

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

SSH开发中的注解使用

在SSH中使用注解可以减少配置XML文件,毕竟随着项目规模的扩大,配置bean将把Spring的配置文件(applicationContext.xml)变得很混乱 在Spring的配置文件中开启注解扫描 <context:component-scan base-package="cn.lynu"></context:component-scan> 注意这个ba...

weixin_30449239的博客 120

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

菜鸟学SSH——基于注解的SSH将配置精简到极致

很早之前就想写一篇关于SSH整合的博客了,但是一直觉得使用SSH的时候那么多的配置文件,严重破坏了我们代码整体性,比如你要看两个实体的关系还得对照*.hbm.xml文件,要屡清一个Action可能需要对照applicationContext*.xml和struts*.xml文件。总之过多的配置文件坏破坏代码的整体性,会打乱代码的连续性,因为很多情况下你需要一边看Java代码,一边看xml的配置,采...

纸上得来终觉浅,绝知此事要躬行 3万+

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

SSM框架和SSH框架对比分析

当下流行的两种企业开发MVC开源框架,是我们Java程序猿必备知识能力。MVC,即模型(model)-视图(view)-控制器(controller)的缩写,一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码,将业务逻辑聚集到一个部件里面,在改进和个性化定制界面及用户交互的同时,不需要重新编写业务逻辑。框架之所以流行,在于其易复用和简化开发,精髓在思想,掌握了核心思想,我们掌握其他类似框架也不会有问题,建议大家有精力的话读一下框架源码,尤其是Spring。 SSH和SSM定义 SSH 通常指

jimbo_chou的博客 3016

SSH框架学习(四、struts+spring搭建,spring注解注入)

这里,还可以用spring的注解注入的方式进行注入。 导入的包和之前一样不变,web.xml不变 applicationContext.xml <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns

wuyt2008的专栏 4838
上一篇: 【JAVA】理解MVC模式,IOC , AOP, orm框架,SOA,ERP管理系统
下一篇: SSH(Struts,Spring,Hibernate)和SSM(SpringMVC,Spring,MyBatis)的区别
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值