Re:从零开始的Spring入门创建项目(一)(图文并茂)

  • 时间:
  • 来源:互联网
  • 文章标签:

文章目录

  • Re:从零开始的Spring入门(一)(图文并茂)
  • 一、创建项目
    • 1)NewProject
    • 2)补全目录结构
    • 3)导入Spring依赖
  • 二、创建实体类
    • 1)安装lombok插件
    • 2)导入lombok依赖
    • 3)创建实体类
    • 4)创建sql表
  • 三、配置数据源
    • 1)导入依赖
    • 2)创建配置文件
    • 3)配置到spring容器中
  • 四、创建接口
    • 1)创建 AccountDao
    • 2)创建 AccountDaoImpl
  • 五、创建service
    • 1)创建 AccountService
    • 2)创建 AccountServiceImpl
  • 六、单元测试
  • 七、创建Servlet
    • 1)导入依赖
    • 2)创建AccountServlet
    • 3)配置web.xml
  • 九、运行项目
    • 1)配置tomcat
    • 2)运行
  • 附录:Tomcat安装
    • 1.[官网下载](http://tomcat.apache.org/index.html)
    • 2.配置环境变量(可选)
    • 3.8080端口占用问题
    • 4.启动乱码问题

Re:从零开始的Spring入门(一)(图文并茂)

Spring 是分层的 full-stack(全栈) 轻量级开源框架,以 IoC 和 AOP 为内核,提供了展现层 SpringMVC 和业务层事务管理等众多的企业级应⽤技术,还能整合开源世界众多著名的第三⽅框架和类库,已经成为使⽤最多的 Java EE 企业应⽤开源框架。

Spring 官⽅⽹址:http://spring.io/

我们经常说的 Spring 其实指的是Spring Framework(spring 框架)。

先从创建一个简单的项目开始吧!

一、创建项目

1)NewProject

在这里插入图片描述
设置保存路径:
在这里插入图片描述
完成创建:

在这里插入图片描述

2)补全目录结构

在 src/main 目录下添加 webapp

使用快捷键(ctrl+alt+shift+s),设置如下

在这里插入图片描述

按顺序编辑这两个路径

在这里插入图片描述

src\main\webapp\WEB-INF\web.xml
在这里插入图片描述

src\main\webapp
在这里插入图片描述

最终如下:

在这里插入图片描述

在这里插入图片描述

3)导入Spring依赖

<!--引入spring IoC容器功能-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.9.RELEASE</version>
</dependency>
<!--引入spring web功能-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>5.2.9.RELEASE</version>
</dependency>
<!--引入spring aop的jar包支持-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>5.2.9.RELEASE</version>
</dependency>
<!--引入spring声明式事务相关-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.2.9.RELEASE</version>
</dependency>
<!--引入spring test-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.2.9.RELEASE</version>
</dependency>

<!--第三方的aop框架aspectj的jar-->
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.6</version>
    <scope>runtime</scope>
</dependency>

二、创建实体类

1)安装lombok插件

在这里插入图片描述

2)导入lombok依赖

<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.16</version>
    <scope>provided</scope>
</dependency>

3)创建实体类

@Data
@NoArgsConstructor
public class Account {
    private String cardNo;
    private String name;
    private int money;
}

4)创建sql表

在这里插入图片描述

CREATE TABLE `account` (
  `cardNo` varchar(100) NOT NULL COMMENT '银行卡号',
  `name` varchar(255) DEFAULT NULL COMMENT '用户名',
  `money` int(11) DEFAULT NULL COMMENT '账户金额',
  PRIMARY KEY (`cardNo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO `account` VALUES ('6029621011000', '李大雷', 1000);
INSERT INTO `account` VALUES ('6029621011001', '韩梅梅', 1000);

三、配置数据源

1)导入依赖

<!--数据库驱动包-->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.22</version>
</dependency>
<!--druid连接池-->
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.1</version>
</dependency>

2)创建配置文件

resource 下创建 jdbc.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/bank?serverTimezone=UTC
jdbc.username=root
jdbc.password=123456
--MySQL8.x
	--驱动:com.mysql.cj.jdbc.Driver
	--url:"jdbc:mysql://localhost:3306/database_name?characterEncoding=utf8 &serverTimezone=UTC"
--MySQL5.x
	--驱动:com.mysql.jdbc.Driver
	--url:"jdbc:mysql://localhost:3306/database_name"

3)配置到spring容器中

编辑 applicationContext.xml文件
导入Context命名空间

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
                           http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd ">
    <!--引入外部资源文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!--第三方jar中的bean定义在xml中-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
     </bean>

    <!--配置一个 JdbcTemplate 对象-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <constructor-arg name="dataSource" ref="dataSource"/>
    </bean>

四、创建接口

1)创建 AccountDao

public interface AccountDao {

    Account queryAccountByCardNo(String cardNo) throws Exception;

    int updateAccountByCardNo(Account account) throws Exception;
}

2)创建 AccountDaoImpl

@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public Account queryAccountByCardNo(String cardNo) throws Exception {
        String sql = "select * from account where cardNo=?";
        return jdbcTemplate.queryForObject(sql, new RowMapper<Account>() {
            @Override
            public Account mapRow(ResultSet resultSet, int i) throws SQLException {
                Account account = new Account();
                account.setName(resultSet.getString("name"));
                account.setCardNo(resultSet.getString("cardNo"));
                account.setMoney(resultSet.getInt("money"));
                return account;
            }
        }, cardNo);
    }

    @Override
    public int updateAccountByCardNo(Account account) throws Exception {
        String sql = "update account set money=? where cardNo=?";
        return jdbcTemplate.update(sql,account.getMoney(),account.getCardNo());
    }
}

五、创建service

1)创建 AccountService

public interface AccountService {
    int transfer(String fromCardNo,String toCardNo,int money) throws Exception;
}

2)创建 AccountServiceImpl

@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

    @Override
    public void transfer(String fromCardNo, String toCardNo, int money) throws Exception {
        Account from = accountDao.queryAccountByCardNo(fromCardNo);
        Account to = accountDao.queryAccountByCardNo(toCardNo);

        from.setMoney(from.getMoney()-money);
        to.setMoney(to.getMoney()+money);

        int row1 = accountDao.updateAccountByCardNo(to);
        //int c = 1/0;
        int row2 = accountDao.updateAccountByCardNo(from);

		return row1&row2;
    }
}

六、单元测试

<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>
@RunWith(SpringJUnit4ClassRunner.class)/*使用spring单元测试*/
@ContextConfiguration("classpath:applicationContext.xml")/*加载配置文件*/
public class AccountDaoTest {

    @Autowired
    private DataSource dataSource;
    @Autowired
    private AccountDao accountDao;
    @Autowired
    private AccountService accountService;

    @org.junit.Test
        public void dataSource() throws SQLException {
        System.out.println(dataSource.getConnection());
    }

    @org.junit.Test
        public void dao() throws Exception {
        Account account = accountDao.queryAccountByCardNo("6029621011000");
        System.out.println(account);
    }

    @org.junit.Test
        public void service() throws Exception {
        int transfer = accountService.transfer("6029621011000", "6029621011001", 1);
        System.out.println(transfer);
    }
}

七、创建Servlet

1)导入依赖

<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>
 <!--设置作用域 scope:provided
	部署到tomcat的时候是不会把jar包打包到项目中的,
      因为tomcat中已经有自己的一份ServletAPI,防止冲突-->

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.74</version>
</dependency>

2)创建AccountServlet

@WebServlet(name = "accountServlet", urlPatterns = "/accountServlet")
public class AccountServlet extends HttpServlet {

    @Autowired
    private AccountService accountService;

    /**
     * servlet单独有一个容器,归tomcat管理
     * @Autowired 无法注入 service
     */
    @Override
    public void init() throws ServletException {
        WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        accountService = (AccountService) webApplicationContext.getBean("accountService");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求体的字符编码
        request.setCharacterEncoding("UTF-8");

        String fromCardNo = request.getParameter("fromCardNo");
        String toCardNo = request.getParameter("toCardNo");
        String moneyStr = request.getParameter("money");
        int money = Integer.parseInt(moneyStr);

        Result result = new Result();

        try {
            // 调用service层方法
            int transfer = accountService.transfer(fromCardNo, toCardNo, money);
            result.setStatus("200");
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus("201");
            result.setMessage(e.toString());
        }

        // 响应
        response.setContentType("application/json;charset=utf-8");
        String s = JSON.toJSONString(result);
        System.out.println(s);
        Object o = JSON.toJSON(result);
        System.out.println(o);
        response.getWriter().print(o.toString());
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

3)配置web.xml

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Archetype Created Web Application</display-name>

    <!--配置Spring ioc容器的配置文件-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <!--使用监听器启动Spring的IOC容器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>

九、运行项目

1)配置tomcat

设置Application context 项目名![image.png](https://img-blog.csdnimg.cn/img_convert/c16f1948aa1417eab98e606826150dd2.png#align=left&display=inline&height=35&margin=[object Object]&name=image.png&originHeight=70&originWidth=799&size=4391&status=done&style=none&width=399.5)

2)运行

浏览器输入
http://localhost:8080/accountServlet?money=1&fromCardNo=6029621011001&toCardNo=6029621011000
![image.png](https://img-blog.csdnimg.cn/img_convert/8067cfc738f3ee9097b486b889d041f8.png#align=left&display=inline&height=268&margin=[object Object]&name=image.png&originHeight=536&originWidth=622&size=31893&status=done&style=none&width=311)

附录:Tomcat安装

1.官网下载

![image.png](https://img-blog.csdnimg.cn/img_convert/c0e331ad44eb6fb8abce844f6ec47e74.png#align=left&display=inline&height=180&margin=[object Object]&name=image.png&originHeight=360&originWidth=538&size=35503&status=done&style=none&width=269)
下载解压到本地(目录不要带中文或者空格)

2.配置环境变量(可选)

CATALINA_HOME  D:\Programs\apache-tomcat-9.0.39
path  %CATALINA_HOME%\bin;

cmd运行  startup.bat
浏览器输入一下 http://localhost:8080

3.8080端口占用问题

可以杀死占用进程 或者 修改tomcat端口号

  • 杀死占用进程
netstat -ano|findstr 8080	//查找进程号
taskkill /pid 1524 /f		//杀死进程号
  • 修改端口号

修改 Tomcat --> conf --> server.xml 文件,第69行
![image.png](https://img-blog.csdnimg.cn/img_convert/a7162f4a53137ef8c129007d67e5265e.png#align=left&display=inline&height=516&margin=[object Object]&name=image.png&originHeight=1031&originWidth=1496&size=410371&status=done&style=none&width=748)
比如修改如下

<Connector port="8888" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />

4.启动乱码问题

修改 Tomcat --> conf --> logging.properties
将所有 UTF-8 改成 GBK
![image.png](https://img-blog.csdnimg.cn/img_convert/bd9a0930485535fd0a7cb2cd16f95b7b.png#align=left&display=inline&height=386&margin=[object Object]&name=image.png&originHeight=772&originWidth=1383&size=219226&status=done&style=none&width=691.5)
![image.png](https://img-blog.csdnimg.cn/img_convert/dac98fd8d4542d1ba3f96d9c0eef8851.png#align=left&display=inline&height=400&margin=[object Object]&name=image.png&originHeight=800&originWidth=1290&size=152327&status=done&style=none&width=645)

本文链接http://www.taodudu.cc/news/show-1782059.html