您好,登錄后才能下訂單哦!
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&characterEncoding=utf8
jdbc.username=root
jdbc.password=root
b.配置連接池(在applicationContext.xml中添加)
<context:property-placeholder location="classpath:database.properties" /> <bean id="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中添加)
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" p:packagesToScan="com.yan.entity"(重點:使組件自動掃描特定的包以發現實體類的定義) p:dataSource-ref="dataSource"> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext (重點:使getCurrentSession不為null)</prop> </props> </property>
d.配置事務管理SessionFactory(在applicationContext.xml中添加)
<tx:annotation-driven />配置注解事務有效 <bean id="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_write NONSTRICT_READ_WRITE TRANSACTIONAL public class RoleBean implements Serializable { private static final long serialVersionUID = -7132291370667604346L; @Id //聲明主鍵 @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(length = 32, unique = true, nullable = false)//定義類說明,length字串長度unique唯一性約束,nullable非空約束 private String name; @Basic(fetch = FetchType.LAZY)//針對屬性的加載策略,需要支持 @Column(length = 200) private String descn; @OneToMany(mappedBy = "role", cascade = CascadeType.ALL)//說明一對多關聯,mapedby表示由對方負責維護兩者之間的關聯關系,cascade級聯策略 private Set<UserBean> users = new HashSet<>();
6.定義DAO接口--IBaseDao
在src/com/wcg/dao包下添加DAO接口
public interface IBaseDao<T extends Serializable,ID extends Serializable> { T save(T record); T delete(T record); T load(ID id); T update(T record); List<T> selectByExample(T record, int... pages); int selectByExampleRowsNum(T record); //查詢滿足條件的一共有多少行 } //-------------------------- public interface IRoleDao extends IBaseDao<RoleBean, Long> { } //-------------------------- public class BaseDaoImpl<T extends Serializable, ID extends Serializable> implements IBaseDao<T, ID> { @Autowired private SessionFactory sessionFactory; private Class<T> recordClass; @SuppressWarnings("unchecked") public BaseDaoImpl() { this.recordClass = (Class<T>) (((ParameterizedType) getClass().getGenericSuperclass()) .getActualTypeArguments()[0]); } protected Session getSession() { return sessionFactory.getCurrentSession(); } @Override public T save(T record) { this.getSession().save(record); return record; } @Override public T delete(T record) { this.getSession().delete(record); return record; } @Override public T load(ID id) { return this.getSession().get(recordClass, id); } @Override public T update(T record) { this.getSession().update(record); return record; } @SuppressWarnings("unchecked") @Override public List<T> selectByExample(T record, int... pages) { Criteria criteria = 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]); return criteria.list(); } //-------------------------- @Repository("roleDao")//聲明DAO類型的受管bean,其中的value就是名稱,類似于<bean>的id public class RoleDaoImpl extends BaseDaoImpl<RoleBean, Long> implements IRoleDao { }
7.定義業務
在src/com/wcg/biz包下添加Server接口
public interface IRoleServ { void create(RoleBean role); } //-------------------------- @Service //定義業務類型的受管bean,如果不定義名稱,則默認名稱就是類名稱,首字母小寫 @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) //聲明事務,readOnly只讀事務propagation事務傳播特性 public class RoleServImpl implements IRoleServ { @Resource(name = "roleDao") private IRoleDao roleDao; @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public void create(RoleBean role) { roleDao.save(role); }
8.定義Action
在src/com/wcg/action包下添加action類
@Controller //定義控制器類型的受管bean @Scope("prototype") //定義scope=prototype以保證Action的多實例 @Namespace("/") //Struts2的注解,表示名空間 @ParentPackage("struts-default") //Struts2的注解,定義繼承的包名稱 public class UserAction extends ActionSupport implements ModelDriven<UserBean>, SessionAware { private UserBean user = new UserBean(); private Map<String, Object> sessionAttribute; @Autowired private IUserServ userv; @Action(value = "tologin", results = { @Result(name = "success", location = "/WEB-INF/content/user/login.jsp") }) public String toLogin() throws Exception { return SUCCESS; }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。