springboot02(系统学习):yaml格式 多配置文件 springboot整合servlet springboo整合jsp springboo整合jdbc freemarker模板页

1 yaml

1.1 概念

YAML(/ˈjæməl/)是一个可读性高,用来描述数据的以数据为中心的语言(数据格式)
YAML是"YAML Ain't a Markup Language"的递归缩写。
这种语言以数据做为中心,而不是以标记语言为重点.  具备标记类语言的作用 但不具备标记类语言的特点
yaml不是标记类语言:::不需要标签来封装数据
yaml是标记类语言:::和标记类语言相同  都是用来描述数据

1.2 语法

    大小写敏感
    使用缩进表示层级关系
    缩进不允许使用tab,只允许空格
    缩进的空格数不重要,只要相同层级的元素左对齐即可
    '#'表示注释

2 yaml练习1

2.1 配置文件:application.yml

  • 准备数据
# 注释

--- # 分割符号
stu1:
  # 单值属性
  sid: 1
  sage: 12
  sname: 韩梅梅
  sex:sdy: true
  sbirth: 2000-11-12

  # 数组属性:写法1: -
  arr1:
    - 1
    - 3
    - 6
    - 8
    - 11
    - 13
  # 数组属性:写法2: []
  arr2: [11.3,12.6,19.5,12,45,11,13]

  # 对象属性:写法1:yaml
  teacher1:
    tid: 1001
    tname: 张三
    tsubject: 数学
  # 对象属性:写法2:json
  teacher2: { tid: 1002,tname: "李四", tsubject: "语文" }

2.2 创建实体类

package com.zhiyou100.entity;

import java.io.Serializable;

public class Teacher  implements Serializable {
    private Integer tid;
    private String tname;
    private String tsubject;
    ...
}
package com.zhiyou100.entity;
...
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)


@Component
@ConfigurationProperties(prefix = "stu1")
public class Student  implements Serializable {
    private Integer sid;
    private Integer sage;
    private String sname;
    private String sex;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date sbirth;
    private Boolean sdy;
    private int[] arr1;
    private double[] arr2;

    private Teacher teacher1;
    private Teacher teacher2;
}

2.3 创建action 装配学生对象

package com.zhiyou100.action;
...
@RestController  //@Controller+@ResponseBody
@RequestMapping("/test01")
public class Test01 {
    @Autowired
    private Student student;
    @GetMapping("/m1.action")//@RequestMapping(value = "test01",method = RequestMethod.GET)
    public Student method01(){
        return student;
    }
}

2.4 结果

在这里插入图片描述

2.5 老师对象

  • 配置文件:application.yml

在这里插入图片描述

  • 实体类
@Component
@ConfigurationProperties(prefix = "stu1.teacher1")
public class Teacher  implements Serializable {
    private Integer tid;
    private String tname;
    private String tsubject;
    ...
}
  • action
@Autowired
private Teacher teacher;
@GetMapping("/m2.action")//@RequestMapping(value = "test01",method = RequestMethod.GET)
public Teacher method02(){
    return teacher;
}
  • 效果
    在这里插入图片描述

3 属性集文件配置信息的读取

3.1 默认文件:application.properties

  • 定义属性

在这里插入图片描述

  • 实体类:写法1:通过注解@Value
@Component
public class Teacher2 implements Serializable {
    @Value("${teacher03.tid}")
    private Integer tid;
    @Value("${teacher03.tname}")
    private String tname;
    @Value("${teacher03.tsubject}")
    private String tsubject;
    ...
}
  • 实体类:写法2:通过注解@ConfigurationProperties
@Component
@ConfigurationProperties(prefix = "teacher03")
public class Teacher2 implements Serializable {
    //@Value("${teacher03.tid}")
    private Integer tid;
    //@Value("${teacher03.tname}")
    private String tname;
    //@Value("${teacher03.tsubject}")
    private String tsubject;
    ...
}
  • action
@Autowired
private Teacher2 teacher2;
@GetMapping("/m3.action")//@RequestMapping(value = "test01",method = RequestMethod.GET)
public Teacher2 method03(){
    return teacher2;
}
  • 效果

在这里插入图片描述

3.2 自定义文件:config/hehe.properties

在启动类上加@PropertySource指定自定义配置文件的位置即可
  • 配置文件:/config/hehe.properties

