基础篇-Spring框架的搭建

Spring 也是开源轻量级的IOC和AOP的容器框架

1.IOC(Inverse of Control)控制反转是Spring的核心模块。(面向接口的编程)

2.AOP(Aspect-Oriented Programming)面向切面的编程,除了IOC容器,Spring的另一个核心模块就是我们AOP框架了。(当然我们的Spring的IOC模块并不依赖于AOP)

接下来就让Spring结合之前的Struts2来创建一个小项目吧

  a.在我们的lib目录下导入Spring的依赖包(Spring在与Struts2结合使用时需要导入两个包commons-logging-1.1.3.jarstruts2-spring-plugin-2.3.30

  这样我们的包就已经导好了。

  b.将Spring配置文件加载到Web进行解析就需要在Web.xml的配置文件里边写解析的代码:

  (我们老师说:“Spring 就像一只鹰,在天空中俯视着,管理着我们项目的每一个实例”)

  c.Web.xml的配置文件已经写好了,接下来就需要在src目录下创建util包,entity包,dao包,service包,action包。

  1.在java_util包里边创建我们的JavaConnection的类,在这边我就直接写JavaConnection的实现类(JavaConnectionImpl):

  

package java_util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JavaConnectionImpl implements JavaConnection {
    //获取数据库的连接(加载驱动,URL地址,访问数据库的名字,访问数据库的密码,connection连接变量)
    
    private String driver="com.microsoft.sqlserver.jdbc.SQLServerDriver";
    private String url="jdbc:sqlserver://localhost:1433;DatabaseName=SSH";
    private String name="sa";
    private String pwd="123";
    private Connection conn=null;
    
    @Override
    public Connection getAllConnection() {
        try {
            //加载驱动
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            //获取数据库连接
            conn=DriverManager.getConnection(url,name,pwd);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return conn;
    }

}

  2.在entity包创建我们的实体类:

  

 
package java_entity;

import java.math.BigDecimal;
import java.sql.Date;

public class BookJava {
    private int cid; //编号
    private String name;  // 书本名称
    private Date BookDate;  //出版日期
    private BigDecimal deposit;  //价格
    
    
    public BookJava() {
        super();
    }
    public BookJava(int cid, String name, Date bookDate, BigDecimal deposit) {
        super();
        this.cid = cid;
        this.name = name;
        BookDate = bookDate;
        this.deposit = deposit;
    }
    public int getCid() {
        return cid;
    }
    public void setCid(int cid) {
        this.cid = cid;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Date getBookDate() {
        return BookDate;
    }
    public void setBookDate(Date bookDate) {
        BookDate = bookDate;
    }
    public BigDecimal getDeposit() {
        return deposit;
    }
    public void setDeposit(BigDecimal deposit) {
        this.deposit = deposit;
    }
    
    
}

  3.在Java_dao包创建访问数据库的类:

   

package ssh.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java_entity.BookJava;
import java_util.MyConnection;
import java_util.MyConnectionImpl;

public class JavaBookDaoImpl implements JavaBookDao {

   //给dao注入JavaConnection的类(往后学习了hibernate将会自动完成JDBC的写法)

    private JavaConnection c = null;

   public void setC(JavaConnection c) {
      this.c = c;
    }

  @Override
    public List<BookJava> getAllBookJava() {
        //1.dao这一层只做访问数据库
        //2.任何与数据库无关的代码,统统不参与 
        MyConnection c = new MyConnectionImpl();
        Connection conn = c.getConnection();
        // 第二步:查询数据库
        // (操作JDBC,需要sql语句,需要执行sql语句对象,需要执行sql语句后结果集合)
        String sql = "select * from BookJava";// 需要执行的sql语句
        PreparedStatement stmt = null;// 执行sql语句对象
        ResultSet rs = null;// 执行sql语句后的结果集
        try {
            stmt = conn.prepareStatement(sql);
            rs = stmt.executeQuery();
        } catch (Exception e) {
            System.out.println(e.getMessage());;
        }

        // 2.拿到rs后,执行一个遍历以及封装
        List myBookJavaList = new ArrayList<BookJava>();
        try {
            while (rs.next()) {
                // 风格:实体类是一个pojo对象,一般直接new就行
                BookJava bc = new BookJava();
                // 进行数据库封装
                bc.setCid(rs.getInt("cid"));
                bc.setName(rs.getString("name"));
                bc.setBookDate(rs.getDate("BookDate"));
                bc.setDeposit(rs.getBigDecimal("deposit"));
                myBookCardList.add(bc);// 添加到list集合
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }

        // 第四步(关闭外部资源【数据库、文件、网络资源】)
        try {
            rs.close();
            stmt.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  myBookJavaList;
    }

}

  4.在java_service包写业务逻辑类:

  

package java_service;

import java.util.List;
import java_dao.JavaBookDao;
import java_entity.BookJava;

public class JavaServiceImpl implements JavaService {
    //(spring)注入dao包里实现类的实例
    private JavaBookDao jd;
    
    public void setJd(JavaBookDao jd) {
                //在控制台输出注入的实例
        System.out.println("注入dao的实例"+jd);
        this.jd = jd;
    }
    public List<BookJava> getAllJavaBook() {
        // TODO Auto-generated method stub
        List<BookJava> JavaBook=jd.getAllJavaBookDao();
        return JavaBook;
    }

}

5.在java_Action包写action类:

package java_action;

import java.text.DecimalFormat;
import java.util.List;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import java_entity.BookJava;
import java_service.JavaService;

public class JavaBookAction extends ActionSupport {
    //注入service实例
    private JavaService jsi;
    public void setJsi(JavaService jsi) {
        this.jsi = jsi;
    }
    public String execute(){
        List<BookJava> javaList=jsi.getAllJavaBook();
        System.out.println("结果集:"+javaList.size());
        ActionContext ac=ActionContext.getContext();
        ac.put("javaList",javaList);
        return SUCCESS;
    }
    //输出人民币符号
    public String formatDouble(double s){
        DecimalFormat df=new DecimalFormat("u00A4##.0");
        return df.format(s);
    }
}

6.将所有的类都注入实例后,需要写Spring的配置文件(Spring将会对所有的实例进行管理)在src的目录下创建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: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">

    <bean id="javaBookAction" class="java_action.JavaBookAction" scope="prototype">
        <property name="jsi" ref="javaService"></property>
    </bean>
<!--javaService = new java_service.JavaServiceImpl() -->
<!-- javaService 的class相当于是new出来的java_service.JavaServiceImpl()-->
    <bean id="javaService" class="java_service.JavaServiceImpl" scope="prototype">
        <property name="jd" ref="javaBookdaoImpl"></property>
    </bean>
    <bean id="javaBookdaoImpl" class="java_dao.JavaBookDaoImpl" scope="prototype">
     <property name="c" ref="JavaConnectionImpl"></property>   
    </bean>
    <bean id="JavaConnectionImpl" class="java_unit.JavaConnectionImpl" scope="prototype"></bean>

</beans> 

 7.附上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>
    <!-- 告知Struts2运行时使用Spring来创建对象 -->
    <constant name="struts.objectFactory" value="spring"></constant>
    <package name="javaPackage" extends="struts-default" namespace="/">
        <action name="index" class="javaBookAction" method="execute">
            <result name="success">/WEB-INF/jsp/javaIndex.jsp</result>
        </action>
    </package>
</struts>

8.jsp页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!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>
</head>
<body>
    <table border="1px">
        <tr>
            <th>编号</th>
            <th>书名</th>
            <th>出版日期</th>
            <th>课本价格</th>
        </tr>
        <s:iterator value="javaList">
            <tr>
                <td><s:property value="cid"/></td>
                <td><s:property value="name"/></td>
                <td><s:date  name="BookDate" format="yyyy-MM-dd"></s:date></td>
                <td><s:property value="%{formatDouble(deposit)}" /></td>
            </tr>
        </s:iterator>
        <s:if test="javaList.size()==0">
            <tr>                    
                <td colspan="7">没有查找到数据</td>
            </tr>
        </s:if>
    </table>
</body>
</html>

9.最后输出页面

基本的Spring框架就已经搭建好了,其实注入也是IOC的另一个说法。Spring的注入降低了类与类之间的耦合度,提高了类内部的内聚度,使我们的软件具有更容易扩展和维护。

SpringAOP将会在后面SSH框架搭完后再进行详细的介绍。

原文地址:https://www.cnblogs.com/songyannan/p/5847376.html