Passing value from a jsp button click to a servlet - java

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. :)

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) {
}
});
}

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) {
}
});
}

Related

Ajax request is not calling Spring boot controller

I'm trying to call my Spring controller using Ajax and submitting a form.
Function always retrieves the error window. I tried changing the URL parameter to "/profile", "profile" or "PrivateAreaController/profile", but I keep getting the same error.
My main.js file and controller are placed in the following order:
-->Mainfolder
-->src
-->java
-->controller
-->PrivateAreaController.java
-->resources
-->static
-->js
-->main.js
My controller is called PrivateAreaController
Ajax Code
$('#sampleForm').submit(
function(event) {
var firstname = $('#firstname').val();
var lastname = $('#lastname').val();
var data = 'firstname='
+ encodeURIComponent(firstname)
+ '&lastname='
+ encodeURIComponent(lastname);
$.ajax({
type : "POST",
dataType: "json",
url : '#Url.Action("callingcontroller","PrivateAreaController")',
contentType: "application/json; charset=utf-8",
data : data,
success : function(response) {
alert( response );
},
error : function() {
alert("not working");
}
});
return false;
});
Spring code
#RequestMapping(value = "/profile", method = RequestMethod.POST)
public #ResponseBody
String processAJAXRequest(
#RequestParam("firstname") String firstname,
#RequestParam("lastname") String lastname ) {
String response = "";
System.out.println("working");
return response;
}
HTML form
<form id="sampleForm" method="post" action="/profile">
<input type="text" name="firstname" id="firstname"/>
<input type="text" name="lastname" id="lastname"/>
<button type="submit" name="submit">Submit</button>
</form>
EDIT:
I found the answer.. i needed to add
#CrossOrigin(origins = "http://localhost:8080")
before the #RequesMapping parameter and change the url parameter of the ajax call to url: 'http://localhost:8080/(your requestmapping parameter)
I found the answer.. i needed to add
#CrossOrigin(origins = "http://localhost:8080")
before the #RequesMapping parameter and change the url parameter of the ajax call to url: 'http://localhost:8080/(your requestmapping parameter)
This worked for me using springboot with thymeleaf, made small modification to one of the answers on this post How do you get the contextPath from JavaScript, the right way?
In the HTML
<html>
<head>
<link id="contextPathHolder" th:data-contextPath="#{/}"/>
<body>
<script src="main.js" type="text/javascript"></script>
</body>
</html>
THEN IN JS
var CONTEXT_PATH = $('#contextPathHolder').attr('data-contextPath');
$.get(CONTEXT_PATH + 'action_url', function() {});
What is error you are getting, Press F12 and go to Network tab and the press submit button now see the url, try adding url:"../your service URL..
Well. I never seen this part before.
#Url.Action("callingcontroller","PrivateAreaController")
I normally do like as below:
$.ajax({
type : "POST",
dataType: "json",
url : '/profile',
contentType: "application/json; charset=utf-8",
data : data,
success : function(response) {
alert( response );
},
error : function() {
alert("not working");
}
});
But it can have a problem with the contextPath.
So, What I do is adding 'request.getContextPath()/' as below:
$.ajax({
type : "POST",
dataType: "json",
url : '${request.getContextPath()}/profile',
contentType: "application/json; charset=utf-8",
data : data,
success : function(response) {
alert( response );
},
error : function() {
alert("not working");
}
});
The contextPath has the URL of your start page.
For instance, 'www.google.com' or 'www.naver.com'
But in general, Since I personally use the contextPath a lot, I make a value and keep it.
var context = ${request.getContextPath()};
Then, your code will look neat and easy to reuse.
And also you can figure it out with the error attribute.
error : function(err) {
console.log("not working. ERROR: "+JSON.stringify(err));
}
I hope this works out.

how to send data from servlet to Jsp using request dispatcher

servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
System.out.println("Received Value: " + request.getRequestURL());
response.getWriter().append("Decoded string: ").append(
Utils.getDataFromFeedbackLink(request.getPathInfo().substring(1, request.getPathInfo().length())));
String decodeValue = Utils
.getDataFromFeedbackLink(request.getPathInfo().substring(1, request.getPathInfo().length()));
request.setAttribute("finalData", decodeValue);
RequestDispatcher rd = request.getRequestDispatcher(decodeValue);
rd.forward(request, response);
}
jsp:
<body>
Hello World ::::
<%=request.getAttribute("finalData")%>
</body>
web.xml
<servlet>
<servlet-name>SubmitFeedbackServlet</servlet-name>
<description></description>
<servlet-class>com.techjini.tfs.servlets.SubmitFeedbackServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SubmitFeedbackServlet</servlet-name>
<url-pattern>/submitfeedback/*</url-pattern>
</servlet-mapping>
i am getting value but when i try to send value from Servlet to Jsp then each time same servlet loaded so am unable to get value inside jsp please suggest me how to get value from servlet to jsp using request dispatcher or some thing i did wrong please point me where am doing mistake .
If you store some data in request attribute in will be seen on forwarded page. Just set req.setAttribute("key", "value") and it will be visible on destination page via ${"key"}
in the line "RequestDispatcher rd = request.getRequestDispatcher(decodeValue);"
the decodeValue should contain the name of the jsp file . can you check that by printing the value of decodeValue on console.

I am trying to fetch data from a servlet into a jsp using angularjs. However, the ng-click seems to be not working. What am I doing wrong?

Please find my code below :
angulardemo.jsp
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>AJAX with Servlets using AngularJS</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
angular.module('myApp', [])
.controller('MyController', ['$scope', '$http', function($scope, $http) {
$scope.getDataFromServer = function() {
$http.get('AngularServlet',function(data) {
$scope.person=data;
},function(failure){
console.log("failed");
})
};
}]);
</script>
</head>
<body>
<div ng-app="myApp">
<div controller="MyController">
<button ng-click="getDataFromServer()">Fetch data from server</button>
<p>First Name : {{person.fname}}</p>
<p>Last Name : {{person.lname}}</p>
</div>
</div>
</body>
</html>
The Servlet code :
package com.controller;
public class AngularServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
public AngularServlet()
{
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//JSONObject obj = new JSONObject();
try {
PersonalData personData = new PersonalData();
personData.setFname("Fname");
personData.setLname("Lname");
String json = new Gson().toJson(personData);
response.setContentType("application/json");
response.getWriter().write(json);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
PersonalData is a simple class with the getter and setter methods for fname and lname. Now when I run the angularjsp.demo on the server and click on Get Data From Server Method , nothing happens. I am not sure if the ng-click is working properly in the first place. Am I doing something wrong ?
The web.xml is :
<web-app>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>AngularServlet</servlet-name>
<servlet-class>com.controller.AngularServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AngularServlet</servlet-name>
<url-pattern>/AngularServlet</url-pattern>
</servlet-mapping>
</web-app>
Edit 1: I am getting the proper json output on running the servlet manually.
Please try it. I have tried. Doesn't seem a problem like this.
public class PersonalData {
private String fName;
private String lName;
//setters getters...
}
Try it that way.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"> </script>
<script>
angular.module('myApp', [])
.controller('MyController', ['$scope', '$http', function($scope, $http) {
$scope.getDataFromServer = function() {
$http.get("/AngularServlet").success(function(data){
$scope.person = data;
});
};
}]);
</script>
Access to the data.
<p>First Name : {{person.fName}}</p>
<p>Last Name : {{person.lName}}</p>
And use ng-controller.
yeah #shaohao lin pointed out use response.data (or data.data in your case) instead of just data. What your $http service returns is an object of type Response (with response code, headers, data and stuff) and you need only data from it!
The way you make a GET request is not the Angular way. Try the following code.
$scope.getDataFromServer = function() {
$http.get('/AngularServlet').then(
function (response) {
$scope.person = response.data;
},
function (error) {
console.log(error);
}
);
};
Problem no. 1
You need to replace controller with ng-controller inside your div.
<div controller="MyController"> => <div ng-controller="MyController">
Problem no. 2
You are using $http call in wrong way. Try
$http.get('/AngularServlet')
.then(function (res) {
$scope.person = res.data;
}, function (err) {
console.log("failed");
};
Problem no. 3
Since your json has properties "Fname", "Lname", you need to use them inside your app, instead of "fname", "lname", as 'fname' is not same as 'Fname' in javascript.
<p>First Name : {{person.Fname}}</p>
<p>Last Name : {{person.Lname}}</p>

Cannot send ajax post request to Servlet

Here is my code.,
Javascript
$(document).ready(function()
{
$("button").click(function(){
$.post("AjaxpostloginServlet.java",
{
name:"kevin",
pass:"Duckburg"
});
});
});
Java servlet
package com.iappuniverse.ajaxpostlogin;
import java.io.IOException;
import javax.servlet.http.*;
#SuppressWarnings("serial")
public class AjaxpostloginServlet extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse resp)throws IOException
{
String name=req.getParameter("name");
System.out.println(name);
}
}
The name here in the servlet doesn't get printed in the console. Trying to send data to the server using ajax .post(), but cannot make the servlet linked to the ajax .post() call run.
Change your web.xml to something like the below
<?xml version="1.0" encoding="ISO-8859-1" ?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<display-name>Application</display-name>
<description>
Description Example.
</description>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>AjaxpostloginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
lets take it a step further and change your servlet post method
public void doPost(HttpServletRequest req, HttpServletResponse resp)throws IOException {
String name=req.getParameter("name");
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(name);
}
finally change the url of the ajax call and use a callback function.
$(document).ready(function() {
$("button").click(function() {
$.post("login",{
name:"kevin",
pass:"Duckburg"
}).done(function( data ) {
alert( "name: " + data );
})
});
});
Disclaimer:
I haven't test it!

Jquery ajax call to invoke spring controller?

I have below config in web.xml
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/mvc-dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
I have controller as below.
#Controller
public class SomeController {
#RequestMapping(value = "/getData", method = RequestMethod.GET)
public ModelAndView showExtendedUi(#RequestParam("geo") String geo, #RequestParam("tab") String tab, #RequestParam("gid") String gid, HttpServletResponse response) {
//logic
}
}
Now how can i specify URL in jquery ajax call?
$.ajax({
type: "GET",
url: "getData.do",
dataType: "json",
success: function(responseJson) {
alert("json"+responseJson);
},
error: function(xhr, status, error) {
alert('Failed to get details: ' + error);
}
});
From looking at the code above, you should just be able to go to the following url (assuming 8080 port as default Tomcat port).
http://localhost:8080/getData.do?geo=1&tab=1&gid=1
This should show you in a browser the JSON you require. If the JSON appears on the page here, just do $.getJSON() from jQuery as it has built in methods for pulling back JSON. You can see the documentation on this method here.

Categories

Resources