在这里插入图片描述

  • 启动类
@SpringBootApplication
@PropertySource("classpath:config/hehe.properties")//加载非默认的配置文件:::名字不是application
public class Springboot03Application {
    public static void main(String[] args) {
        SpringApplication.run(Springboot03Application.class, args);
    }
}
  • 实体类
@Component
@ConfigurationProperties(prefix = "teacher04")
public class Teacher3 implements Serializable {
    private Integer tid;
    private String tname;
    private String tsubject;
    ...
}
  • action
@Autowired
private Teacher3 teacher3;
@GetMapping("/m4.action")//@RequestMapping(value = "test01",method = RequestMethod.GET)
public Teacher3 method04(){
    return teacher3;
}
  • 效果

在这里插入图片描述

3.3 总结

1 properties和yaml使用完全相同
2 如果是自定义配置文件 想被加载就需要在启动类上加@PropertySource
3 在实体类的属性上  可以通过@Value("${teacher03.tname}")指定要赋的值--从配置文件中读取
4 在实体类上       可以通过@ConfigurationProperties(prefix = "teacher03")指定要赋的前缀

4 配置文件

4.1 多配置文件

不同环境需要加载不同的信息:多个配置文件
  • 创建文件:application-development.yml
server:
  port: 8082
  servlet:
    context-path: /springboot03_development
  • 创建文件:application-produce.yml
server:
  port: 8083
  servlet:
    context-path: /springboot03_produce
  • 创建文件:application-test.yml
server:
  port: 8081
  servlet:
    context-path: /springboot03_test
  • 在核心配置文件application.yml 中 通过active属性设置要加载的配置文件的后缀
#  指定环境要使用的配置文件
spring:
  profiles:
    active: produce

4.2 一个配置文件多个环境

  • 在核心配置文件中 通过— 设置多个环境 通过spring. config. activate.on-profile 来指定环境的名字
#指定环境使用的端配置信息的on-profile值
spring:
  profiles:
    active: t

--- # test环境
server:
  port: 8081
  servlet:
    context-path: /springboot03_test
spring:
  config:
    activate:
      on-profile: t

--- # development环境
server:
  port: 8082
  servlet:
    context-path: /springboot03_development
spring:
  config:
    activate:
      on-profile: d

--- # produce环境
server:
  port: 8082
  servlet:
    context-path: /springboot03_produce
spring:
  config:
    activate:
      on-profile: p

5 springboot整合servlet

引入springbootweb::springmvc和servlet可以共存

5.1 创建servlet:添加注解@WebServlet指定其url

package com.zhiyou100.action;

@WebServlet(urlPatterns = {"/test02/s1","/test02/s2","/test02/s3"})
public class Test02Servlet   extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         resp.getWriter().println("servlet::::::");
    }
}

5.2 启动类上加注解@ServletComponentScan扫描servlet

package com.zhiyou100;
...
@SpringBootApplication
@PropertySource("classpath:config/hehe.properties")//加载非默认的配置文件:::名字不是application
@ServletComponentScan(basePackages = {"com.zhiyou100.action"})
public class Springboot03Application {
    public static void main(String[] args) {
        SpringApplication.run(Springboot03Application.class, args);
    }
}

6 springboot整合jdbc

6.1 创建项目

在这里插入图片描述

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

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.49</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.24</version>
</dependency>

6.2 数据库

