I have made an AJAX call to a JSP, which in turn calls a Java method in a separate Java class. All files are in the same folder.
For some reason, I can't get the correct value returned to AJAX. It simply prints the whole JSP content.
JavaScript:
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if(true){
alert('hello!');
var response = xhr.responseText;
alert(response);
document.getElementById('newgame').innerHTML = xhr.responseText;
}
};
xhr.open('GET', 'javaconnect.jsp', true);
xhr.send(null);
JSP:
<%# page import="com.example.Server"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
Server tc = new Server();
out.print(tc.highScore());
%>
</body>
</html>
Java class:
package com.example;
public class Server {
public String highScore() {
return "hello!!!";
}
}
The best solution is to use a Servlet to make the control layer in place of jsp that instantiates the Server class, like:
public class HelloWorld extends HttpServlet {
protected void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
Server tc = new Server();
String txt = tc.highScore();
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(txt);
}
}
Do not forget to map the servlet and change the url of the ajax call.
You can test call
Related
I just started learning JSP and Java servlets and I stumbled upon an issue. I will use a simple example to show this unexpected behavior.
I have a .jsp file which has a button and makes an ajax request when clicking the button:
<%# page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>JSP - Hello World</title>
</head>
<body>
<button class="btn">Test button</button>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(".btn").click(function () {
$.ajax({
url: "hello-servlet",
method: "GET",
data: {action: "action", arg: "someData"}
})
}
);
</script>
</html>
And this is the servlet that the above .jsp file references:
package com.example.demo;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet {
public HelloServlet() {
super();
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String action = req.getParameter("action");
String data = req.getParameter("arg");
System.out.println(action + ", " + data);
}
}
And there is no issue. It works. If I run it, or use the debugger to test it, I get the expected behavior. It prints action, someData so the parameters of the request were successfully retrieved in the servlet.
Now, I will change just this: the method argument in the ajax call from GET into PUT and the method I override in the servlet from doGet into doPut:
<%# page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>JSP - Hello World</title>
</head>
<body>
<button class="btn">Test button</button>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(".btn").click(function () {
$.ajax({
url: "hello-servlet",
method: "PUT",
data: {action: "action", arg: "someData"}
})
}
);
</script>
</html>
And the servlet:
package com.example.demo;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet {
public HelloServlet() {
super();
}
#Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String action = req.getParameter("action");
String data = req.getParameter("arg");
System.out.println(action + ", " + data);
}
}
I expected it to work in the same way. This does not happen. The output is null, null. The request parameters cannot be retrieved if I use PUT in the ajax call. I added the previous function doGet to the servlet to see if maybe the request doesn't make it to the PUT handler and defaults to GET. I used the debugger and I noticed that the execution does indeed enter the doPut handler, which is good, since that's what we expect to happen. It's just that at each req.getParamter() call I get null returned. I cannot retrieve the parameters if I use PUT, but I can retrieve them if I use GET (or POST for that matter, I tried it). This is weird to me and unexpected. What is going on and what can I do to solve it?
In theory when the AMPByExample server receives the POST request
from the login page, if the credentials are correct, it will redirects
the request to the URL of returnURL and the parameter is added
success = true. Once done, the AMP execution time can finally
authorize the page.
The login page is the following:
login.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Page</title>
</head>
<body>
<form method="post" action="loginauthorization">
Correo Electronico: <input type="text" name="correo"><br>
ContraseƱa: <input type="password" name="clave"><br>
<input name="returnurl" type="hidden" value="https://cdn.ampproject.org/v0/amp-login-done-0.1.html?url=https%3A%2F%2Fampbyexample.com%2Fplayground%2F">
<input type="submit" value="Ingresar">
</form>
</body>
</html>
As you can see, in the returnurl it is the same login URL ofAmpByExample and it does not work.
I already tried to make my own url in the following way:
<input name="returnurl" type="hidden" value="https://cdn.ampproject.org/v0/amp-login-done-0.1.html?url=http%3A%2F%2Flocalhost%3A8084%2Fmypage%2Fpanel.jsp">
And it doesn't work either.
In the servlet loginauthorization.java I receive thatreturnurl and I add the # success = true (supposedly I must verify username and password, but I want to make it work first).
loginauthorization.java:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class loginauthorization extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try{
response.setContentType("text/html");
//I get the parameters
String email = request.getParameter("correo");
String password = request.getParameter("clave");
String url = request.getParameter("pageurl");
int ridini = url.indexOf("rid=")+4;
int ridend = url.indexOf("&url=");
String rid = url.substring(ridini, ridend);
String returnurl = request.getParameter("returnurl");
//assuming that the username and password are correct, add to the returnurl success true
returnurl= returnurl + "#success=true";
//create a session
HttpSession session=request.getSession();
session.setAttribute("umail",email);
session.setAttribute("upass",password);
session.setAttribute("rid",rid);
session.setAttribute("returnurl",returnurl);
//redirect after login with the success = true
response.sendRedirect(returnurl);
}catch(Exception exp){
System.out.println(exp);
}
}
}
The configuration of the panel is as follows:
panel.jsp
<script id="amp-access" type="application/json">
{
"authorization": "http://localhost:8084/mypage/jsonauthorization",
"noPingback": "true",
"login": {
"sign-in": "/mypage/login.jsp?rid=READER_ID&url=CANONICAL_URL&return=RETURN_URL",
"sign-out": "/mypage/endsession"
},
"authorizationFallbackResponse": {
"loggedIn": false
},
"type": "server"
}
</script>
The jsonauthorization prints{"loggedIn": true}or{"loggedIn": false}:
jsonauthorization.java
import java.io.*;
import javax.servlet.http.*;
public class jsonauthorization extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("application/json");
response.setHeader("AMP-Access-Control-Allow-Source-Origin", "http://localhost:8084/mypage");
PrintWriter pwriter = response.getWriter();
HttpSession session=request.getSession(false);
if(session != null){
String email=(String)session.getAttribute("umail");
if(email==null){
session.invalidate();
pwriter.print("{\"loggedIn\":false}");
}else{
String rid;
rid = (String) session.getAttribute("rid");
Cookie AmpCookie = new Cookie("authorized",rid);
AmpCookie.setPath("/");
AmpCookie.setDomain("/mypage");
response.addCookie(AmpCookie);
pwriter.print("{\"loggedIn\":true}");
}
}else{
pwriter.print("{\"loggedIn\":false}");
}
pwriter.close();
}catch(Exception exp){
System.out.println(exp);
}
}
}
I appreciate the answers, if the error is not in the returnurl please tell me where :P
I am also trying to figure out AMP integration with login/registration. Not sure if this will help, but I found that the return url is automatically added to the url param, so you don't necessarily have to add it to your sign-in url within your initialization json object.
I figured out, it is not necessary to configure the return url. Simply add the hidden input inside the html in order to close the login window and read the json url approving the login.
Just like this:
<input name = "returnurl" type = "hidden" value = "https://cdn.ampproject.org/v0/amp-login-done-0.1.html">
Then, if the json url aproves the login it will works.
Actually the code is fine, the problem was in the json generator file.
CORS problems. Is necessary to set the header "AMP-Access-Control-Allow-Source-Origin" right.
I am trying to pass an attribute from a java servlet to jsp and write this attribute on jsp file. However it does not redirect to jsp file url but it writes the content of the jsp file. Here is my related codes:
Control.java:
#WebServlet("/Control")
public class Control extends HttpServlet{
#Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Key key = MacProvider.generateKey();
long time = System.currentTimeMillis();
try{
String jwt = Jwts.builder()
.signWith(SignatureAlgorithm.HS256, key)
.setSubject("username")
.setIssuedAt(new Date(time))
.setExpiration(new Date(time+6000000))
.claim("password","password")
.compact();
req.setAttribute("jwt", jwt);
req.getRequestDispatcher("/Home.jsp").forward(req,resp);
}catch (Exception e){
e.printStackTrace();
}
}
}
Home.jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Welcome</title>
</head>
<body>
${jwt}
</body>
</html>
Here, browser stays on http://localhost:8080/Control but it writes the content of Home.jsp file which is just a java web token result string.
2) My second question is when I tryed to store this jwt result string in browser local storage and then write it in jsp file in order to check if it stored in browser or not. But it does not prints anything. To do this, I just changed the Home.jsp file as follow:
(I took both of the code snippets from here)
Home.jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<script>
localStorage.setItem("jwt", ${jwt});
console.log(localStorage.getItem("jwt"));
var jjwt = localStorage.getItem("jwt");
document.write(jjwt);
</script>
</body>
</html>
Another try:
<html>
<head>
<script>
function myFunction() {
localStorage.setItem("jwt", ${jwt});
console.log(localStorage.getItem("jwt"));
var jjwt = localStorage.getItem("jwt");
document.getElementById("myText").innerHTML = jjwt;
}
</script>
</head>
<body onload="myFunction()">
<span id="myText"></span>
</body>
</html>
Where am I doing wrong?
1) When you use RequestDispatcher.forward(request,response), your servlet will still have control but your jsp page will be loaded so this is nothing to worry about.
If you want your browser URL to show your JSP page URL, do response.sendRedirect("URL TO LOAD");
2)Since you are using JSP, try accessing the request variables like below and print it
<% String jwt = (String) request.getAttribute("jwt");%>
We need to set it as
localStorage.setItem('jwt', <%=jwt%>);
I'm calling my Java Servlet with an AJAX call, but I'm not able to read the input parameter from the request. I've tried two ways but with no luck:
var id;
$("#scan").click(function() {
id = 1;
$.ajax({
type: "POST",
data: id,
url: "http://10.1.42.249:8080/test-notifier-web/RestLayer"
});
});
And:
id = 1;
$.post('http://10.1.42.249:8080/test-notifier-web/RestLayer', {
reqValue: id
}, function(responseText) {
// $('#welcometext').text(responseText);
alert("OK!!!");
});
My servlet code is a simple log print of the request parameter, but the return value is always null:
String reqID = "";
log.info("Servlet called");
reqID = request.getParameter("reqValue");
log.info("reqID = " + reqID);
How can I get this working?
The only way I've found to get the code working is manually add the parameter to servlet url, like http://10.1.42.249:8080/test-notifier-web/RestLayer?reqValue=1
i have check you code.this is my working code.
<%# 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>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
var id;
function fun() {
alert("aaaa");
id = 1;
$.ajax({
type : "POST",
data : {
reqValue : id
},
url : "/WebProject/callAjax"
});
}
</script>
</head>
<body>
<button id="scan" onclick="fun()">Sacn</button>
</body>
</html>
//Servlet
#WebServlet(urlPatterns = {"/callAjax",})
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(request.getParameter("reqValue"));
}
}
var id;
$("#scan").click(function() {
id = 1;
$.ajax({
type: "POST",
data: { reqValue : id},
url: "http://10.1.42.249:8080/test-notifier-web/RestLayer"
});
});
There are different methods you need to override in servlet. Those are doPost(), doGet(), service() and etc.
I suspect you are using doGet() method that's why when you add parameter to the URL your java code is working and in other two cases as you are using type : "POST" java code is unable to read the data from Request Body( in post method the data will be added to Request Body).
I suggest you to use doPost() or service() methods instead doGet().
Im trying pass specific element from my Model to servlet to jsp.
This is working in my servlet: System.out.println(beanModel.getSortedDomainList().get(0).split(";")[1]) When I go to http://localhost:8080/Comparebet/Controller
But I dont know what Im doing wrong since I dont get it to my jsp. All tutorials ive been watching is mostly input parameters or they put code in the JSP.
UPDATE EDIT
Tried with this in my JSP and I get "null"
<%= request.getAttribute("rank1") %>
SERVLET
#WebServlet("/Controller")
public class Controller extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// ArrayList<String> sortedDomainList = new BeanModel().getSortedDomainList();
BeanModel beanModel = new BeanModel();
request.setAttribute("rank1", beanModel.getSortedDomainList().get(0).split(";")[1]);
RequestDispatcher view = request.getRequestDispatcher("view.jsp");
view.forward(request, response);
//TESTING SERVLET
System.out.println(beanModel.getSortedDomainList().get(0).split(";")[1]);
System.out.println("CONTROLLER CALLED");
// System.out.println(${rank1});
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
}
}
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>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>CompareBet</title>
</head>
<body>
<form action="/Controller/*" method="get">
<h1>${rank1.getSortedDomainList().get(0).split(";")[1] } </h1>
</form>
</body>
</html>
In your JSP try this, instead of rank1.getSortedDomainList().get(0).split(";")[1]
<h1>${request.rank1 } </h1>
You have already done beanModel.getSortedDomainList().get(0).split(";")[1] in your servlet and have added the result to the request scope object.
Try to replace this line in your jsp:
<h1>${rank1.getSortedDomainList().get(0).split(";")[1] } </h1>
To this:
<h1>${rank1} </h1>
In JSP you can access this data using the expression language like ${rank1}.
And take it out from the <form like this:
<form action="/Controller/*" method="get">
...
</form>
Try to use <h1><%= request.getParameter("rank1")%></h1>