I want to call Servlet doPost() method by using the javascript code but iam getting http 405(HTTP method GET is not supported by this URL) exception.
Here is my javascript code:
url="RedirectServlet?&FD="+FD+"&TD="+TD+"&actionid="+status+"&usercode="+usercode+"&action=reports"+"";
RedirectServlet.java:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
if(action.equals("reports")){
System.out.println("inside reports");
//Getting values from Reports_arb.jsp
String Fromdate=request.getParameter("FD");
String Todate=request.getParameter("TD");
String status=request.getParameter("actionid");
String usercode=request.getParameter("usercode");
//placing given values in a session
request.setAttribute("FD", Fromdate);
request.setAttribute("TD", Todate);
request.setAttribute("actionid", status);
request.setAttribute("usercode", usercode);
//Redirecting to showReport_arb.jsp
//response.sendRedirect("showReport_arb.jsp");
request.getRequestDispatcher("showReport_arb.jsp").include(request, response);
}
}
By seeing you URL, you are sending the data along with the URL. which as servlet get request.
So URL is trying access doGet, but where there is no implemention of doGet in servlet causing problem.
EDIT
use this to make access of your servlet doPost
<form ... method="post">...</form>
Related
The problem
I'm creating a web app where the user is served a login page, login.html, and has to enter his credentials. The servlet class grabs the information using ajax in the form of a POST request, generated by the user clicking the submit button. After checking the correctness of the credentials, i wish to serve the user with a new HTML page, a welcome page, where the response of the servlet is transferred. The problem i'm facing is how to transfer the response from a starting LoginServlet class to a WelcomeServlet all the meanwhile, the client is projecting a new HTML page, welcome.html, and catch the response of the WelcomeServlet in an ajax call made by a js script in the new HTML page.
Background
I'm just starting to delve into the development of web-apps, so if i'm mistaken in any part of my logic and understanding of the whole frontend-to-backend process, please say so. I'm aware of the redirect() and forward() functions but i'm not understanding the way these functions can be used in conjunction, or the complete difference, with the client side of things.
I have the following servlets:
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher dispatcher = request.getRequestDispatcher("welcomeservlet");
dispatcher.forward(request, response);
}
public class WelcomeServlet extends HttpServlet {
private static final long serialVersionUID = 2L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//parse request and send response
}
In the login.html file i've included the following js code:
function loadNewPage() {
// retrieve data and store them in a js Object
$.ajax({
url: "loginservlet",
type: 'POST',
dataType: 'json',
data: JSON.stringify(jsObject),
contentType: 'application/json',
mimeType: 'application/json',
success: function (data) {
window.location.href = "welcome.html";
},
error: function (data, status, er) {
alert("error: " + data.text + " status: " + status + " er:" + er);
}
});
}
I'm not including another js script which would be placed inside the welcome.html purposely since i don't know what would i have to add in there to catch the response of the new servlet. A possible reason why this whole thing isn't working could be that i'm missing something in the functionality of the forward() function but couldn't find an example online that does the exact thing that i want to do.
(Image credit w3schools)
The fact is you can't jump to another servlet. Ajax response will be sent back to the same webpage from which request was generated.
For your requirement what you can do is, Check whether login is success or not in LoginServlet. If yes create a token, save it in database along with the username and send the same token as response to the client.
Now in client save the token in localStorage and redirect to welcome.html.
On welcome.html page loading check whether token saved in localStorage exists or not. If yes, check whether it's valid or not. If valid the call WelcomeServlet . Else display login screen.
It's called token based authentication. You can read more about it here
How do I generate an HTML response in a Java servlet?
You normally forward the request to a JSP for display. JSP is a view technology which provides a template to write plain vanilla HTML/CSS/JS in and provides ability to interact with backend Java code/variables with help of taglibs and EL. You can control the page flow with taglibs like JSTL. You can set any backend data as an attribute in any of the request, session or application scope and use EL (the ${} things) in JSP to access/display them. You can put JSP files in /WEB-INF folder to prevent users from directly accessing them without invoking the preprocessing servlet.
Kickoff example:
#WebServlet("/hello")
public class HelloWorldServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String message = "Hello World";
request.setAttribute("message", message); // This will be available as ${message}
request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);
}
}
And /WEB-INF/hello.jsp look like:
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 2370960</title>
</head>
<body>
<p>Message: ${message}</p>
</body>
</html>
When opening http://localhost:8080/contextpath/hello this will show
Message: Hello World
in the browser.
This keeps the Java code free from HTML clutter and greatly improves maintainability. To learn and practice more with servlets, continue with below links.
Our Servlets wiki page
How do servlets work? Instantiation, sessions, shared variables and multithreading
doGet and doPost in Servlets
Calling a servlet from JSP file on page load
How to transfer data from JSP to servlet when submitting HTML form
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
How to use Servlets and Ajax?
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
Also browse the "Frequent" tab of all questions tagged [servlets] to find frequently asked questions.
You need to have a doGet method as:
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Hola</title>");
out.println("</head>");
out.println("<body bgcolor=\"white\">");
out.println("</body>");
out.println("</html>");
}
You can see this link for a simple hello world servlet
Apart of directly writing HTML on the PrintWriter obtained from the response (which is the standard way of outputting HTML from a Servlet), you can also include an HTML fragment contained in an external file by using a RequestDispatcher:
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("HTML from an external file:");
request.getRequestDispatcher("/pathToFile/fragment.html")
.include(request, response);
out.close();
}
I am fairly new to spring and want to the correct way of making post request. I have a list of json object that I want to post to my server
for example
var list = [{name:"abc",age:23},{name:"xyz",age:22},{name:"xcx",age:33}]
I am making a post request in google closure using xhr to my server in this fashion
model.xhrPost(id,url,"list="+JSON.stringify(this.list),callback);
This is what my controller looks like
#RequestMapping(value={"/getInput"}, method = RequestMethod.POST)
#ResponseBody
public String logClientError(ModelMap model, HttpServletRequest request, HttpServletResponse response) throws Exception{
JSONObject result = new JSONObject();
try{
String errorObj = request.getParameter("list");
JSONArray errors = new JSONArray(errorObj);
some more code here which loops through the list...
result.put("isSuccess", true);
return result.toString();
}catch(JSONException e){
result.put("isSuccess", false);
return result.toString();
}
}
So in short I am making a post request by passing querystring parameter. Is this the correct way or should the content be posted in the body? If I post in the body what changes do I have to make ?
This is definitely not how you should post the data to REST endpoint. Going this way you can use GET instead of POST and it will work as well. However POST should be definitely used to create new resource and the content should be carried in message body not as a query param.
On the backend side you can catch and parse the content yourself or create a class (see below) that will be filled with data from body.
DTO:
class Person {
String name
Integer age
}
class PersonList {
List<Person> persons
}
Endpoint:
public String logClientError(#RequestBody PersonList list, HttpServletRequest request, HttpServletResponse response) throws Exception
Body:
{
"persons": [{name:"abc",age:23},{name:"xyz",age:22},{name:"xcx",age:33}]
}
#ResponseBody can be used in the same manner for responses.
How can I return to the registration page from the oauth authentication?
I put the url of the app(as &redirect_uri=) but when the user accept the authentication, the script fails:
Error: Access to 'app://6cb90889-d3dd-4ca7-8bab-ea11831b922d/reg.html#access_token=xxxxxxxxxxx' from script denied
It should close the browser and return to the app! Any idea?
redirection of url are taken care by server. Server has to understand the redirect_uri= attribute and need to redirect it.
In case of J2EE.
it will be done as
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
String contextPath= "http://www.java2s.com";
response.sendRedirect(response.encodeRedirectURL(contextPath + "/maps"));
}
Let me know if your trying someting different.
Regards,
Chandra.
I have a JavaScript from which I am making an Ajax Call to a JSP. Both JavaScript and JSP are deployed in the same web server. From JSP I am forwarding the request to one of the service (servlet) available in other web server using HttpURLConnection. I got the response in JSP, but now I need to pass the response back to JavaScript which made an Ajax Call. How I can do it?
My ultimate goal is to make an Ajax request from JavaScript to a JSP and from that JSP to one of the services and return the response back to JavaScript.
JSP is the wrong tool for the job. The output would be corrupted with template text. Replace it by a Servlet. You just need to stream URLConnection#getInputStream() to HttpServletResponse#getOutputStream() the usual Java IO way.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
URLConnection connection = new URL("http://other.service.com").openConnection();
// Set necessary connection headers, parameters, etc here.
InputStream input = connection.getInputStream();
OutputStream output = response.getOutputStream();
// Set necessary response headers (content type, character encoding, etc) here.
byte[] buffer = new byte[10240];
for (int length = 0; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
}
That's all. Map this servlet in web.xml on a certain url-pattern and have your ajax stuff call that servlet URL instead.