Acess java servlet from an ajax request - java

I have never used ajax and have no idea if I am doing anything right. I wrote some code to test if I could access a java servlet using ajax and it didn't work.
In the script:
var xmlhttp=new xmlHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.write=xmlhttp.responseText;
}
};
xmlhttp.open("GET", "http://localhost:8080/timer/timer, true);
xmlhttp.send();
}
and in my servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//code
PrintWriter out=response.getWriter();
out.println("hi");
All I am trying to do here is write "hi". What am I doing wrong?
Thanks for any help!

After writing to an java.io.Writer you have to execute flush() the internal Buffer to execute the operation on IO level. After all writing a stream should always get closed, to free the resources:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//code
PrintWriter out=response.getWriter();
out.println("hi");
out.flush();
out.close();
}
http://docs.oracle.com/javase/6/docs/api/java/io/Writer.html#flush%28%29

Related

How transfer control between two Servlets with doPost methods?

I have a two servlets.
In my first servlet I use sendRedirect construction, but it call doGet from second servlet:
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if (someCondition()) {
resp.sendRedirect(req.getContextPath() + "/urlPattern");
} else { ... }
}
And my second servlet:
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// something to do...
}
But this is not security, user may get second servlet through compose URL. This is not permissible for my case, I need replace call sendRedirect to directly use doPost in second servlet.
Please help me replace resp.sendRedirect(...) to something calling doPost. Thank You.

A href link is empty but the servlet is redirecting itself to home page.how it is done ?

//inboxservlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name=request.getParameter("uname");
PrintWriter out=response.getWriter();
out.println("welcome "+name);
out.println("<a href='SentItems?uname="+name+" '>sent items</a>");
out.println("<a href=''>Logout</a>");
}
If i click logout it redirects to login page.Help me with this
Try like this
Proper way to logout is below way:
out.println("Logout")
You have to create a servlet to call logout properly:
public class LogoutServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
request.getRequestDispatcher("loginPage.jsp").include(request, response);
HttpSession session=request.getSession();
session.invalidate();
out.print("You are successfully logged out!");
out.close();
}
}
out.println("<a href=''>Logout</a>");
I believe your javascript code must be binding the event during page load time. See related javascript code.

Mockito when...thenResult always returns null

With the above code I always get an error in line of test
when(request.getServletContext().getAttribute("SessionFactory"))
.thenReturn(factory);
Any ideas?
Java class
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
SessionFactory sessionFactory = (SessionFactory) request.getServletContext().getAttribute("SessionFactory");
...............
}
Test class
#Test
public void testServlet() throws Exception {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
factory = contextInitialized();
when(request.getServletContext().getAttribute("SessionFactory")).thenReturn(factory); //Always error here
when(request.getParameter("empId")).thenReturn("35");
PrintWriter writer = new PrintWriter("somefile.txt");
when(response.getWriter()).thenReturn(writer);
new DeleteEmployee().doGet(request, response);
verify(request, atLeast(1)).getParameter("username"); // only if you want to verify username was called...
writer.flush(); // it may not have been flushed yet...
assertTrue(FileUtils.readFileToString(new File("somefile.txt"), "UTF-8")
.contains("My Expected String"));
}
when(request.getServletContext().getAttribute("SessionFactory")).thenReturn(factory);
This bit:
request.getServletContext().getAttribute("SessionFactory")
is a chained call; you're trying to stub both the request, and the servlet context that the request returns.
You can do that, but you need to use deep stubs:
HttpServletRequest request = mock(HttpServletRequest.class, RETURNS_DEEP_STUBS);

Eclipse Internal Browser doesn't apply HTML tags

I've created a simple servlet in Java and showing its HTML output in Eclipse internal browser.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter writer = response.getWriter();
writer.println("<h3> Hello World </h3>");
}
But the output is like this :
Why doesn't apply <h3> tag ?
Need to set response content type:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException
{
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("<h3> Hello World </h3>");
}

Java Servlet return error 405 (Method Not Allowed) for POST request

My servet work fine for get requests but when I call POST (using jquery ajax $.post) I get error 405 (Method Not Allowed)
Here is my code:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class init extends HttpServlet {
public init() { }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.println("GET");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, IllegalStateException {
response.setContentType("application/json");
ServletInputStream in = request.getInputStream();
PrintWriter out = response.getWriter();
out.print("POST");
}
}
This happened to me when my method call
"super.doGet(req, resp)" or "super.doPost(req, resp)" .
After i removed above super class calling from the doGet and doPost it worked fine.
Infact those super class calling codes were inserted by the Eclipse IDE template.
Are you sure that you actually override the doPost Method?
The signature looks like this:
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, java.io.IOException
but you specify it like this:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, IllegalStateException
I am not sure whether this is allowed:
Overriding Java interfaces with new checked exceptions
Try the following steps:
Add the #Override Annotation
Remove the throws IllegalStateException (shouldn't be a problem as it is a runtime exception)

Categories