calling servlet on submiting formpanel in gwt - gwt

I am trying to call a servlet when submitting the FormPanel in GWT.I am setting the url on form.setAction("myurl") and also done mapping on the web.xml but while on the form suvmit the servlet is not called.Here is the code:
public class MainEntryPoint implements EntryPoint {
public void onModuleLoad() {
AbsolutePanel panel=new AbsolutePanel();
FileUpload upload = new FileUpload();
upload.setName("file");
final FormPanel form = new FormPanel();
form.setWidget(panel);
form.setMethod(FormPanel.METHOD_POST);
form.setEncoding(FormPanel.ENCODING_MULTIPART);
form.setAction("/NewServlet");
RootPanel.get().add(new Label("path="+GWT.getModuleBaseURL()+"/NewServlet"));
Button sub=new Button("Submit");
sub.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
RootPanel.get().add(new Label("In click event submiting form"));
try{
form.submit();
}catch(Exception e){RootPanel.get().add(new Label(e+""));}
}});
form.addFormHandler(new FormHandler() {
public void onSubmit(FormSubmitEvent event) {
// This event is fired just before the form is submitted. We can take
// this opportunity to perform validation.
RootPanel.get().add(new Label("On submit"));
}
public void onSubmitComplete(FormSubmitCompleteEvent event) {
// When the form submission is successfully completed, this event is
// fired. Assuming the service returned a response of type text/html,
// we can get the result text here (see the FormPanel documentation for
// further explanation).
RootPanel.get().add(new Label("On submiting complete"));
}
});
panel.add(upload);
panel.add(sub);
RootPanel.get().add(form);
}
}
Here is the web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>upload</servlet-name>
<servlet-class>org.fileup.client.UploadServlet2</servlet-class>
</servlet>
<servlet>
<servlet-name>NewServlet</servlet-name>
<servlet-class>NewServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>upload</servlet-name>
<url-pattern>/uploadservlet2</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>NewServlet</servlet-name>
<url-pattern>/NewServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>welcomeGWT.html</welcome-file>
</welcome-file-list>
</web-app>
And NewServlet.java
public class NewServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
// /* TODO output your page here
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet NewServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet NewServlet at " + request.getContextPath () + "</h1>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Please tell me how can I call the NewServlet on submitting the FormPanel.

You probably want form.setAction(GWT.getHostPageBaseURL() + "NewServlet")

Or as an alternative you could use: form.setAction("NewServlet");

Very similar code, with your exact setAction statement, works for me. Possibly the problem was just that
<servlet-class>NewServlet</servlet-class>
left out the dotted path, e.g. org.fileup.server., to NewServlet.

Related

Servlet 404 error on get request upon submitting the form