CREATE TABLE `student` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `score` FLOAT DEFAULT NULL,
  `dy` BIT(1) DEFAULT NULL,
  `sex` VARCHAR(255) DEFAULT NULL,
  `name` VARCHAR(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8;
INSERT INTO student VALUES(
    NULL,
    TRUNCATE(RAND()*100,1),
    RAND()>0.5,
    IF(RAND()>0.5,"男","女"),
    SUBSTRING(REPLACE(UUID(),"-",""),1,10));
SELECT * FROM student;

6.3 实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public class Student  implements Serializable {
    private Integer id;
    private String name;
    private String sex;
    private Float score;
    private Boolean dy;
}

6.4 dao

  • 接口
public interface StudentDao {
    public List<Student> getAll();
    public Student getOne(int id);
    public List<Student> getSomeBySex(String sex);

    public int update(Student student);
    public int add(Student student);
    public int delete(int id);
}
  • 实现类
package com.zhiyou100.dao;
...
@Repository
public class StudentDaoImp  implements  StudentDao{

    //获取jdbc模板类 //对jdbc的封装
    @Autowired
    private JdbcTemplate jdbcTemplate;
    //jdbcTemplate.update(sql,args);         //dml
    //jdbcTemplate.query(sql,rowmapper,args);//dql  rowmapper指定类中属性与表列的对应关系
    //jdbcTemplate.call();                   //调用函数和存储过程
    //jdbcTemplate.execute(sql) ;//可以执行dml 和 dql

    @Autowired
    //private RowMapper<Student> studentRowMapper;

    @Override
    public List<Student> getAll() {
        return  jdbcTemplate.query("select * from student",getRowMapper());
    }

    @Override
    public Student getOne(int id) {
        return jdbcTemplate.query("select * from student where id=?",getRowMapper(),id).get(0);
    }

    @Override
    public List<Student> getSomeBySex(String sex) {
        return jdbcTemplate.query("select * from student where sex=?",getRowMapper(),sex);
    }

    @Override
    public int update(Student s) {
        return jdbcTemplate.update("update student set sex=?,name=?,score=?,dy=? where id=?",s.getSex(),s.getName(),s.getScore(),s.getDy(),s.getId());
    }

    @Override
    public int add(Student s) {
        return jdbcTemplate.update("insert into student(name,sex,dy,score) values(?,?,?,?)",s.getName(),s.getSex(),s.getDy(),s.getScore());
    }

    @Override
    public int delete(int id) {
        return jdbcTemplate.update("delete from student where id=?",id);
    }

    //@Bean
    public RowMapper<Student> getRowMapper(){
        return new RowMapper<Student>(){
            @Override
            public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
                Student student =new Student();
                student.setId(rs.getInt("id"));
                student.setName(rs.getString("name"));
                student.setSex(rs.getString("sex"));
                student.setDy(rs.getBoolean("dy"));
                student.setScore(rs.getFloat("score"));
                return student;
            }
        };
    }
}

6.5 测试dao

@SpringBootTest
public class Test01StudentDao {

    @Autowired
    private StudentDao studentDao;

    @Test
    public void test01(){
        System.out.println(studentDao.getAll());
    }
}

6.6 service

  • 接口
  • 实现类
package com.zhiyou100.service;
...
@Service
public class StudentServiceImp  implements  StudentService{
    @Autowired
    private StudentDao studentDao;
    public List<Student> getAll(){
        return studentDao.getAll();
    }
    public Student getOne(int id){
        return studentDao.getOne(id);
    }
    public List<Student> getSomeBySex(String sex){
        return studentDao.getSomeBySex(sex);
    }

    public int update(Student student){
        return studentDao.update(student);
    }
    public int add(Student student){
        return studentDao.add(student);
    }
    public int delete(int id){
        return studentDao.delete(id);
    }
}

6.7 action

package com.zhiyou100.action;

import com.zhiyou100.entity.Student;
import com.zhiyou100.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.w3c.dom.stylesheets.LinkStyle;

import java.util.List;

@RestController
@RequestMapping("/student")
public class StudentAction {

    @Autowired
    private StudentService studentService;

    @RequestMapping("/getAll.action")
    public List<Student> getAll(){
        return studentService.getAll();
    }
    @RequestMapping("/getOne/{id}.action")
    public Student getOne(@PathVariable("id") int id){
        return studentService.getOne(id);
    }
    @RequestMapping("/getSomeBySex.action")
    public List<Student> getSomeBySex(String sex){
        return studentService.getSomeBySex(sex);
    }
    @RequestMapping("/update.action")
    public String update(Student student){
        int hang=studentService.update(student);
        return "修改"+hang+"行成功!";
    }
    @RequestMapping("/add.action")
    public String add(Student student){
        int hang=studentService.add(student);
        return "添加"+hang+"行成功!";
    }
    @RequestMapping("/delete/{id}.action")
    public String delete(@PathVariable("id") int id){
        int hang=studentService.delete(id);
        return "删除"+hang+"行成功!";
    }
}

6.8 浏览器测试即可

7 springboot整合jsp

7.1 创建springboot项目

