《开启微服务之旅:Spring Boot Web开发举例》(二)

news/2024/12/24 2:31:47 标签: spring boot, 微服务, 前端
  1. Springboot开发企业信息管理系统
    1. 引入资源

1.创建项目引入页面原型

2.引入maven依赖和starters

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
</dependency>

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-devtools</artifactId>
   <optional>true</optional>
</dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
   <groupId>org.webjars</groupId>
   <artifactId>jquery</artifactId>
   <version>3.3.1</version>
</dependency>
<dependency>
   <groupId>org.mybatis.spring.boot</groupId>
   <artifactId>mybatis-spring-boot-starter</artifactId>
   <version>1.3.1</version>
</dependency>

<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>druid</artifactId>
   <version>1.0.9</version>
</dependency>
<dependency>
   <groupId>log4j</groupId>
   <artifactId>log4j</artifactId>
   <version>1.2.15</version>
</dependency>

<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <scope>runtime</scope>
</dependency>

    1. thymeleaf模板处理

创建mvc的配置类TxMvcConfig

@Configuration
@MapperScan("cn.tx.springboot.mapper")
public class TxMvcConfig implements WebMvcConfigurer{

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/toLogin").setViewName("login");
        registry.addViewController("/header").setViewName("header");
        registry.addViewController("/index").setViewName("index");
        registry.addViewController("/menu").setViewName("menu");
        registry.addViewController("/add").setViewName("add");
    }


    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        List<String> excludePatterns = new ArrayList<String>();
        excludePatterns.add("/css/**");
        excludePatterns.add("/images/**");
        excludePatterns.add("/toLogin");
        excludePatterns.add("/login");
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns(excludePatterns);
    }
}

    1. 创建数据库环境

1.创建数据库执行脚本

SET FOREIGN_KEY_CHECKS=0;

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

-- Table structure for my_user

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

DROP TABLE IF EXISTS `my_user`;

CREATE TABLE `my_user` (

  `pid` int(11) NOT NULL AUTO_INCREMENT,

  `username` varchar(255) DEFAULT NULL,

  `password` varchar(255) DEFAULT NULL,

  `p_addr` varchar(255) DEFAULT NULL,

  `gender` int(11) DEFAULT NULL,

  `birth` date DEFAULT NULL,

  PRIMARY KEY (`pid`)

) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

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

-- Records of my_user

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

INSERT INTO `my_user` VALUES ('1', 'zhangsan', '123', '北京', '1', '2020-06-14');

  1. 配置druid数据源

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/boot_demo
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

  1. 创建数据源的配置类

@Configuration
public class DruidConfig {
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource dataSource(){
        return new DruidDataSource();
    }

}

    1.  编写数据层

1.创建mybatis的配置类MybatisConfig

@Configuration
public class MybatisConfig {


