简体   繁体   中英

Java- How to declare attribute in HTML file?

How do declare a attribute in a HTML file then use it in a java class to display a error message for example? working with .jsp files i know that you need to use ${example} in the .jsp file. What is the correct way in HTML files? I want to add the message in the else statement before "return Login.html" I know that .jsp is basicly HTML code but somehow it doesnt work using ${example} in .html files. I have tried model.put("example","something something") but it doesn't seem to work.

Using the class LoginController.java:

@Controller
public class LoginController {

@Autowired
private UserValidationService userValidationService;

@RequestMapping(value="/", method = RequestMethod.GET)
private String getLoginPage() {
    return "Login.html";
}


@RequestMapping(method = RequestMethod.GET)
private String handleLoginRequests(@RequestParam String name, @RequestParam String password, ModelMap model) {
    if(userValidationService.isUserValid(name,password))
        return "Welcome.html";
    else

        return "Login.html";
}

}

The HTML file is :

<form action="/login">
    <br>
    <br>
    <br>
    <br>
    <div align="center">
        <font size="6" color="white"><i><b>Welcome! Please Login</b></i></font> <br>
        <br>
        <br> <font color="white" size="4"><i>Enter Name</i></font> <br>
        <input type="text" name="name"/> <br>
        <br> <font color="white" size="4"><i>Enter Password</i></font> <br>
        <input type="password" name="password"/> <br><br>

        <input type="submit" name="Submit" value="Login"
               style="height: 40px; width: 85px"/>
    </div>

</form>

<form action="/Signup">
    <div align="center" style="margin-right:auto;margin-left:auto;">
        <input type="submit" name="Signup" value="Sign up" style="height:40px; width:85px"/>
    </div>
    <p align="center">
        ${example}
    </p>

</form>

Unfortunately, you cannot have attributes in HTML. That is the main difference between HTML and JSP. HTML pages are static, whereas JSPs are dynamic

Putting a value into the model was the right thing to do.

model.put("example","something something")

But then in your template, you got the syntax wrong. If you use Spring with Spring-Boot, your default template engine is Thymeleaf . Simply displaying the example value could be done like this:

<span th:text="${example}">some_text_to_be_replaced_by_model</span>

There is a detailed tutorial on Thymeleaf/Spring integration on the Thymeleaf website as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM