How do you mix up java with html and javascript?

2019-09-14 00:18发布

问题:

I have this little java project in which I have to use jsp files.
I have an html with a login button that triggers the following function:

var loginCall = "user/login";
var logoutCall = "user/logout";
var signupCall = "user/signup";

function login() {
var login = baseUrl + loginCall + "?";

var loginFormElements = document.forms.loginForm.elements;

login = addParam(login, USER_NAME, loginFormElements.userName.value, false);
login = addParam(login, PASSWORD, loginFormElements.password.value, true);

simpleHttpRequest(login, function(responseText){

    var status = evalJSON(responseText);

    if (status.errorCode == 200) {
        var res = status.results;
        var sessionId = res[0].sessionId;
        setCookie(SESSION_ID,sessionId);
        window.location="http://localhost:8080/"+baseUrl+"/main.html";
    } else {
        showError(status.errorCode, "Username or password was incorrect.")
    }

}, function(status, statusText){console.log('z');    
    showError(status, statusText);
});
}

As far as I can see a httpRequest is made and sent with data to baseUrl + loginCall, meaning localhost/something/user/login?name=somename&pass=somepass

This is where I'm stuck, do I have to make a java file somewhere somehow, that takes the request information, works it up with the database and returns an answer?
If so, where, how? Do I have to name it login/user.java?

Can anyone point me to the right direction, if not give me some code example or explanation of what I have to do next?

回答1:

You need to have another look at the JSP MVC The jsp page should hold the html and javascript and java code. If you want to call a separate .java class, you need to write that class as a servlet then call it.

So in your .jsp you have you html and javascript just like you have it there, then any java you include in these brackets <% %>

Have a look at the tutorials here http://www.jsptut.com/

And i see your doing a login page. I used this brilliant tutorial for creating a log in system which helped me understand how jsp and servlets worked. http://met.guc.edu.eg/OnlineTutorials/JSP%20-%20Servlets/Full%20Login%20Example.aspx

Also check out this image which should help you understand the concept. Remember servlets are pure java classes, used for mostly java but can also output html, jsp's are used for mostly html (& javascript) but can include jsp. So the servlets do the work, then the jsp gets the computed values so that they can be utilized by JavaScript. that's how i think of it anyway, may be wrong http://met.guc.edu.eg/OnlineTutorials/static/article_media/jsp%20-%20servlets/LoginExample%20[4].jpg

All the best



回答2:

If you are not using any MVC framework then best approach would be to extending HttpServlet classes for handling requests and doing all heavy lifting tasks such as business logic processing,accessing/updating databases etc. and then dispatching the request to .jsp files for presentation.In .jsp.You can also add custom objects to request scope that you wish to access on '.jsp' pages + using expression language you can access most request related implicit objects

I taken a typical example of flow in brief.You may can an idea and explore in deep yourself.

Here is java servlet class that will handle a posted form.

public class doLogin extends HttpServlet{

    @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException {

    String username= request.getParameter("username"); // get username/pasword from form
    String password = request.getParameter("password");

       // This is your imaginary method for checking user authentication from database
    if(checkUserAuthentication(username,password)){
     /* 
      user is authenticated.Now fetch data for user to be shown on homepage
      User is another class that holds user info. Initialize it with data received from database
     */
      user userData = new User;
      user.setName(...);
      user.setAge(...);
      user.setInfo(...); 
      // etc
    }
    RequestDispatcher view = req.getRequestDispatcher("login.jsp");             

    req.setAttribute("userdata", userData); // set user object in current request scope

    view.forward(req, resp);//forward to login.jsp          

}

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException {       


}

but you need a form with some action to invoke above ServletClass

<form action="/checkLogin" method="POST">
  <input type="text" name="username" value="">
  <input type="password" name="password" value="">
  <input type="submit" name="login" value="Login">
</form>

To tell your Servlet container to invoke doLogin class on form login button click you have to configure it in deployment descriptor file web.xml which is part of standard dynamic web application in java

In web.xml' following xml snippet make apllication server aware ofdoLogin` class

<servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.yourdomain.doLogin</servlet-class>
</servlet>

But its not mapped to any url yet,It is configured as below in <servlet-mapping> section in web.xml

<servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/checkLogin</url-pattern>
</servlet-mapping>

Now any post request to url /checkLogin will invole doPost method on doLogin class After successful login request will be trasfered to 'login.jsp' page.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>

You can use java code in sciptlet <% %> syntax to access userData object <% User data = (User)request.getAttribute('userData'); %>

Better and tidy approach is to use expression language

${ pageContext.request.userData.name } 

Above expression calls getName() method on object of User class using java beans naming conventions

Here, you can learn more about expression language May be some time later I can improve this and provide you more insight.Hope that helps :)