7.2 引入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.zhiyou100</groupId>
    <artifactId>springboot05_jsp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot05_jsp</name>
    <properties>
        <java.version>8</java.version>
    </properties>
    <dependencies>
        <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.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
        </dependency>


        <!-- 添加jstl标签库依赖模块 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <!-- 使用jsp引擎,springboot内置tomcat没有此依赖 -->

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

7.3 创建文件夹 main/webapp/WEB-INF/jsps

在这里插入图片描述

7.4 指定web resources directory

project structure---选中当前项目的web--

在这里插入图片描述

7.5 通过idea的配置来添加web.xml

在这里插入图片描述

7.6 配置work directory

在这里插入图片描述

7.8 在核心配置文件中设置视图解析器

# 配置视图解析器
spring:
  mvc:
    view:
      prefix: /WEB-INF/jsps/
      suffix: .jsp

7.9 创建jsp

<head>
    <title>test01.jsp</title>
</head>
<body>
     <h1>test01</h1>
     请求参数 age=${param.age}<br/>
     请求域属性 n=${requestScope.n}<br/>
     请求session id=${pageContext.session.id}<br/>
</body>
<head>
    <title>test02.jsp</title>
</head>
<body>
     <h1>jstl表达式</h1>
      <table>
          <tr>
              <th>学号</th><th>名字</th><th>政治</th><th>性别</th><th>分数</th>
          </tr>
          <c:forEach var="stu" items="${requestScope.list}">
              <tr>
                  <td>${stu.id}</td>
                  <td>${stu.name}</td>
                  <td>${stu.dy}</td>
                  <td>${stu.sex}</td>
                  <td>${stu.score}</td>
              </tr>
          </c:forEach>
      </table>
</body>

7.10 创建action

package com.zhiyou100.action;

import com.zhiyou100.entity.Student;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@RequestMapping("/test01")
@Controller
public class Test01 {
    @RequestMapping("/m1.action")
    public String method01(int age, Model model){
        model.addAttribute("n",System.currentTimeMillis());
        return "demo01";
    }

    @RequestMapping("/m2.action")
    public String method02(Model model){
        List<Student> list=new ArrayList<>();
        for (int i = 0; i <10 ; i++) {
            list.add(new Student(i+1,"韩梅梅"+i,i%2==0?"男":"女",i+10f,i%2==0));
        }
        model.addAttribute("list",list);
        return "demo02";
    }
}
  • 实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public class Student  implements Serializable {
    private Integer id;
    private String name;
    private String sex;
    private Float score;
    private Boolean dy;
}

7.11 测试

在这里插入图片描述

在这里插入图片描述

8 使用springboot整合jdbc+jsp实现学生的crud

8.0 每个module整合jsp 都需要重新设置

参考段落7

8.1 创建springboot

8.2 添加依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.zhiyou100</groupId>
    <artifactId>springboot06_jdbc_jsp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot06_jdbc_jsp</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--引入jsp的依赖-->
        <!-- 添加jstl标签库依赖模块 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <!-- 使用jsp引擎,springboot内置tomcat没有此依赖 -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

8.3 完善目录

在这里插入图片描述

8.4 设置支持jsp的三个操作

  • 指定web resources directory
  • 配置work directory
  • 配置work directory

8.5 设置项目参数:核心配置文件

# 配置视图解析器
spring:
  mvc:
    view:
      prefix: /WEB-INF/jsps/
      suffix: .jsp
  # jdbc四大参数
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/db_1?charset=utf8
    username: root
    password: 123456

# 项目信息
server:
  servlet:
    context-path: /
  port: 8081

8.6 数据库

