简体   繁体   中英

How do JSP's and Servlets interact with each other

I am creating a Java Web Application on Eclipse and am unsure exactly how you can link jsp pages with Servlets. Example if your jsp page displays forms for the user to enter their First Name and age and then once they click submit, re-directing to the Servlet to handle the data.

Here is intro.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <title>Hello World</title>
        <style>.error { color: red; } .success { color: green; }</style>
    </head>
    <body>
        <form action="intro" method="post">
            <h1>Hello</h1>
            <p>
                <label for="name">What's your name?</label>
                <input id="name" name="name">
                <span class="error">${messages.name}</span>
            </p>
            <p>
                <label for="age">What's your age?</label>
                <input id="age" name="age">
                <span class="error">${messages.age}</span>
            </p>
            <p>
                <input type="submit">
                <span class="success">${messages.success}</span>
            </p>
        </form>
    </body>
</html>

Here is IntroductionServlet.java:

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/intro")
public class IntroductionServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Preprocess request: we actually don't need to do any business stuff, so just display JSP.
        request.getRequestDispatcher("/WEB-INF/intro.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Postprocess request: gather and validate submitted data and display result in same JSP.

        // Prepare messages.
        Map<String, String> messages = new HashMap<String, String>();
        request.setAttribute("messages", messages);

        // Get and validate name.
        String name = request.getParameter("name");
        if (name == null || name.trim().isEmpty()) {
            messages.put("name", "Please enter name");
        } else if (!name.matches("\\p{Alnum}+")) {
            messages.put("name", "Please enter alphanumeric characters only");
        }

        // Get and validate age.
        String age = request.getParameter("age");
        if (age == null || age.trim().isEmpty()) {
            messages.put("age", "Please enter age");
        } else if (!age.matches("\\d+")) {
            messages.put("age", "Please enter digits only");
        }

        // No validation errors? Do the business job!
        if (messages.isEmpty()) {
            messages.put("success", String.format("Hello, your name is %s and your age is %s!", name, age));
        }

        request.getRequestDispatcher("/WEB-INF/intro.jsp").forward(request, response);
    }

}

According to my understanding, form action = "intro" should re-direct the intro.jsp page to the IntroductionServlet once the submit button has been clicked. However, I receive a requested resource is not available error in Eclipse. It seems like it searches for an intro.jsp file instead. I am running Dynamic Web Module 3.0 so I thought that mapping the servlets is not required in web.xml since I have the "@WebServlet("/intro")" tag.

Basically, I want to know how to retrieve information from a text field once the submit button has been pressed and use it as a variable in my application.

you can also submit your form by manually define your servlet, i have used that in my application. following is the code :-

$("#SubmitButton").click(function()
            {       var HashedPass=Sha1.hash($("#userPassword").val());
                    $("#userPassword").val(HashedPass);
                    $('#loginForm').attr('method','post');
                    $('#loginForm').attr('action','SignupServlet');
                    $('#loginForm').submit();
            }); 

Did you try giving it like this(the conventional way):

action="<%=request.getContextPath() %>/IntroductionServlet"

For your second question: Once the control reaches the servlet from the jsp page, the textfield content can be accessed via request.getparameter(textfieldname) in the servlet.

Hope this is useful.

try :

request.getRequestDispatcher("WEB-INF/intro.jsp").forward(request, response);

to receive parameters you should use :

request.getParameter("<name of input text>");

send parameters :

request.setAttribute("myobject", myobjetc); 

and to access this variable from jsp using :

${myobject.atribute}

If the servlet not works add this to form (It is not necessary but you can try):

<form action="${pageContext.request.contextPath}/intro" method="POST"> 

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