Servlet mapping for ajax call parameters - java

I have ajax calls that have the url http://localhost:80/Push/GetContacts?id=23 and the following servlet mapping:
<servlet-mapping>
<servlet-name>Test</servlet-name>
<url-pattern>/GetContacts*</url-pattern>
</servlet-mapping>
The servlet does not get invoked on ajax calls. It returns a HTTP 404 not found response. What is the right URL pattern for my ajax calls?
Here is the ajax call that is not working because of the servlet.
jQuery.getJSON('http://localhost:8080/Push/GetContacts&callback=?', function(data) {
alert(data.data);
});
The servlet:
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException{
try{
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.write("{data: helloworld}");
out.close();
}
catch(Exception e){
e.printStackTrace();
}

The url pattern needs to be just /GetContacts without the star. The parameters are not part of the servlet mapping and are ignored when finding the correct servlet. If you wanted to support an URL like /GetContacts/23 you could use a servlet mapping for /GetContacts/* and retrieve the id using request.getPathInfo.
Edit: as BalusC just noticed, the url in your ajax call is incorrect. The parameter callback should be separated by a question mark, not an ampersand: GetContacts?callback=...
Also, {data: helloworld} is invalid according to the json spec, both data and helloworld should be enclosed in quotes. But that is also independent from the 404 problem.

Related

access WEB-INF/jsp from html

I have a simple application to test the communication between html and jsp. My jsp is located in
WEB-INF/test.jsp
Here is the structure of my files:
ProjectA
src
irstServlet.java
Web-Content
test1.html
WEB-INF
test.jsp
Here is the code from servlet
protected void doPost(HttpServletRequest request, response) throws ServletException, IOException {
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/test.jsp");
request.setAttribute("userName", request.getParameter("userName"););
dispatcher.forward(request, response);
}
First I have deploy in tomcat start my test1.html: It take me to the servlet: FirstServlet.java and I can enter userName there.
But after i enter the values in and press enter I expect it to forward me to test.jsp which is not working. I get the error:
The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
Edited:
In my html I am trying to use it like:
<form method="POST" name="XX" action="/HelloWorldServlet">
Still not working.
Please can someone help me?
Your code does not look like it would compile at all.
Parameter response has no type - should be HttpServletResponse
There is a semicolon (;) after request.getParameter("userName")
Also I'm not sure why you're getting RequestDispatcher from servlet context rather than from the request - then again I've never checked if it makes any difference.
Anyway, I would rewrite doPost method like this:
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("userName", request.getParameter("userName"));
req.getRequestDispatcher("/WEB-INF/test.jsp").forward(req, resp);
}
EDIT:
I'm assuimng you have either a correct servlet mapping in your web.xml:
<servlet>
<servlet-name>HelloWorldServlet</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorldServlet</servlet-name>
<url-pattern>/HelloWorldServlet</url-pattern>
</servlet-mapping>
or your servlet is annotated with #WebServlet annotation:
#WebServlet("/HelloWorldServlet")
public class FirstServlet extends HttpServlet {
//your code
}
. If neither of those is true, that's your problem right there.

Not Understanding Servlet RequestDispatcher

I have one doubt in Servlet RequstDispatcher. it has 2 methods(include and forward) right. my doubt is what happen when we use forward method following by include method..
RequestDispatcher rd = req.getRequestDispatcher("/S2");
rd.forward(req, res);
rd.include(req, res);
in this case these 2 methods executing fine or not ..
Thanks in Advance,
public void forward(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException
Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.
public void include(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException
Includes the content or data of a resource (servlet, JSP page, or HTML file) in the response.
More information on : http://www.javatpoint.com/requestdispatcher-in-servlet

call servlet from controller with parameters to servlet

I am writing a jsp file to call a controller with some parameters. And from this controller i want to call a servlet by passing the values from the controller. And with in the servlet i should get access to the parameters. Is it possible to forward values from jsp to servlet via controller?
Yes it's possible in Spring controller,
Try this in Spring controller:
public void requestedURL(HttpServletRequest req, HttpServletResponse res){
String jspParameter = request.getParameter("param_name");
req.getRequestDispatcher("your servlet url pattern?param1="+jspParameter)
.forward(req, res);
}

Showing servlet's list output in table using ajax asynchronously

I'm new to ajax and don't know how to use it for displaying my data from sevlet on page asynchronously.Moreover I must not to use additional libraries like jquery. So I have to "reinvent a wheel" not knowing how it wheel looks like. So I have simple servlet which sends to my request List of plain beans, here is it's doGet:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List<Category> categoryList = dao.getCategoryList();
request.setAttribute(PARAM_NAME_CATEGORY_LIST, categoryList);
RequestDispatcher dispatcher = getServletContext()
.getRequestDispatcher(PRODUCT_PAGE);
dispatcher.forward(request, response);
}
And after forwarding to my page I need to represent data in table with help of ajax.
Loading data and displaying it in AJAX is made in several steps:
The page sends an AJAX request to a URL of the wabapp. It registers a JavaScript callback function that will be called when the response to the request is received.
The webapp generates a response to this request. The content of the response could be HTML, XML, JSON or anything else.
The JavaScript callback function is called.
The JavaScript callback function gets the data from the response, and updates the DOM tree of the page to display the received data.
Googling for "AJAX example" will lead you to plenty of tutorials explaining how to do that. If you have a more specific problem, come back.

How do I specify a query string in Tomcat's <servlet-mapping> <url-pattern>?

I am running Tomcat 5.5.4 and have a servlet running with no problems. However, I'd like to set up a mapping to only launch the servlet when a URL containing a particular query string is submitted.
Right now in web.xml I have:
<servlet-mapping>
<servlet-name>MyServer</servlet-name>
<url-pattern>/go/*</url-pattern>
</servlet-mapping>
If a browser submits http://localhost/MyServer/go?P=123 the servlet is launched and all is well. However, I'd like to only launch that servlet if the URL is exactly as just shown. Unfortunately, right now if the URL is http://localhost/MyServer/go?P=AnyDarnThing the servlet still launches. I have tried setting up the following:
<url-pattern>/go?P=123</url-pattern>
but this results in The requested resource (/MyServer/go) is not available.
I've tried numerous variations (quoting the string, ...) on the above URL pattern but I always get the above error. I notice that if I (for debugging purposes) drop the "?" as in
<url-pattern>/goP=123</url-pattern>
I no longer get the error message and the server launches (but, of course, it doesn't respond to the "query string" because it's not properly formed.) This suggest to me that the "?" is causing a problem in the mapping. I've tried replacing it with its URL special character equivalent as follows:
<url-pattern>/go%3FP=123</url-pattern>
but this gives the same result just described above when I tried dropping the "?" altogether.
I realize I can let the servlet get launched when any query string is submitted and then "ignore" the request for all but the one I care about but there is a reason I'd prefer to not have the servlet launched to begin with. So, my question is, how can I configure the servlet so that it is only launched when a specific query string is included?
Thank you.
You can't do that. The url-pattern is pretty limited.
If you want to have distinct actions taken based on a GET parameter, you can do that manually. In the doGet() method of the servlet have a simple if-clause and invoke different methods depending on the query string / get param.
You can't do that using URL patterns.
You can achive this using filters. Implement a filter which will forward to the Servlet only if the query params exists.
Here is the how the filter will look like:
public class ServletAcessFilter implements Filter
{
public void init(FilterConfig filterConfig) throws ServletException
{
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException
{
//validate the request, check if the request can be forwarded to servlet.
if(request.getParameter("P").equalsIgnoreCase("123")){
filterChain.doFilter(request, response);
} else {
//write what you want to do if the request has no access
//below code will write 404 not found, you can do based on your requirement
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setStatus(404);
}
}
public void destroy()
{
}
}
Define the filter in the web.xml like this:
<filter>
<filter-name>ServletAccessFilter</filter-name>
<filter-class>com.ServletAcessFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ServletAccessFilter</filter-name>
<url-pattern>/go/*</url-pattern>
</filter-mapping>
To add to Bozho response, you may also try to move to Clean URLs
This will greatly increase your options in terms of URL pattern matching, and, in particular, may significantly ease configuration of a fronting reverse proxy if you ever need one.

Categories

Resources