我正在做一个客户端/服务器的项目,我使用的是spring Boot 和angular。
所以我有一个表单,我想从输入字段中获取数据并将其发送到后端,我的数据库(mySQL),但问题是它只在我的数据库中添加空字段。angular.io
表单输入示例:
<div class="form-group">
<label for="body">Body:</label>
<input type="text" class="form-control" id="body"
[ngModel]="article?.body" (ngModelChange)="article.body = $event" name="body">
</div>
字符串
我想添加的文章的模型类:
export class Article {
id: string;
title: string;
abstract_art: string;
writer: string;
body: string;
}
型
我添加的组件:
@Component({
selector: 'app-add',
templateUrl: './add-article.component.html'
})
export class AddArticleComponent {
article: Article = new Article();
writers: Writer[];
constructor(private router: Router, private articleService: ArticleService) {
}
createArticle(): void {
console.log(this.article);
this.articleService.createArticle( this.article).subscribe( data => { alert('Article created successfully.');
});
console.log('function called!');
}
get diagnostic() { return JSON.stringify(this.article); }
}
型
服务等级:
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json',
'Authorization': 'my-auth-token'})
};
@Injectable()
export class ArticleService {
constructor(private http: HttpClient) {}
// private userUrl = 'http://localhost:8080/articles';
private articleUrl = '/api';
public getArticles() {
return this.http.get<Article[]>(this.articleUrl);
}
public deleteArticle(article) {
return this.http.delete(this.articleUrl + '/' + article.id, httpOptions);
}
public createArticle(article) {
// const art = JSON.stringify(article);
console.log(article);
return this.http.post<Article>(this.articleUrl, article);
}
}
型
现在是后端。Article Class
@Entity
@Getter @Setter
@NoArgsConstructor
@ToString @EqualsAndHashCode
@Table(name="article")
public class Article {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(name="title")
private String title;
@Column(name="abstract_art")
private String abstract_art;
@Column(name="writer")
private String writer;
@Column(name="body")
private String body;
public Article(String title,String abstract_art, String writer, String body) {
this.title = title;
this.body = body;
this.abstract_art = abstract_art;
this.writer = writer;
}
}
型
仓库:
@RepositoryRestResource
//@CrossOrigin(origins = "http://localhost:4200")
public interface ArticleRepository extends JpaRepository<Article,Integer> {
}
型
文章服务:
@Service
public class ArticleServiceImpl implements ArticleService {
@Autowired
private ArticleRepository repository;
@Override
public Article create(Article article) {
return repository.save(article);
}
@Override
public Article delete(int id) {
Article article = findById(id);
if(article != null){
repository.delete(article);
}
return article;
}
@Override
public List<Article> findAll() {
return repository.findAll();
}
@Override
public Article findById(int id) {
return repository.getOne(id);
}
@Override
public Article update(Article art) {
return null;
}
}
型
控制器:
@RestController
@RequestMapping({"/api"})
public class ArticleController {
@Autowired
private ArticleService article;
//Get all articles
@GetMapping
public List<Article> listAll(){
return article.findAll();
}
// Create a new Article
//@PostMapping
@PostMapping
public Article createArticle(Article art) {
return article.create(art);
}
// Get a Single Article
@GetMapping(value="/{id}")
public Article getArticleById(@PathVariable("id") int id ){
return article.findById(id);
}
// Delete a Note /art/
@DeleteMapping(value = "/{id}")
public void deleteArticle(@PathVariable("id") int id) {
article.delete(id);
}
@PutMapping
public Article update(Article user){
return article.update(user);
}
}
型
In the picture you can see that it creates my json object but when i'm adding it to the database it only adds null values.
附加信息:我可以从数据库中获取数据,也可以从数据库中删除数据。
顺便说一句,这是我的第一个帖子,所以我很抱歉,如果我错过了一些张贴指南。提前感谢你的答案。有一个好的!
2条答案
按热度按时间nom7f22z1#
@RestController是一个方便的注解,它只不过添加了**@Controller和@ResponseBody**注解,并允许类接受发送到其路径的请求
@DOCS
@ResponseBody
annotation告诉控制器返回的对象会自动序列化为JSON并传递回HttpResponse对象。@RequestBody
注解将HttpRequest主体Map到传输或域对象,从而实现将入站HttpRequest主体自动化为Java对象。你错过了
@RequestBody
@RequestBody
标记文章输入是从POST请求的主体/内容中检索的。这是GET
和POST
之间的一个显著差异,因为GET
请求不包含主体。修改代码
字符串
inb24sb22#
由于命名的原因,你也会看到这样奇怪的东西。我认为JPA假设像my_Stuff这样的名字是my_Stuff。
所以我总是在完成构建控制器后使用Postman来测试帖子或获取。
当Postman返回原始JSON时,请注意所有属性的命名,因为大小写很重要。