CREATE TABLE `student` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `score` FLOAT DEFAULT NULL,
  `dy` BIT(1) DEFAULT NULL,
  `sex` VARCHAR(255) DEFAULT NULL,
  `name` VARCHAR(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8;
INSERT INTO student VALUES(
    NULL,
    TRUNCATE(RAND()*100,1),
    RAND()>0.5,
    IF(RAND()>0.5,"男","女"),
    SUBSTRING(REPLACE(UUID(),"-",""),1,10));
SELECT * FROM student;

8.7 实体类

package com.zhiyou100.entity;
...
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public class Student   implements Serializable {
    private Integer id;
    private String name;
    private Float score;
    private String sex;
    private Boolean dy;
}

8.8 dao

package com.zhiyou100.dao;

import com.zhiyou100.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
@SuppressWarnings("all")
public class StudentDaoImp   implements  StudentDao{
    @Autowired
    private JdbcTemplate jdbcTemplate;
    public Student getOne(int id){
        return jdbcTemplate.query("select * from student where id=?",getMapper(),id).get(0);
    }
    public List<Student> getAll(){
        return jdbcTemplate.query("select * from student",getMapper());
    }
    public int add(Student s){
        return jdbcTemplate.update("insert into student(name,sex,score,dy) values(?,?,?,?)",s.getName(),s.getSex(),s.getScore(),s.getDy());
    }
    public int update(Student s){
        return jdbcTemplate.update("update student set name=?,sex=?,score=?,dy=? where id=?",s.getName(),s.getSex(),s.getScore(),s.getDy(),s.getId());
    }
    public int delete(int id){
        return jdbcTemplate.update("delete from student where id=?",id);
    }

    private RowMapper<Student> getMapper(){
        return new RowMapper<Student>() {
            @Override
            public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
                return new Student().setScore(rs.getFloat("score")).
                        setDy(rs.getBoolean("dy")).
                        setSex(rs.getString("sex")).
                        setName(rs.getString("name")).
                        setId(rs.getInt("id"));
            }
        };
    }
}

8.9 service

package com.zhiyou100.service;

import com.zhiyou100.dao.StudentDao;
import com.zhiyou100.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StudentServiceImp  implements  StudentService{
    @Autowired
    private StudentDao studentDao;

    @Override
    public Student getOne(int id) {
        return studentDao.getOne(id);
    }

    @Override
    public List<Student> getAll() {
        return studentDao.getAll();
    }

    @Override
    public int add(Student s) {
        return studentDao.add(s);
    }

    @Override
    public int update(Student s) {
        return studentDao.update(s);
    }

    @Override
    public int delete(int id) {
        return studentDao.delete(id);
    }
}

8.10 action

package com.zhiyou100.action;

import com.zhiyou100.entity.Student;
import com.zhiyou100.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/student")
public class StudentAction {
     @Autowired
    private StudentService studentService;

     @RequestMapping("/getAll.action")
     public String getAllMethod(Model model){
          model.addAttribute("list",studentService.getAll());
          return "student_manager";
     }
    @RequestMapping("/getOne/{id}.action")
    public String getOneMethod(@PathVariable("id") int id, Model model){
        model.addAttribute("stu",studentService.getOne(id));
        return "student_manager";
    }
    @RequestMapping("/update.action")
    public String updateMethod(Student student,Model model){
        studentService.update(student);
        model.addAttribute("message","修改成功!");
        return "student_manager";
    }
    @RequestMapping("/delete/{id}.action")
    public String deleteMethod(@PathVariable("id") int id, Model model){
        studentService.delete(id);
        model.addAttribute("message","删除成功!");
        return "student_manager";
    }
    @RequestMapping("/add.action")
    public String addMethod(Student student, Model model){
        studentService.add(student);
        model.addAttribute("message","添加成功!");
        return "student_manager";
    }
}

8.11 jsp

1 判断是否有list 没有list去action要
2 判断是否有提示信息 有就显示
3 显示list
4 创建一个表单 通过判断request域中是否有stu 来确定表单是添加还是修改
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
    <title>学生管理页面</title>
    <link rel="stylesheet" type="text/css" href="<c:url value='/css/student.css'/>"/>
