简体   繁体   中英

Passing value from a jsp button click to a servlet

ininI am bit new to jsp and servlet. I need to pass a value to a servlet on a button click. below I have mentioned my code. web.xml

<servlet>
<servlet-name>Login</servlet-name>
    <servlet-class>org.wso2.carbon.identity.application.authentication.endpoint.oauth2.OAuth2Login</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Login</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>

test.jsp

       function ok() {
        $.ajax({
            url: "/login",
            data: 'test=' +'test',
            type: "GET",
            async: false,
            success: function (data) {

            }
        });
    }

below is my html code in test.jsp

<button id="ok" class="btn btn-primary btn-large" onclick="ok()">OK</button>

The servelet

public class OAuth2Login extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
        IOException {
       System.out.print("========do get fires===========");
    }

}

But when my test.jsp is loading it invokes the doget() of the servlet. But at the button click it does not. I dont need to invoke the servlet at the page load. But I need it on the button click. Help me to solve this out. Sorry for the ignorance. :)

Write your servlet mapping url in url attribute:

function myFun() {
         var requestPath = "<%=request.getContextPath()%>";

        $.ajax({
            url: requestPath+"/login";
            data: {"data1":"value1", "data2": "value2"}
            type: "GET",
            async: false,
            success: function (data) {

            }
        });
}

I think in web.xml /test.jsp this is wrong in place of /test.jsp you can give yours servlet name like

<servlet-mapping>
    <servlet-name>Login</servlet-name>
    <url-pattern>/login</url-pattern>
</servlet-mapping>

and later on button click which is in test.jsp you can call ajax function and call get method of servlet

function ok() {
        $.ajax({
            url: "/login",
            data: 'test=' +'test',
            type: "GET",
            async: false,
            success: function (data) {

            }
        });
    }

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