Python中文网

一个关于 编程问题的解答网站.

有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在使用Thymeleaf和JavaScript进行输入验证时,如何访问另一个类中某个类中的变量?

我有动物课:

@Entity
public class Animal {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    private String name;
    @Autowired
    private Species species;
    @Autowired
    private Habitat habitat;
    //constructors, getters, setters, unrelated variables omitted 

我的栖息地和物种类别:

    @Embeddable
    public class Habitat {
    private String continent;
    private String biome;
    //constructors, getters, setters omitted 


    @Embeddable
    public class Species {
    private String commonName;
    private String scientificName;
    //constructors, getters, setters omitted 

我真正的问题在于访问Thymeleaf变量时的JavaScript。这是我的HTML页面:

   <html xmlns:th="http://www.thymeleaf.org">
   <head>
   <meta charset="ISO-8859-1">
   <title>Menu</title>
   <script th:inline="javascript">
       var name = /*[[${animal.name}]]*/; // WORKS FINE
       //PROBLEM STARTS HERE
       var commonName = /*[[${animal.species.commonName}]]*/; //DOESN'T WORK
       // var commonName = /*[[${animal.commonName}]]*/; ALSO DOESN'T WORK

       var continent = /*[[${animal.habitat.continent}]]*/; //DOESN'T WORK
       //  var continent = /*[[${animal.continent}]]*/; ALSO DOESN'T WORK

       //FUNCTION WILL WORK WITHOUT commonName AND continent
       function checkInput() {
           if(name === "" || commonName === "" || continent === "") {
           alert("FALSE");
           return false;
       }
       else {
           alert("TRUE");
           return true;
       }
   }

   //EVERYTHING ELSE IS FINE

   </script>

   </head>
   <body>

   <form th:object="${animal}" th:action="@{/inputAnimal}" th:method="post" th:onsubmit="return checkInput();">

   Name: <input id="name" name="name" size="20" type="text"><br />
   Species(common): <input id="commonName" name="species.commonName" size="20" type="text"><br />
   Continent: <input id="continent" name="habitat.continent" size="20" type="text"><br />

   <input type="submit" value="Submit"/>
   </form>
   </body>
   </html>

“commonName”和“Continume”变量是另一个类的一部分,但到目前为止可以访问。这些字段正被添加到我的数据库中。问题在于验证他们的输入,我认为我在JS中没有正确访问他们

我在JS中的“name”变量非常有效,当该字段留空时,表单将不会提交。然而,当我以同样的方式添加“commonName”和“Continental”时,在localhost上运行页面会显示为一个空白的白色页面。我相信这就是我试图从嵌入式类访问变量的方式

当用户将这三个字段留空时,我想提醒他们。有人能告诉我正确的方法吗?谢谢!


共 (0) 个答案