Getting a 404 error on click on submit button on the form. Getting error (The requested resource is not available.) for the URL mapping http://localhost:8080/HelloWorld/HelloServlet. I tried the reference this as well, Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available" but this also doesn't seem to work.
1, index,html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="HelloServlet">
<input type="submit" value="HIT">
</form>
</body>
</html>
2. HelloServlet
package com.example.aman;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class HelloServlet
*/
#WebServlet("/HelloServlet")
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public HelloServlet() {
// TODO Auto-generated constructor stub
}
/**
* #see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
System.out.println("DIVESH");
}
/**
* #see HttpServlet#doGet(HttpServletRequest request,
HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at:
").append(request.getContextPath());
response.getWriter().println("DIVESH");
}
/**
* #see HttpServlet#doPost(HttpServletRequest request,
HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
3. web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>HelloWorld</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
http://localhost:8080/HelloWorld/HelloServlet.
Straight away that tells me what the problem is. You are trying to access a servlet from within the same folder directory. This is what happens if you are not careful with your relative URLS
In your form, change the URL mapping to this:
<form action="/HelloServlet">
<input type="submit" value="HIT">
</form>
Or if that didn't work, do this:
<form action="../HelloServlet">
<input type="submit" value="HIT">
</form>
Adding a / to the path makes it absolute.
Adding ../ makes it go to the parent of the current directory.
Hope that helps.

Web Application: the requested resource is not available after Maven clean

I have a dynamic web project that has worked perfectly fine many times, but after going to Run As > Maven clean, I tried running my application again and when trying to go to the url http://localhost:8080/Servlet_Project/AccountServlet I get an error saying the requested resource is not available. No exception is thrown - I can't seem to be able to access the servlet. Here is my AccountServlet.java. I also mapped the servlet in the web.xml but thought it was unnecessary because of the annotations.
#WebServlet("/AccountServlet")
public class AccountServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public AccountServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/account.jsp").forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
String password = request.getParameter("password");
HibernateClient hc = HibernateClient.getInstance();
Accounts a = hc.getAccount(username, password);
if(a==null){request.getRequestDispatcher("/login.jsp").forward(request, response);
}
else{
HttpSession sess = request.getSession();
sess.setMaxInactiveInterval(600);
sess.setAttribute("username", username);
sess.setAttribute("firstName", a.getFirstname());
sess.setAttribute("lastName", a.getLastname());
sess.setAttribute("address", a.getAddress());
sess.setAttribute("state", a.getState());
sess.setAttribute("country", a.getCountry());
sess.setAttribute("phone", a.getPhone());
sess.setAttribute("SSN", a.getSsn());
sess.setAttribute("email", a.getEmail());
sess.setAttribute("city", a.getCity());
String balances = (a.getBalance()).toString();
double balance = Math.round(Double.parseDouble(balances)* 100d)
sess.setAttribute("balance", balance);
request.getRequestDispatcher("/account.jsp").forward(request, response);}}
}

Tomcat Class Not Found - Servlet

I am having a strange problem in deploying a basic web app through Eclipse and Tomcat
The error -
SEVERE: Allocate exception for servlet DeCommServlet
java.lang.ClassNotFoundException: com.authentication.DeCommServlet
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
However, the application still gets to the DeCommServlet doPost() method and tomcat stays deployed but with that error.
Servlet:
<servlet>
<servlet-name>DeCommServlet</servlet-name>
<servlet-class>com.authentication.DeCommServlet</servlet-class>
</servlet>
<!-- Servlet Mappings -->
<servlet-mapping>
<servlet-name>DeCommServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
The servlet class is the correct link but still getting this error. I have nothing in any of the lib folders, but in the application properties I have the Apache Tomcat Lib added in Build Path >> Libraries
Has anyone seen this before?
Code for DeCommServlet:
#WebServlet("/DeCommServlet")
public class DeCommServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public DeCommServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("sdf");
System.out.println("ddd");
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.getUserPrincipal().getName();
response.sendRedirect("http://www.google.com");
}
New Class Path1
This is how your webapp should look like :
> DeCommGlobal
> |-->src
> |-->com
> |-->authentication
> |-->DeCommServlet.java
> |-->META-INF
> |-->WEB-INF
> |-->classes
> |-->lib
It was the deployment assembly that was causing the issue. Added the lib folder and we are good to go! Thanks

what values can a JSP form "action" take?

What can a JSP form action be?
I have a Login.jsp page for the user to end the details.
Can i give the servlet class in the form action?
here is the the servlet code.
package mybean;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try
{
System.out.println("In the Login Servlet");
LoginBean user = new LoginBean();
user.setUemail(request.getParameter("uemail"));
user.setUpass(request.getParameter("upass"));
user = LoginDAO.login(user);
if(user.isValid())
{
HttpSession session = request.getSession(true);
session.setAttribute("currentSessionUser",user);
response.sendRedirect("LoginSuccess.jsp");
}else
response.sendRedirect("LoginFailed.jsp");
} catch (Throwable exc)
{
System.out.println(exc);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
As per the specs , it can take any valid URI
This attribute specifies a form processing agent. User agent behavior for a value other than an HTTP URI is undefined.
Can i give the servlet class in the form action ?
Yes if the servlet class name resolves to a valid URL mapped in the web.xml or else you will encounter a 404 .
Let us consider your JSP is at the root of the application, then
<FORM action="someServletName" method="post">
Now this will be resolved as protocol://servername:port/context/someServletName .Now somewhere you should have a mapping for /someServletName , either in web.xml or through annotation to a Servlet or JSP.
<servlet>
<servlet-name>someServletName</servlet-name>
<servlet-path>packageName.servletName</servlet-path>
</servlet>
<servlet-mapping>
<servlet-name>someServletName</servlet-name>
<url-pattern>/someServletName</url-pattern>
</servlet-mapping>

Error 404 during GWT RPC jetty server

I just written simple RPC call, when i tried i get the below error, could you please help me out to fix this..
[WARN] 404 - POST /com.sribalajiele.gwt.client.SriBalajiEle/emailRpcService (127.0.0.1)
Email Failure404
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<title>Error 404 NOT_FOUND</title>
The code like below.
/*
* Copyright (c) Balaji electricals AG 2011, All Rights Reserved
*/
package com.sribalajiele.gwt.client.client;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
/**
* #author kdel.
* This interface provides Email Service.
*
*/
#RemoteServiceRelativePath("emailRpcService")
public interface EmailRpcService extends RemoteService {
public WriteToUsForm sendEmail(WriteToUsForm writeToUsForm) throws IllegalArgumentException;
}
/*
* Copyright (c) Balaji electricals 2011, All Rights Reserved
*/
package com.sribalajiele.gwt.client.client;
import com.google.gwt.user.client.rpc.AsyncCallback;
/**
* #author kdel
* Async service for Email.
*/
public interface EmailRpcServiceAsync {
void sendEmail(WriteToUsForm writeToUsForm, AsyncCallback<WriteToUsForm> asyncCallback)
throws IllegalArgumentException;
}
public final class EmailRpcServiceImpl extends RemoteServiceServlet implements EmailRpcService {
/**
* Default serialVersionUID.
*/
private static final long serialVersionUID = 1L;
#Override
public WriteToUsForm sendEmail(WriteToUsForm writeToUsForm) throws IllegalArgumentException {
System.out.println("send Email called");
}
}
In web.xml:
<servlet>
<servlet-name>emailService</servlet-name>
<servlet-class>com.sribalajiele.gwt.client.server.EmailRpcServiceImpl</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>emailService</servlet-name>
<url-pattern>sriBalajiEle/emailRpcService</url-pattern>
</servlet-mapping>
Finally i could correct my self, may be this is use full for others.
1) #RemoteServiceRelativePath("emailRpcService")
public interface EmailRpcService extends RemoteService {
2) In *Module*.gwt.xml
<servlet class="com.sribalajiele.ui.server.EmailRpcServiceImpl" path="/emailRpcService"/>
3) Register your servlet in web.xml
<servlet>
<servlet-name>eamilService</servlet-name>
<servlet-class>com.sribalajiele.ui.server.EmailRpcServiceImpl</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>eamilService</servlet-name>
<url-pattern>/com.sribalajiele.ui.SriBalaji/emailRpcService</url-pattern>
</servlet-mapping>
4) Usage:
final EmailRpcServiceAsync emailRpcServiceAsync = (EmailRpcServiceAsync) GWT.create(EmailRpcService.class);
ServiceDefTarget serviceDef = (ServiceDefTarget) emailRpcServiceAsync;
serviceDef.setServiceEntryPoint(GWT.getModuleBaseURL() + "emailRpcService");
emailRpcServiceAsync.sendEmail(parameter, new AsyncCall()) {
onSuccess() { }
onFailure() { }
}
Hope this will help...
The problem is that you have the servlet mapped to /sriBalajiEle/emailRpcService, but the request is being sent to /com.sribalajiele.gwt.client.SriBalajiEle/emailRpcService. The URL that the request is being sent to is generated by GWT in the form /${moduleName}/relativePath. If you include the following at the top of your GWT module, it should fix the 404.
<module rename-to="sriBalajiEle">
1) Include annotatation in your interface too.
#RemoteServiceRelativePath("emailRpcService")
public interface EmailRpcServiceAsync {
void sendEmail(WriteToUsForm writeToUsForm,
AsyncCallback asyncCallback)
throws IllegalArgumentException;
}
2) And change your url mapping to the following.
<url-pattern>com.sribalajiele.gwt.EmailRpcService/emailRpcService</url-pattern>
For my case, url mapping gave me headache for hours. Hope this helps.
the 404 error will site a url, I had to make sure the url sited in the 404 message was the url in my web.xml
<servlet-mapping>
<servlet-name>messageServiceImpl</servlet-name>
<url-pattern>/com.mbe.site.main/message</url-pattern>
</servlet-mapping>