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
arr1 :
- 1
- 3
- 6
- 8
- 11
- 13
arr2 : [ 11.3 , 12.6 , 19.5 , 12 , 45 , 11 , 13 ]
teacher1 :
tid : 1001
tname : 张三
tsubject : 数学
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
@RequestMapping ( "/test01" )
public class Test01 {
@Autowired
private Student student;
@GetMapping ( "/m1.action" )
public Student method01 ( ) {
return student;
}
}
2.4 结果
2.5 老师对象
@Component
@ConfigurationProperties ( prefix = "stu1.teacher1" )
public class Teacher implements Serializable {
private Integer tid;
private String tname;
private String tsubject;
. . .
}
@Autowired
private Teacher teacher;
@GetMapping ( "/m2.action" )
public Teacher method02 ( ) {
return teacher;
}
效果
3 属性集文件配置信息的读取
3.1 默认文件:application.properties
@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 {
private Integer tid;
private String tname;
private String tsubject;
. . .
}
@Autowired
private Teacher2 teacher2;
@GetMapping ( "/m3.action" )
public Teacher2 method03 ( ) {
return teacher2;
}
3.2 自定义文件:config/hehe.properties
在启动类上加@PropertySource指定自定义配置文件的位置即可
配置文件:/config/hehe.properties
@SpringBootApplication
@PropertySource ( "classpath:config/hehe.properties" )
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;
. . .
}
@Autowired
private Teacher3 teacher3;
@GetMapping ( "/m4.action" )
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 来指定环境的名字
spring :
profiles :
active : t
---
server :
port : 8081
servlet :
context-path : /springboot03_test
spring :
config :
activate :
on-profile : t
---
server :
port : 8082
servlet :
context-path : /springboot03_development
spring :
config :
activate :
on-profile : d
---
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" )
@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 {
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
@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) ;
}
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/>
</ 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>
< dependency>
< groupId> javax.servlet</ groupId>
< artifactId> jstl</ artifactId>
</ dependency>
< 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/>
</ 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>
< dependency>
< groupId> javax.servlet</ groupId>
< artifactId> jstl</ artifactId>
</ dependency>
< 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
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: 获取域属性和请求参数
< 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
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:流程控制
@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" ;
}
< 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>
< 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>
</ #if>
</ td>
</ #list>
</ tr>
</ #list>
</ table>
< #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:函数
@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" ;
}
< 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 = " 呵呵" />
< 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/>