I、springboot基本概念

1.受管Bean

Spring中那些组成应用的主体以及由Spring IoC容器所管理的对象被称之为bean;

Bean就是由Spring容器初始化、装配以及被管理的对象

2.控制反转IOC和依赖注入DI

IoC实现由容器控制程序之间的关系,而非传统实现中,由程序代码直接操控,控制权由应用代码中转到了外部容器,控制权的转移,是所谓控制反转;

创建被调用者实例的工作通常由Spring容器来完成,然后注入调用者,因此也称为依赖注入

依赖注入:接口注入、设置注入、构造器注入

3.AOP面向切面编程

AOP即Aspect-Oriented Programming, 面向切面编程是一种新的方法论,是一种技术,不是设计模式,是对传统OOP(Object-Oriented Programming,面向对象编程)的补充

AOP 的主要编程对象是切面(aspect), 而切面模块化横切关注点

II、搭建简单的web服务器(SSH)

1.添加jar包

整合maven,在pom.xml中添加

<dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId><version>${spring.version}</version></dependency><dependency><groupId>com.oracle</groupId><artifactId>ojdbc6</artifactId><version>1.5</version><scope>system</scope><systemPath>${project.basedir}/src/main/webapp/WEB-INF/lib/ojdbc6.jar</systemPath></dependency></dependencies>

2.整合Spring和web应用(在web.xml中添加)

<context-param><param-name>contextConfigLocation</param-name><param-value>classpath:app*.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>

3.整合struts2(在web.xml中添加)

<filter><filter-name>struts2</filter-name><filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class><init-param><param-name>struts.devMode</param-name><param-value>true</param-value></init-param></filter><filter-mapping><filter-name>struts2</filter-name><url-pattern>/*</url-pattern></filter-mapping>

4.整合Hibernate

a.添加database.properties文件

jdbc.driver=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf8

jdbc.username=root

jdbc.password=root

b.配置连接池(在applicationContext.xml中添加)

<context:property-placeholderlocation="classpath:database.properties"/><beanid="dataSource"class="com.alibaba.druid.pool.DruidDataSource"p:driverClassName="${jdbc.driver}"p:url="${jdbc.url}"p:username="${jdbc.username}"p:password="${jdbc.password}"destroy-method="close"/>

c.配置SessionFactory(在applicationContext.xml中添加)

<beanid="sessionFactory"class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"p:packagesToScan="com.yan.entity"(重点:使组件自动扫描特定的包以发现实体类的定义)p:dataSource-ref="dataSource"><propertyname="hibernateProperties"><props><propkey="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop><propkey="hibernate.show_sql">true</prop><propkey="hibernate.format_sql">true</prop><propkey="hibernate.hbm2ddl.auto">update</prop><propkey="hibernate.current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext(重点:使getCurrentSession不为null)</prop></props></property>

d.配置事务管理SessionFactory(在applicationContext.xml中添加)

<tx:annotation-driven/>配置注解事务有效<beanid="transactionManager"p:sessionFactory-ref="sessionFactory"class="org.springframework.orm.hibernate5.HibernateTransactionManager"/>

5.定义带注解的实体类

在src/com/wcg/entity包下添加实体类

@Entity(name="t_roles")//声明实体类,name是对应的表名称@Cache(usage=CacheConcurrencyStrategy.READ_ONLY)//配置二级缓存的并发访问策略,read_only/read_writeNONSTRICT_READ_WRITETRANSACTIONALpublicclassRoleBeanimplementsSerializable{privatestaticfinallongserialVersionUID=-7132291370667604346L;@Id//声明主键@GeneratedValue(strategy=GenerationType.IDENTITY)privateLongid;@Column(length=32,unique=true,nullable=false)//定义类说明,length字串长度unique唯一性约束,nullable非空约束privateStringname;@Basic(fetch=FetchType.LAZY)//针对属性的加载策略,需要支持@Column(length=200)privateStringdescn;@OneToMany(mappedBy="role",cascade=CascadeType.ALL)//说明一对多关联,mapedby表示由对方负责维护两者之间的关联关系,cascade级联策略privateSet<UserBean>users=newHashSet<>();

6.定义DAO接口--IBaseDao

在src/com/wcg/dao包下添加DAO接口

publicinterfaceIBaseDao<TextendsSerializable,IDextendsSerializable>{Tsave(Trecord);Tdelete(Trecord);Tload(IDid);Tupdate(Trecord);List<T>selectByExample(Trecord,int...pages);intselectByExampleRowsNum(Trecord);//查询满足条件的一共有多少行}//--------------------------publicinterfaceIRoleDaoextendsIBaseDao<RoleBean,Long>{}//--------------------------publicclassBaseDaoImpl<TextendsSerializable,IDextendsSerializable>implementsIBaseDao<T,ID>{@AutowiredprivateSessionFactorysessionFactory;privateClass<T>recordClass;@SuppressWarnings("unchecked")publicBaseDaoImpl(){this.recordClass=(Class<T>)(((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0]);}protectedSessiongetSession(){returnsessionFactory.getCurrentSession();}@OverridepublicTsave(Trecord){this.getSession().save(record);returnrecord;}@OverridepublicTdelete(Trecord){this.getSession().delete(record);returnrecord;}@OverridepublicTload(IDid){returnthis.getSession().get(recordClass,id);}@OverridepublicTupdate(Trecord){this.getSession().update(record);returnrecord;}@SuppressWarnings("unchecked")@OverridepublicList<T>selectByExample(Trecord,int...pages){Criteriacriteria=this.getSession().createCriteria(recordClass);if(record!=null)criteria.add(Example.create(record));if(pages!=null&&pages.length>0)criteria.setFirstResult(pages[0]);if(pages!=null&&pages.length>1)criteria.setMaxResults(pages[1]);returncriteria.list();}//--------------------------@Repository("roleDao")//声明DAO类型的受管bean,其中的value就是名称,类似于<bean>的idpublicclassRoleDaoImplextendsBaseDaoImpl<RoleBean,Long>implementsIRoleDao{}

7.定义业务

在src/com/wcg/biz包下添加Server接口

publicinterfaceIRoleServ{voidcreate(RoleBeanrole);}//--------------------------@Service//定义业务类型的受管bean,如果不定义名称,则默认名称就是类名称,首字母小写@Transactional(readOnly=true,propagation=Propagation.SUPPORTS)//声明事务,readOnly只读事务propagation事务传播特性publicclassRoleServImplimplementsIRoleServ{@Resource(name="roleDao")privateIRoleDaoroleDao;@Transactional(readOnly=false,propagation=Propagation.REQUIRED)publicvoidcreate(RoleBeanrole){roleDao.save(role);}

8.定义Action

在src/com/wcg/action包下添加action类

@Controller//定义控制器类型的受管bean@Scope("prototype")//定义scope=prototype以保证Action的多实例@Namespace("/")//Struts2的注解,表示名空间@ParentPackage("struts-default")//Struts2的注解,定义继承的包名称publicclassUserActionextendsActionSupportimplementsModelDriven<UserBean>,SessionAware{privateUserBeanuser=newUserBean();privateMap<String,Object>sessionAttribute;@AutowiredprivateIUserServuserv;@Action(value="tologin",results={@Result(name="success",location="/WEB-INF/content/user/login.jsp")})publicStringtoLogin()throwsException{returnSUCCESS;}