</head>
<body>
   <c:if test="${empty list}">
       <jsp:forward page="/student/getAll.action"/>
   </c:if>
   <table>
       <c:if test="${not empty message}">
           <tr>
               <th style="color: red;font-weight: bold;" colspan="6">
                    ${message}
               </th>
           </tr>
       </c:if>
       <tr>
           <th>学号</th><th>名字</th><th>分数</th><th>性别</th><th>政治</th><th>操作</th>
       </tr>
       <c:forEach items="${list}" var="s">
            <tr>
                <td>${s.id}</td>
                <td>${s.name}</td>
                <td>${s.score}</td>
                <td>${s.sex}</td>
                <td>
                    <c:choose>
                        <c:when test="${s.dy}">
                            党员
                        </c:when>
                        <c:otherwise>
                            群众
                        </c:otherwise>
                    </c:choose>
                </td>
                <td>
                    <a href="<c:url value='/student/getOne/${s.id}.action'/>">修改</a> |
                    <a href="<c:url value='/student/delete/${s.id}.action'/>">删除</a>
                </td>
            </tr>
       </c:forEach>
       <tr>
           <th style="color: blue;font-weight: bold;" colspan="6">
               <input type="button" value="添加一个" οnclick="add();"/>
           </th>
       </tr>
   </table>
   <form action="" method="post" id="form_add_update">
       <input type="hidden" name="id" value="${stu.id}"/>
       <table id="tab_add_update" >
           <tr>
               <th>学生名字:</th>
               <td><input type="text" name="name" value="${stu.name}"/></td>
           </tr>
           <tr>
               <th>学生性别:</th>
               <td>
                   男:<input type="radio" name="sex" value="男"/> |
                   女:<input type="radio" name="sex" value="女"/>
               </td>
           </tr>
           <tr>
               <th>学生分数:</th>
               <td><input type="text" name="score" value="${stu.score}"/></td>
           </tr>
           <tr>
               <th>政治面貌:</th>
               <td>党员:<input type="radio" name="dy" value="true"/> |
                   群众:<input type="radio" name="dy" value="false"/></td>
           </tr>
           <tr>
               <th colspan="2">
                   <input type="reset" value="重填"/>
                   <input type="submit" value="提交">
               </th>
           </tr>
       </table>
   </form>
   <script type="text/javascript">
       $(function(){

             if("${stu}"){
                 $("#tab_add_update").show();
                 $("#form_add_update").attr("action","<c:url value='/student/update.action'/>");
                 $("#form_add_update input[type='submit']").val("修改");

                 //性别被选中
                 var sex="${stu.sex}";
                 $.each($("#form_add_update input[name='sex']"),function(i,n){
                      if($(n).val()==sex){
                          $(n).attr("checked","checked");
                      }
                 });

                 //政治面貌被选中
                 var dy="${stu.dy}";
                 $.each($("#form_add_update input[name='dy']"),function(i,n){
                     if($(n).val()==dy){
                         $(n).attr("checked","checked");
                     }
                 });

             }else{
                 $("#tab_add_update").hide();
             }
       });

       function add(){
           $("#tab_add_update").show();
           $("#form_add_update").attr("action","<c:url value='/student/add.action'/>");
           $("#form_add_update input[type='submit']").val("添加");
       }
   </script>
</body>
</html>

8.12 定义action 能跳转此jsp

package com.zhiyou100.action;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class WebAction {
    @RequestMapping("/")
    public String welcome(){
        return "student_manager";
    }
}

8.13 效果

在这里插入图片描述

9 freemarker

9.0 参考

https://blog.csdn.net/weixin_44454512/article/details/109877418

9.1 概念

模板引擎(这里特指用于Web开发的模板引擎)是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎就会生成一个标准的HTML文档。

FreeMarker是一款模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页、电子邮件、配置文件、源代码等)的通用工具。 它不是面向最终用户的,而是一个Java类库,是一款程序员可以嵌入他们所开发产品的组件。
学习和jsp完全相同:怎么获取数据+流程控制+函数

9.2 案例1: 获取域属性和请求参数

  • 创建springboot项目
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
  • 核心配置文件
spring.freemarker.tempalte-loader-path=classpath:/templates
spring.freemarker.cache=false
spring.freemarker.charset=utf-8
spring.freemarker.check-template-location=true
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=true
spring.freemarker.expose-session-attributes=true
spring.freemarker.request-context-attribute=request
spring.freemarker.suffix=.ftl
#使用url模板映射需要设置此属性
spring.freemarker.allow-request-override=true

  • action
package com.zhiyou100.action;

import com.zhiyou100.entity.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RequestMapping("/student")
@Controller
public class StudentAction {

