How to send input to servlet but not from action? - forms

I've got a form that I use to post some inputs to one site but I want to post them also to my servlet - is it even possible?
I've tried to do something with submit button, I mean executing onclick with function but something is not working properly
<input type="submit" value="value1" onclick="afterSubmit()"/>
...some inputs...
</form>
form=document.getElementById("${initParam['posturl']}";
function afterSubmit() {
form.action="http://localhost:8080/url/servlet";
}
</script>
And my servlet:
public class sendThis extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println(request.getParameter("item_name_1"));
}
}```
So when I click on submit button and then go to localhost:8080/url/servlet, I get this error:
HTTP Status 405 – Method Not Allowed
Type Status Report
Message HTTP method GET is not supported by this URL
Description The method received in the request-line is known by the origin server but not supported by the target resource.

Add doGet method to your servlet and handle the request:
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println(request.getParameter("item_name_1"));
}

Related

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

Attempt to POST to a servlet results in HTTP Status 404 - Could not find resource for relative

I've a HTML form:
<form action="rest/ws/addNote" method="post">
I'm trying to POST to this servlet:
#WebServlet("/ws")
public class AddNote extends HttpServlet {
#POST
#Path("/addNote")
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// ...
}
}
But I keep getting
HTTP Status 404 - Could not find resource for relative : /ws/addNote of full path: http://localhost:8080/project/rest/ws/addNote
You are sending a post request for that you should have a post request handler method there in your servlet. I am assuming you are not using any REST framework. Then your servlet should be:
#WebServlet("/rest/ws/addNote")
public class AddNote extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
........
Or if you are already using any REST frameworks like Jersy, don't use a servlet here.Try some examples
Update
since you are using REST try following instead of servlet:
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
#Path("/ws")
public class AddNote {
#POST
#Path("/addNote")
public Response addUser(
#FormParam("name") String name,
#FormParam("age") int age) {
.........
Here I assumed in your web.xml, the REST controller servlet mapping is /rest/* and your html <form> having <input> tags with names name,age, then the will be passed into the corresponding method arguments as above.
Full example you can see here

Eclipse/Tomcat7: application context root reloading returns 404

I have a servlet which is mapped to application context root using the "" string:
So when I hit the url http://127.0.0.1:8080/myapp/, I can see "This is ROOT!" in the browser. So far so good.
But if I modify something, say changing the String This is ROOT!! to ROOT!! and save the file in eclipse. Eclipse will take a couple of seconds to reload the context. Now if i hit the same url, a 404 page is displayed while all other pages still work fine. Only the root mapping is broken. So I redeploy (eclipse's "run on server") the app and the root mapping is back again. Any ideas on how can I fix this?
#WebServlet("")
public class Root extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().println("This is ROOT!!");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
https://issues.apache.org/bugzilla/show_bug.cgi?id=54955
This is a bug of tomcat 7.0.40.
when you deploy it. Context root is accessible. But reload the app will cause context root to return 404.

JBoss AS 6, Eclipse, Seam 2.2 - Servlet don´t show up

I use JBoss AS 6 with Seam 2.2 in Eclipse. I had create a simple Seam 2 Web Project, (I think with seam gen) and now I wanted to add servlet.
File->New->Servlet
public class Test extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter writer = response.getWriter();
writer.println("Hello post!");
writer.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter writer = response.getWriter();
writer.println("Hello get!");
writer.close();
}
}
In web.xml there is also the servlet registrated.
Okay, but when I compile all and go to localhost:8080/mypage/test the page get loaded but no output is visible (also not in the sourcecode of the page).
The symptoms indicate that your project isn't properly deployed. Make sure that your project is properly built and deployed and that the server is cleanly restarted.

Using GWT RPC from a GWTTestCase using Guice

I've configured my GWT app with Guice as documented here. With this setup the app works fine.
However what I'd like to do now is get a GWTTestCase to call a service using GWT RPC. To this end I've done this,
Updated my <app>JUnit.gwt.rpc so that the service URL maps to GuiceRemoteServiceServlet
Added an init() method to GuiceRemoteServiceServlet to initialise the Injector as per this comment
Unfortunately I'm still getting an error,
com.google.inject.ProvisionException: Guice provision errors:
Caused by: com.google.inject.OutOfScopeException: Cannot access scoped object. Either we are not currently inside an HTTP Servlet request, or you may have forgotten to apply com.google.inject.servlet.GuiceFilter as a servlet filter for this request.
at com.google.inject.servlet.GuiceFilter.getContext(GuiceFilter.java:132)
at com.google.inject.servlet.GuiceFilter.getRequest(GuiceFilter.java:118)
at com.google.inject.servlet.InternalServletModule$1.get(InternalServletModule.java:35)
.....
The object it's trying to provision is ServletContext. The cause of the error is due to the fact the GuiceFilter hasn't been called so the ServletContext hasn't been bound to ThreadLocal.
Is there any way of getting past this?
In the Junit environment you aren't getting two things that you normally get from the servlet container: the setup/destroy help from the GuiceServletContextListener and the filtering of the GuiceFilter, so you need to do these bits yourself.
You basically need to create another servlet that wraps your servlet and does all the setup/filtering that you'd normally see done by the servlet container; what I recommend is something like this:
Suppose your servlet is called AdriansGuicedGwtServiceServlet. Then create this in your testing directory:
public class TestAdriansGuicedGwtServiceServlet extends AdriansGuicedGwtServiceServlet {
private GuiceFilter filter;
#Override
public void init() {
super.init();
// move your injector-creating code here if you want to
// (I think it's cleaner if you do move it here, instead of leaving
// it in your main servlet)
filter = new GuiceFilter();
filter.init(new FilterConfig() {
public String getFilterName() {
return "GuiceFilter";
}
public ServletContext getServletContext() {
return TestAdriansGuicedGwtServiceServlet.this.getServletContext();
}
public String getInitParameter(String s) {
return null;
}
public Enumeration getInitParameterNames() {
return new Vector(0).elements();
}
});
}
#Override
public void destroy() {
super.destroy();
filter.destroy();
}
private void superService(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
super.service(req, res);
}
#Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
filter.doFilter(new FilterChain() {
public void doFilter (ServletRequest request, ServletResponse response)
throws IOException, ServletException {
superService(request, response);
}
});
}
}
And then in your <app>Junit.gwt.rpc have it map in TestAdriansGuicedGwtServiceServlet instead of your real servlet.