上一节,我们搭建好环境。现在来定义本项目所需的model book类。代码如下:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.GenerationType;;
@Entity
public class Book {
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String bookName;
private String author;
private String details;
private String imageURL; //用于放图片的url
private String url; //本地计算机中书的路径
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
@Entity指数据库表对应的实体类,如果数据库中没有对应的表,spring boot启动后会在数据库创建相应的表。 @Id声明此属性为主键 @GeneratedValue 指定主键的生成策略。有如下四个值 TABLE:使用表保存id值 IDENTITY:identitycolumn SEQUENCR :sequence AUTO:根据数据库的不同使用上面三个 这个时候启动springboot程序,book数据库中增加了一张book表。
接下来我们开始创建一个上传书籍信息的网页。页面相当简陋,submit.jsp
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Insert title here</title>
</head>
<body>
<!--form表單里 -->
<div class="back">
<form action="/admin/add" method="post" id="book">
<div class="from-goup">
<label for="bookName">BookName:</label>
<input type="text" id="bookName" name="bookName"/>
</div>
<div class="from-goup">
<label for="authorName">AuthorName:</label>
<input type="text" id="author" name="author"/>
</div>
<div class="from-goup">
<label for="image">Image:</label>
<input type="text" id="imageURL" name="imageURL" />
</div>
<div class="from-goup">
<label for="URl">URL:</label>
<input type="text" id="url" name="url"/>
</div>
<div class="from-goup">
<div class="from-goup">
<label for="detail">Detail:</label>
<span>
<textarea rows="5" cols="30" id="details" name="details" style="overflow-y:hidden;overflow-x:hidden;resize:none" wrap="hard"></textarea>
</span>
</div>
<button type="submit">submit</button>
</div>
</form>
</div>
</body>
</html>
但是由于spring boot不直接支持jsp.所以我们在application.properties中加入
spring.mvc.view.prefix= /WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
并且在pom.xml里添加
<!--对jsp的支持 -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!--配置jsp jstl的支持 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
我把jsp放在src/main/webapp/WEB-INF/jsp/文件夹下。提交表单后会访问action="/admin/add"。 所以接下来我们进行后台处理。