- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有两个 java 模型
作为玩家和团队。我有一个 Controller 类。当我从用户界面通过 ajax 发送 post 请求时出现错误。我已经解决了诸如 CORS
之类的错误。但有一个错误我无法解决; knockout.js
调试错误和 post 请求没有发生。我的数据库没有任何变化。我共享了模型类、 Controller 类、html 和 javascript
文件。
我需要改变什么?你能帮忙吗?
玩家模型
@Entity
@Table(name = "player")
public class Player{
@Id
@GeneratedValue
@NotNull
@Column
private int id;
@NotNull
@Column
private String playerName;
@NotNull
@Column
private String playerSurname;
@Column
private int playerAge;
public String getPlayerName() {
return playerName;
}
public void setPlayerName(String playerName) {
this.playerName = playerName;
}
public String getPlayerSurname() {
return playerSurname;
}
public void setPlayerSurname(String playerSurname) {
this.playerSurname = playerSurname;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getPlayerAge() {
return playerAge;
}
public void setPlayerAge(int playerAge) {
this.playerAge = playerAge;
}
}
团队模型
@Entity
@Table(name = "team")
public class Team {
@Id
@GeneratedValue
@NotNull
@Column
private int id;
@NotNull
@Column
private String teamName;
@Column
private String teamCountry;
public Team(){
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTeamName() {
return teamName;
}
public void setTeamName(String teamName) {
this.teamName = teamName;
}
public String getTeamCountry() {
return teamCountry;
}
public void setTeamCountry(String teamCountry) {
this.teamCountry = teamCountry;
}
@ManyToOne
private Player player;
public Player getPlayer() {
return player;
}
public void setPlayer(Player player) {
this.player = player;
}
}
Controller
@CrossOrigin(origins = "http://localhost:8000/")
@RestController
public class TeamController {
@Autowired
PlayerRepository playerRepository;
@Autowired
TeamRepository teamRepository;
@RequestMapping("/")
public void main() {
//create players by manual
Player messi = new Player();
Player ronaldo = new Player();
Player ozil = new Player();
messi.setPlayerName("Lionel");
messi.setPlayerSurname("Messi");
messi.setPlayerAge(31);
ronaldo.setPlayerName("Cristiano");
ronaldo.setPlayerSurname("Ronaldo");
ronaldo.setPlayerAge(32);
ozil.setPlayerName("Mesut");
ozil.setPlayerSurname("Ozil");
ozil.setPlayerAge(29);
this.playerRepository.save(messi);
this.playerRepository.save(ronaldo);
this.playerRepository.save(ozil);
//create teams by manual
Team barcelona = new Team();
Team juventus = new Team();
Team arsenal = new Team();
barcelona.setTeamName("Barcelona");
barcelona.setTeamCountry("Spain");
barcelona.setPlayer(messi);
juventus.setTeamName("Juventus");
juventus.setTeamCountry("Italy");
juventus.setPlayer(ronaldo);
arsenal.setTeamName("Arsenal");
arsenal.setTeamCountry("England");
arsenal.setPlayer(ozil);
this.teamRepository.save(barcelona);
this.teamRepository.save(juventus);
this.teamRepository.save(arsenal);
}
//**PLAYER**
@GetMapping(value="/getAllPLayers")
public List<Player> getAllPlayers(){
return playerRepository.findAll();
}
@PostMapping(value="getPlayerByName")
public List<Player> getPlayerByName(@RequestParam("playerName") String playerName){
return playerRepository.findByPlayerName(playerName);
}
@PostMapping(value="getPlayerBySurname")
public List<Player> getPlayerBySurname(@RequestParam("playerSurname") String playerSurname){
return playerRepository.findByPlayerSurname(playerSurname);
}
@PostMapping(value="getPlayerByAge")
public List<Player> getPlayerByAge(@RequestParam("playerAge") int playerAge){
return playerRepository.findByPlayerAge(playerAge);
}
@PostMapping(value="createNewPlayer")
public Player createNewPlayer(@Valid @RequestBody Player player) {
return playerRepository.save(player);
}
//**TEAM**
@GetMapping(value="/getAllTeams")
public List<Team> getAllTeams(){
return teamRepository.findAll();
}
@PostMapping(value = "/getTeamsByName")
public List<Team> getTeamByName(@RequestParam("teamName") String teamName){
return teamRepository.findByTeamName(teamName);
}
@PostMapping(value = "/getTeamsByCountry")
public List<Team> getTeamByCountry(@RequestParam("teamCountry") String teamCountry){
return teamRepository.findByTeamCountry(teamCountry);
}
@PostMapping(value="/createNewTeam")
public Team createNewTeam(@Valid @RequestBody Player player,@RequestBody Team team) {
playerRepository.save(player);
team.setPlayer(player);
return teamRepository.save(team);
}
}
配置
@Configuration
@EnableWebMvc
public class WebConfig implements Filter,WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
System.out.println("WebConfig; "+request.getRequestURI());
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With,observe");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Expose-Headers", "Authorization");
response.addHeader("Access-Control-Expose-Headers", "USERID");
response.addHeader("Access-Control-Expose-Headers", "ROLE");
response.addHeader("Access-Control-Expose-Headers", "responseType");
response.addHeader("Access-Control-Expose-Headers", "observe");
System.out.println("Request Method: "+request.getMethod());
if (!(request.getMethod().equalsIgnoreCase("OPTIONS"))) {
try {
chain.doFilter(req, res);
} catch(Exception e) {
e.printStackTrace();
}
} else {
System.out.println("Pre-flight");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST,GET,DELETE,PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Access-Control-Expose-Headers"+"Authorization, content-type," +
"USERID"+"ROLE"+
"access-control-request-headers,access-control-request-method,accept,origin,authorization,x-requested-with,responseType,observe");
response.setStatus(HttpServletResponse.SC_OK);
}
}
}
玩家 repo
public interface PlayerRepository extends JpaRepository<Player, Integer>{
List<Player> findByPlayerName(String playerName);
List<Player> findByPlayerSurname(String playerSurname);
List<Player> findByPlayerAge(int playerAge);
}
团队 repo
public interface TeamRepository extends JpaRepository<Team, Integer>{
List<Team> findByTeamName(String teamName);
List<Team> findByTeamCountry(String teamCountry);
}
发布 HTML 页面
<!DOCTYPE HTML>
<html>
<head>
<title>Team Management</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" />
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<script src="js/restGetPlayer.js"></script>
<script src="js/restGetTeam.js"></script>
<script src="js/postTeam.js"></script>
</head>
<body>
<div class="container">
<h3 style="color: darkolivegreen" align="center">Create a new team</h3>
<div class"main-block>
<form id="teamForm" class="form-inline" style="margin:20px 20px 20px 20px">
<div class="form-group">
<label for="playerName" style="margin-left:20px; margin-right:5px">Player Name:</label>
<input type="text" class="form-control" id="playerName" placeholder="Enter player name"/>
</div>
<br>
<div class="form-group">
<label for="playerSurname" style="margin-left:20px; margin-right:5px">Player Surname:</label>
<input type="text" class="form-control" id="playerSurname" placeholder="Enter player surname"/>
</div>
<div class="form-group">
<label for="playerAge" style="margin-left:20px; margin-right:5px">Player Age:</label>
<input type="text" class="form-control" id="playerAge" placeholder="Enter player age"/>
</div>
<br style="clear: both;">
<div class="form-group">
<label for="teamName" style="margin-right:5px">Team Name:</label>
<input type="text" class="form-control" id="teamName" placeholder="Enter team name"/>
</div>
<br>
<div class="form-group">
<label for="teamCountry" style="margin-left:20px; margin-right:5px">Team Country:</label>
<input type="text" class="form-control" id="teamCountry" placeholder="Enter team country"/>
</div>
<br>
<hr>
<button type="submit" class="btn btn-default" style="margin-left:20px; margin-right:5px" >Submit Team</button>
</form>
</div>
<div class="col-sm-7" style="margin:20px 0px 20px 0px">
<button id="getAllTeams" class="btn btn-primary">Get Team Information</button>
<div id="getResultDiv3" style="padding:20px 10px 20px 50px">
<ul class="list-group">
</ul>
</div>
</div>
</div>
<style>
.container {
max-width: 400px;
width: 100%;
margin: 0 auto;
position: relative;
}
#contact {
background: #F9F9F9;
padding: 25px;
margin: 150px 0;
box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0 rgba(0, 0, 0, 0.24);
}
</style>
<script type="text/javascript" src="js/libs/require/require.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
AJAX POST
$( document ).ready(function() {
$("#teamForm").submit(function(event) {
event.preventDefault();
ajaxPost();
});
function ajaxPost(){
var formData = {
playerName : $("#playerName").val(),
playerSurname : $("#playerSurname").val(),
playerAge : $("#playerAge").val(),
teamName : $("#teamName").val(),
teamCountry : $("#teamCountry").val()
}
$.ajax({
type : "POST",
contentType : "application/json",
url : "http://localhost:8080" + "/createNewTeam",
data : JSON.stringify(formData),
dataType : 'json',
success: function(result){
alert("Teams loaded!");
console.log(result);
$('#getResultDiv3 ul').empty();
var tableTitle = "<h2><strong>Team List</strong></h2>";
var teamList = "<table border='1'>";
teamList += "<tr><td><strong>Team Name</strong></td><td><strong>Team Country</strong></td><td><strong>Player Name</strong></td><td><strong>Player Surname</strong></td><td><strong>Player Age</strong></td></tr>";
$.each(result, function(i, teams){
teamList +="<tr>";
teamList +="<td>"+teams.teamName +"</td>";
teamList +="<td>"+teams.teamCountry+"</td>";
teamList +="<td>"+teams.player.playerName+"</td>";
teamList +="<td>"+teams.player.playerSurname+"</td>";
teamList +="<td>"+teams.player.playerAge+"</td>";
teamList +="</tr>";
});
teamList +="</table>";
$('#getResultDiv3').append(tableTitle, teamList)
console.log("Success: ", result);
},
error : function(e) {
$("#getResultDiv3").html("<strong>Error</strong>");
console.log("ERROR: ", e);
}
});
resetData();
}
function resetData(){
$("#playerName").val("");
$("#playerSurname").val("");
$("#playerAge").val("");
$("#teamName").val("");
$("#teamCountry").val("");
}
})
MainController.js
/**
* @license
* Copyright (c) 2014, 2019, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
/*
* Your application specific code will go here
*/
define(['ojs/ojresponsiveutils', 'ojs/ojresponsiveknockoututils', 'knockout', 'ojs/ojknockout'],
function(ResponsiveUtils, ResponsiveKnockoutUtils, ko) {
function ControllerViewModel() {
var self = this;
// Media queries for repsonsive layouts
var smQuery = ResponsiveUtils.getFrameworkQuery(ResponsiveUtils.FRAMEWORK_QUERY_KEY.SM_ONLY);
self.smScreen = ResponsiveKnockoutUtils.createMediaQueryObservable(smQuery);
// Header
// Application Name used in Branding Area
self.appName = ko.observable("Oracle JET + REST API");
// User Info used in Global Navigation area
self.userLogin = ko.observable("admin@oracle.com");
// Footer
function footerLink(name, id, linkTarget) {
this.name = name;
this.linkId = id;
this.linkTarget = linkTarget;
}
self.footerLinks = ko.observableArray([
new footerLink('About Oracle', 'aboutOracle', 'http://www.oracle.com/us/corporate/index.html#menu-about'),
new footerLink('Contact Us', 'contactUs', 'http://www.oracle.com/us/corporate/contact/index.html'),
new footerLink('Legal Notices', 'legalNotices', 'http://www.oracle.com/us/legal/index.html'),
new footerLink('Terms Of Use', 'termsOfUse', 'http://www.oracle.com/us/legal/terms/index.html'),
new footerLink('Your Privacy Rights', 'yourPrivacyRights', 'http://www.oracle.com/us/legal/privacy/index.html')
]);
}
return new ControllerViewModel();
}
);
图1: Adding Player
最佳答案
回答你的问题,它没有做任何事情,因为你没有发送参数 Player (必须有效),因为你使用的表单不是你应该这样做的方式。 (请求参数通过 url 发送,您的表单应通过 @RequestBody 执行)
查看此帖子以获取信息。 Can I use @Requestparam annotation for a Post request?
我会做这样的事情:
在我的 Controller 上,由于我只能有一个 @RequestBody,但我的表单发送一个包含多种类型对象数据的对象,我将执行 Dto
类似这样的事情:
@PostMapping(value="/createNewTeam")
public Team createNewTeam(@Valid @RequestBody PayloadDto payloadDto) {
final Player player = new Player();
player.setPlayerName(payloadDto.playerName);
// fill player information
final Team team = new Team();
// fill team information...
playerRepository.save(player);
return teamRepository.save(team);
}
您的 PayloadDto 对象必须包含您发送的所有属性..
public class PayloadDto{
@JsonProperty("playerName")
public String playerName;
@JsonProperty("playerSurname")
public String playerSurname;
// .. more player and team properties
}
确保 jsonProperty("propertyName) 与您发送信息时使用的名称相同
关于javascript - 用户界面中的 Spring boot AJAX POST 请求和 knockout.js 调试错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57304996/
我试图通过屏幕截图捕获带有突出显示的元素,但在屏幕截图中,该元素不带有突出显示。有谁知道解决办法吗?当我捕获文本时会出现突出显示:automatests@gmail.com 查看我的代码: Utili
大家好,我是编码的新手,我正在和一位老师一起上 Java 入门课,希望您已经了解一切。我必须对冰雹序列进行编码,它表示为: 选择一些正整数并将其命名为 n。如果 n 是偶数,则将其除以二。如果 n 是
如果存在名称相同的SCOM组,则尝试制作一个请求更多信息(组ID)的脚本: function myFunction { [CmdletBinding()] Param(
我有这张表: id | CUPNAME | FRENCHNAME 1 | 2 | null 2 | null | 4 我想从非空的 CUPNAME 和 FRENCHNAME 中提
我是 Collection View 的新手,想知道这是否是创建它们的最佳方式,我还想了解一些关于从哪里转到启用分页的详细 View 的建议。 #import "MarbleCollectionVie
好的,这是非常好的 jquery slider 。 http://srobbin.com/jquery-plugins/pageslide 我所做的是 http://mbu.mn/test 问题来了。
...有人可以解释一下区别吗? 我在命令提示符下输入的内容: sys.path.append('M:/PythonMods') import qrcode myqr = qrcode.make("ra
我不时在我的服务器上运行 bash 脚本,我正在尝试编写一个脚本来监视日志文件夹并在文件夹超出定义的容量时压缩日志文件。我知道有更好的方法来做我目前正在尝试做的事情,非常欢迎您提出建议。下面的脚本抛出
我是 Groovy & Grails 的新手,我觉得事情不必那么难看……那么我怎样才能让这段代码更好看呢? 这是一个 Grails Controller 类,去掉了一些无趣的部分。尽量不要太挂断我的
关闭。这个问题需要更多focused .它目前不接受答案。 想改善这个问题吗?更新问题,使其仅关注一个问题 editing this post . 7年前关闭。 Improve this questi
在这个查询中,除了 5 个连接表之外,我试图使用第 6 个表“Days”将值与连接中的三个表进行比较。但它给了我错误,我不能在连接中使用子查询。 select a.ID, a.Name, a.AMT,
我不想通过 Xpath 提取,我想要更清晰的代码。谢谢我的世界兄弟 来自 Xpath,好的!! Assert.assertEquals("Digite um e-mail ou número de t
这个问题已经有答案了: Google Map is not loading due to inflate exception (3 个回答) 已关闭 9 年前。 我知道有很多关于此的帖子,但我就是无法
我的问题.. a.) 使用内存分配创建一个 float 组来存储 GPA 分数10名学生。为其分配值(您的选择) b.) 找出该数组中的最大 GPA。 c.) 将此数组的内容写入文件 alloc.tx
我最近要制作 Sequelize 。 我有 2 个表,data_track 和 car_detail。我想尝试关联那 2 个表,但它从未关联过。 总是返回错误SequelizeEagerLoading
我有一些代码在 LINQ 中根本无法工作的问题,但它确实可以作为一个简单的 for..each 工作。任何解释和解决方案将不胜感激。 我有 3 个类,Users、User 和 UserPermissi
我正在设计我的第一个大型数据库,并想检查我是否可以提供表关系。 我正在设计一个网络应用程序,其中 用户可以在团队中玩游戏 每个游戏都有其类别 用户为游戏创建他们的团队并选择他们的团队类别 每个游戏都启
我很抱歉成为一个 CSS 菜鸟,希望有人能指导我正确的方向。 我需要帮助的网页可以在 http://filefx.com 找到 当您点击该页面时,您会注意到“选择文件”图标和“上传文件”图标不在同一行
我已经尝试过这个我在网上找到的演示代码练习并创建了这个 slider ,使用滚动条更容易获得它,因为它们已经是为此制作的脚本。现在我正在尝试修改此脚本及其 css,以将滚动条更改为左右两侧的箭头。我已
最近我对 CSS 很感兴趣。学习不同的东西。 我正在尝试像这样放置三个 div: http://i.stack.imgur.com/miN9G.png 我得到的: http://i.stack.img
我是一名优秀的程序员,十分优秀!