    @RequestMapping("/getAll.action")
    public String getAll(HttpServletRequest req){
        List<Student>  list=new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            list.add(new Student(1000+i,"韩梅"+i,i+30f,i%2==0?"男":"女",i%2==0));
        }
        req.setAttribute("list",list);
        req.setAttribute("aa","a_request");
        req.getSession().setAttribute("bb","a_session");
        req.getServletContext().setAttribute("cc","a_application");
        //注意:属性名不能重复
        return "index01";
    }
}
  • 实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public class Student   implements Serializable {
    private Integer id;
    private String name;
    private Float score;
    private String sex;
    private Boolean dy;
}
  • 页面: /templates/index01.ftl
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>第一个freemarker页面</title>
</head>
<body>
     <#--
        freemarker注释:: # - -
        freemarker中获取域属性:${内置对象["属性名"]}
        freemarker内置对象:::Request:::request域对象
                            Session:::session域对象
                            Application:::servletContext域对象
                            RequestParamters:::请求参数对象
        注意:属性名不能重复
     -->
     <h1>freemarker中:正常使用:js css html</h1>
     <h1>freemarker中:获取域属性和请求参数</h1>

      request域对象:a:::${Request["aa"]}<br/>
      session域对象:a:::${Session["bb"]}<br/>
      application域对象:a:::${Application["cc"]}<br/>
      请求参数:::::age=${RequestParameters["age"]}:::n=${RequestParameters["n"]}<br/>

</body>
</html>
  • 测试

在这里插入图片描述

9.3案例2:流程控制

  • action
@RequestMapping("/m2.action")
public String method02(HttpServletRequest req){
    List<Student>  list=new ArrayList<>();
    for (int i = 0; i < 18; i++) {
        float score=(int)(Math.random()*200-50);
        list.add(new Student(1000+i,"韩梅"+i,score,i%2==0?"男":"女",i%2==0));
    }
    list.add(new Student(1002,null,30f,"圣",true));
    list.add(new Student(1001,null,30f,"妖",true));
    req.setAttribute("list",list);

    Map<String,Integer> map=new HashMap<>();
    map.put("k11",(int)(Math.random()*100));
    map.put("k12",(int)(Math.random()*100));
    map.put("k13",(int)(Math.random()*100));
    map.put("k14",(int)(Math.random()*100));
    map.put("k15",(int)(Math.random()*100));
    req.setAttribute("map",map);
    //注意:属性名不能重复
    return "index02";
}
  • index2.ftl
     <h1>流程控制:1 遍历集合</h1>
     <table>
         <tr>
             <th>顺序</th><th>学号</th><th>名字</th><th>分数</th><th>等级</th>
             <th>性别</th><th>称呼</th><th>政治</th>
         </tr>
         <#list Request["list"] as stu>
              <tr>
                  <td>${stu_index}</td> <!--对象名_index 获取当前对象在集合中的索引-->
                  <td>${stu.id}</td>
                  <td>
                      <#if stu.name??> <!--变量名?? 判断是否不为空-->
                           ${stu.name}
                      <#else>
                           无名
                      </#if>
                  </td>
                  <td>${stu.score}</td>
                  <td>
                      <#if stu.score lt 0 || stu.score gt 100>
                               无效
                          <#elseif  stu.score lt 60>
                               不及格
                          <#elseif  stu.score lt 70>
                               及格
                          <#elseif  stu.score lt 80>
                               良好
                          <#else>
                               优秀
                      </#if>
                  </td>
                  <td>${stu.sex}</td>
                  <td>
                      <#if stu.sex == "男">
                          帅哥
                          <#elseif stu.sex == "女">
                          美女
                          <#else>
                          妖精
                      </#if>
                  </td>
                  <td>
                      <#if stu.dy>
                           党员
                      <#else>
                           群众
                      </#if>
                  </td>
              </tr>
         </#list>
     </table>
     <h1>流程控制:2 九九乘法表</h1>
     <table>
         <#list 1..9 as i>
             <tr>
                 <#list 1..9 as j>
                     <td>
                         <#if j lte i>
                             ${i}*${j}=${i*j}
                         <#else>
                             &nbsp;
                         </#if>
                     </td>
                 </#list>
             </tr>
         </#list>
     </table>
     <!--遍历list 页可用直接如下::-->
     <!--注意:不能显示null值-->
     <#list list as ss>
         ${ss_index}:::${ss.id}<br/>
     </#list>

     <h1>遍历map</h1>
     <#list map?keys as k>
         ${k}::${map[k]}<br/>
     </#list>

9.3 案例3:函数

  • action
@RequestMapping("/m3.action")
public String method03(HttpServletRequest req){
    List<Student>  list=new ArrayList<>();
    for (int i = 0; i < 18; i++) {
        float score=(int)(Math.random()*200-50);
        list.add(new Student(1000+i,"韩梅"+i,score,i%2==0?"男":"女",i%2==0));
    }
    list.add(new Student(1002,null,30f,"圣",true));
    list.add(new Student(1001,null,30f,"妖",true));
    req.setAttribute("listStu",list);
    //注意:属性名不能重复
    return "index03";
}
  • index03.ftl
<h1>freemarker中:正常使用:js css html</h1>
<h1>函数的使用::日期</h1>
获取当前时间.now::::${.now?datetime}<br/>
获取当前时间.now::年月日::::${.now?date}<br/>
获取当前时间.now::时分秒::::${.now?time}<br/>
获取当前时间.now::时分秒::::${.now?string("yyyy-MM-dd HH:mm:ss")}<br/>

<h1>函数的使用::集合</h1>
<#assign arr1=[1,4,6,8,9,0,33,2,5,7]/>
遍历集合:::<#list arr1 as n>${n}::${n_index},</#list><br/>
获取元素个数:::${arr1?size}<br/>
获取第一个元素:::${arr1?first}<br/>
获取最后一个元素:::${arr1?last}<br/>
数组反转:::::<#list arr1?reverse as n>${n},</#list><br/>
数组排序:::::<#list arr1?sort as n>${n},</#list><br/>
数组排序:::::<#list arr1?sort?reverse as n>${n},</#list><br/>
按元素的指定属性排序:::<br/>
<#list Request["listStu"]?sortBy("score") as stu>
    ${stu}<br/>
</#list>

<h1>函数的使用::字符串</h1>
<#assign str="abc123456abcABCDEFG"/>
字符串长度:::${str?length}<br/>
字符串转化为大写:::${str?length}<br/>
字符串首字母大写:::${str?uncapFirst}<br/>
字符串所有字母大写:::${str?upperCase}<br/>
字符串所有字母小写:::${str?lowerCase}<br/>
字符串获取元素下标:::${str?indexOf("a")}<br/>
字符串从指定索引处找:::${str?indexOf("a",5)}<br/>
字符串去除两边空格:::${str?trim}<br/>
字符串字符替换:::${str?replace("a","-")}<br/>
字符串判断头:::${str?startsWith("abc")?c}<br/>
字符串判断尾:::${str?endsWith("abc")?c}<br/>
字符串切割:::${str?split("a")?size}<br/>

9.4 其他内容

    <h1>自己定义变量</h1>
    <#assign hehe="呵呵"/>  <!--定义一个变量::类似于jsp的 set标签-->
    <h1>空值判断</h1>
    <#if hehe??>
        hehe=${hehe}
        <#else>
        hehe变量不存在
    </#if>
    <h1>空值转换</h1>
    ${haha!"haha没值"}<br/>
    ${hehe!"hehe没值"}<br/>
    <h1>不能直接输出boolean</h1>
    <#assign ab=true/>
    ab=${ab?c}<br/>
    ab=${ab?string("对","错")}<br/>

    <h1>运算符:::比较运算符::+ - * / %</h1>
    1+1=${1+1}<br/>
    3-1=${3-1}<br/>
    2*3=${2*3}<br/>
    6*2=${6*2}<br/>
    5%3=${5%3}<br/>
    <h1>运算符:::逻辑运算符::&& || !</h1>
    ${(1 gt 0 && 2 lt 3)?c}<br/>
    ${(1 gt 0 || 2 lt 3)?c}<br/>
    ${(!true)?c}<br/>

    <h1>运算符:::比较运算符::gt lt gte lte == !=  </h1>
    ${(1 != 2)?c}<br/>
    ${(1 == 2)?c}<br/>
    ${(1 lt 2)?c}<br/>
    ${(1 lte 2)?c}<br/>
    ${(1 gt 2)?c}<br/>
    ${(1 gte 2)?c}<br/>
    <#assign c="abc"/>
    ${(c == "abc")?c}<br/>
       
    <h1>获取项目路径:request.contextPath</h1>
    <a href="${request.contextPath}/hehe">hqhq</a><br/>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值