点击按钮,通过javascript调用JSP页面

时间:2017-10-09 08:29:10

标签: javascript java jsp model-view-controller buttonclick

我目前正在开发一个MVC程序,当用户从home.jsp登录时,我需要调用login.jsp页面。我已经编写了用于呈现视图的登录和家庭控制器的代码。但我不确定如何打电话给控制器'请求通过我的资源下的custom.js javascript文件进行映射。

custom.js

document.getElementById('login_btn').addEventListener("click", function() {
    authorizationCheck();
}, false);


function authorizationCheck()
{
    var username = document.getElementById('username_txt').value;
    var password = document.getElementById('password_txt').value;

    if(username == "admin" && password == "123")
    {
       //code to load the home.jsp
    }
}

HomeController.java

@Controller
public class HomeController {

    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

    /**
     * Simply selects the home view to render by returning its name.
     */

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String login(Locale locale, Model model) {   
        return "login";
    }

    @RequestMapping(value = "/home", method = RequestMethod.GET)
    public String home(Locale locale, Model model) {
        logger.info("Welcome home! The client locale is {}.", locale);

        return "home";
    }
}

我对这个框架很新。因此,任何有关如何在按钮点击时加载不同jsp的建议都将受到高度赞赏。

3 个答案:

答案 0 :(得分:1)

你可以在这里看到一个简单的例子: https://dzone.com/articles/spring-mvc-example-for-user-registration-and-login-1

如果您在JS中选中后只需要显示主页,则可以使用:

if(username == "admin" && password == "123")
{
    document.location.href = "home";
}

答案 1 :(得分:0)

使用它,它将导航到弹簧控制器并显示所需的页面

if(username == "admin" && password == "123")
{
    document.location.href = "/home";
}

答案 2 :(得分:0)

您的表单可以像(JSP的一部分)

一样简单
<form id="myForm" method="post" action="http://localhost/your_app_root/check_credentials.jsp">
<input id="username-txt" name = "username" type="text" value="some_username">
<input id="password-txt" name = "password" type="text" value="some_password">
<input type="submit" value="Log in">
</form>

在JS中

 function authorizationCheck()
    {
   //do some processing if necessary (you can encrypt username/psw but   this   is only slightly more secure)       
    document.getElementById("myForm").submit();
    }

在您的控制器中(是Spring),您将检索用户名和密码为@RequestParam个参数。

在普通的JSP(JSP / servlet)中,您分别使用request.getParameter("username")request.getParameter("password")