    @Bean
    public ConfigurationCustomizer getCustomizer(){
        return new ConfigurationCustomizer() {
            @Override
            public void customize(org.apache.ibatis.session.Configuration configuration) {
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }

}

2.创建数据层UserMapper

public interface MyUserMapper {


    @Options(useGeneratedKeys = true, keyProperty = "pid")
    @Insert("insert into my_user(pid, username, password, p_addr, gender, birth)values(" +
            "#{pid}, #{username}, #{password}, #{pAddr}, #{gender}, #{birth})")
    public  void insert(MyUser user) ;

    @Select("select * from my_user")
    public List<MyUser> selectUsers();

    @Select("select * from my_user t where t.username = #{username} and t.password = #{password}")
    public MyUser selectUsersById(Map<String, String> map);


    @Select("select * from my_user t where t.pid = #{pid}")
    public MyUser selectUsersById1(int userId);

    @Update("update  my_user set " +
            "username = #{username}," +
            "password=#{password}, " +
            "p_addr= #{pAddr}, " +
            "gender=#{gender}, " +
            "birth=#{birth} " +
            "where pid = #{pid}")
    public  void update(MyUser user) ;

    @Delete("delete from my_user  where pid = #{pid}")
    public  void delete(int pid) ;

}

    1.  编写Service

public interface MyUserService {

    public  void insert(MyUser user) ;

    public  void update(MyUser user) ;

    public List<MyUser> selectUsers();

    public MyUser selectUsersById(Map<String, String> map);

    public MyUser selectUsersById1(int userId);

    public  void delete(int pid) ;


}

实现类略(参见视频)

    1. 页面处理

1. main页面处理

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>首页</title>
</head>

<frameset cols="*" rows="136, *" id="frame_main"  border="0">
    <frame src="header" noresize="noresize" name="header">
    
    <frameset cols="240, *">
       <frame th:src="@{/menu}" name="menu" />
       <frame th:src="@{/main}" name="main">
    </frameset>
</frameset>

<a th:href="@{/add}">添加</a>
<table class="mt" align="center">
    <tr >
        <td >用户名</td>
        <td >密码</td>
        <td >地址</td>
        <td >生日</td>
        <td >操作</td>
    </tr>
    <tr th:each="user:${users}">
        <td th:text="${user.username}"></td>
        <td th:text="${user.password}"></td>
        <td th:text="${user.pAddr}"></td>
        <td th:text="${#calendars.format(user.birth,'yyyy-MM-dd')}"></td>
        <td>
            <a th:href="@{/getUser(pid=${user.pid})}" >修改</a>
            <a th:href="@{/delete(pid=${user.pid})}" >删除</a>
        </td>
    </tr>
</table>

2.添加页面处理

引入thymeleaf命名空间后

<form th:action="@{/save}" method="post">
       <table class="mt" align="center">
           <tr >
               <td >用户名</td>
               <td><input name="username" type="text"/></td>
           </tr>
           <tr >
               <td >密码</td>
               <td><input name="password" type="password"/></td>

           </tr>
           <tr >
               <td >地址</td>
               <td><input name="pAddr" type="text"/></td>
           </tr>
           <tr >
               <td >生日</td>
               <td><input name="birth" type="text"/></td>

           </tr>
           <tr >
               <td >性别</td>
               <td><input name="gender" type="text"/></td>
           </tr>
           <tr >
               <td ></td>
               <td><input  type="submit"/></td>
           </tr>
       </table>
   </form>

2.修改页面处理

<form th:action="@{/update}" method="post">
       <input type="hidden" name="pid" th:value="${user.pid}"/>
       <table class="mt" align="center">
           <tr >
               <td >用户名</td>
               <td><input name="username" type="text" th:value="${user.username}"/></td>
           </tr><tr >
               <td >密码</td>
               <td><input name="password" type="password" th:value="${user.password}"/></td>
           </tr><tr >
               <td >地址</td>
               <td><input name="pAddr" type="text" th:value="${user.pAddr}"/></td>
           </tr>
           <tr >
               <td >地址</td>
               <td><input name="gender" type="text" th:value="${user.gender}"/></td>
           </tr>
           <tr >
               <td >生日</td>
               <td><input name="birth" type="text" th:value="${#calendars.format(user.birth, 'yyyy-MM-dd')}"/></td>
           </tr><tr >
               <td ></td>
               <td><input  type="submit"/></td>
           </tr>
       </table>
   </form>

    1. 用户登录

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>用户登录</title>
<!--<link href="css/login.css" rel="stylesheet" type="text/css" />-->
<link th:href="@{/css/login.css}" rel="stylesheet" type="text/css" />
<script th:src="@{/webjars/jquery/3.3.1/jquery.js}"></script>
<script>
   function login1() {
      $("form").submit();
   }

</script>
</head>
<body>

    <div id="login">
   
        <div id="top">
            <div id="top_left"><img src="images/login_03.gif" /></div>
           <div id="top_center"></div>
       </div>
       <form th:action="@{/login}" method="post">
          <div id="center">
              <div id="center_left"></div>
              <div id="center_middle">
                  <div style="text-align: center; color: red" th:text="${tip}"></div>
                  <div id="user">用 户
                   <input type="text" name="username" />
                  </div>
                  <div id="password">密   码
                   <input type="password" name="password" />
                  </div>
                  <div id="btn">
                     <a href="#" οnclick="login1()">登录</a>
                     <a href="#">清空</a>
                  </div>
              </div>
              <div id="center_right"></div>
          </div>
       </form>
       <div id="down">
            <div id="down_left">
               <div id="inf">
                       <span class="inf_text">版本信息</span>
                  <span class="copyright">信息管理系统 v2.0</span>
               </div>
           </div>
           <div id="down_center"></div> 
       </div>
   </div>
</body>
</html>

登录的Controller逻辑

@PostMapping("/login")
public String login(HttpSession session, String username, String password, Model model) {
    Map<String, String> map = new HashMap<String, String>();
    map.put("username", username);
    map.put("password", password);
    MyUser user = userService.selectUsersById(map);
    if (user != null){
        session.setAttribute("user", user);
        return "redirect:index";
    }else{
        model.addAttribute("tip","用户名或者密码错误");
        return "login";
    }
}

Header模板页面

<div id="main">
   <div id="welcome">欢迎你回来
        <span th:text="${session.user.username}" th:if="${not #strings.isEmpty(session.user)}"></span>
        <a target="_top" th:text="请登录" th:href="@{/toLogin}" th:if="${#strings.isEmpty(session.user)}"></a>
        <img src="images/clock.gif" /> 学习是最好的投资</div>
    <div id="adminop">
        <ul>
            <li><a href="#">站点首页</a></li>
            <li><a href="javascript:parent.location.reload();">管理首页</a></li>
            <li><a href="javascript:parent.location.reload();">退出管理</a></li>
            <li><a href="#">站点首页</a></li>
        </ul>
    </div>
</div>


http://www.niftyadmin.cn/n/5797226.html

相关文章

React 底部加载组件(基于antd)

底部加载组件的意义在于提供一种流畅的用户体验&#xff0c;以便在用户滚动到页面底部时自动加载更多内容。这样可以让用户无需离开当前页面&#xff0c;就能够无缝地浏览更多的内容.通过底部加载组件&#xff0c;可以分批加载页面内容&#xff0c;减少一次性加载大量数据对页面…

Java重要面试名词整理(一):MySQLJVMTomcat

文章目录 MySQL篇联合索引最左前缀法则索引下推并发事务处理带来的问题事务隔离级别Read Uncommitted&#xff08;读取未提交内容&#xff09;Read Committed&#xff08;读取提交内容 RC&#xff09;Repeatable Read&#xff08;可重读 RR&#xff09;Serializable&#xff08…

重塑医院挂号体验:SSM 与 Vue 搭建的预约系统设计与实现

4系统概要设计 4.1概述 本系统采用B/S结构(Browser/Server,浏览器/服务器结构)和基于Web服务两种模式&#xff0c;是一个适用于Internet环境下的模型结构。只要用户能连上Internet,便可以在任何时间、任何地点使用。系统工作原理图如图4-1所示&#xff1a; 图4-1系统工作原理…

win11用一条命令给anaconda环境安装GPU版本pytorch,并检查是否为GPU版本

不需要安装cudatookit和cudnn&#xff0c;只要有显卡就有cuda&#xff0c;安装tenserflow-gpu的时候需要额外安装的是cudatookit和cudnn 用一条命令即可 打开官网&#xff1a; Start Locally | PyTorch 选择安装版本 运行命令即可 pip3 install torch torchvision torchaud…

使用Redis实现限流

使用Redis实现限流的三种方式 目录 概述基于计数器的固定窗口限流 实现原理适用场景实现步骤代码实现缺点 基于滑动窗口的限流 实现原理适用场景实现步骤代码实现优点缺点 基于令牌桶算法的限流 实现原理适用场景实现步骤Lua脚本实现Java实现优点缺点 总结 概述 在分布式系统…

Pinia---新一代的Vuex

关于Pinia的一些问题 pinia是用来做什么的&#xff1f; 集中状态管理工具&#xff0c;新一代的Vuex Pinia中还需要mutation吗&#xff1f; 不需要&#xff0c;action既支持同步也支持异步 Pinia如何实现getter&#xff1f; computed计算属性函数 Pinia产生的Store如何解构赋…

如何使用 Python 执行 SQL 查询?

一、常用的Python SQL库 在Python中执行SQL查询&#xff0c;最常用的库包括&#xff1a; sqlite3&#xff1a;用于与SQLite数据库交互&#xff0c;适合小型项目或测试环境。psycopg2&#xff1a;用于与PostgreSQL数据库交互&#xff0c;功能强大&#xff0c;支持复杂查询。my…

FastAPI vs Go 性能对比分析

FastAPI vs Go 性能对比分析 总体结论 FastAPI 虽然性能优秀&#xff0c;但整体上仍无法完全达到 Go 的性能水平。 详细对比 优势 FastAPI 开发效率高Python生态系统丰富自动API文档生成类型检查和验证异步支持好 Go 原生性能更强内存占用更低并发处理能力强编译型语言的优…