Use request.getRequestDispatcher(myurl).forward(request,response) but not working - servlets

When I use request.getRequestDispatcher(myurl).forward(request, response) in servlet to jump to another HTML page, I find it doesn't work. A response can be seen in web browser but the page just doesn't change.
I tried response.sendRedirect(myurl) then, and it also doesn't work.
Here is my code:
public class ServletDemo extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response) {
System.out.println("get");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.sendRedirect("/ForwardTest/new.html");
// request.getRequestDispatcher("/new.html").forward(request, response);
System.out.println("success");
}
}
Each time I run this, just get a "success" output in console. That means getRequestDispatcher had run, but not correctly.

Related

What is called first doGet or doPost? [duplicate]

This question already has answers here:
doGet and doPost in Servlets
(5 answers)
Closed 1 year ago.
I have question about doGet doPost priorities (if there are any). Here is my HelloServlet class:
public class HelloServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().println("Hello, World Post!");
}
#Override
public void init() throws ServletException {
System.out.println("Servlet " + this.getServletName() + " has started.");
}
#Override
public void destroy() {
System.out.println("Servlet " + this.getServletName() + " has stopped.");
}
This class is mapped to the /greeting URL. When I try to access this page now, everything is fine. But when I change the doPost and doGet methods I gives me an error: HTTP Status 405 - HTTP method GET is not supported by this URL. Everytime I read about doGet and doPost I assume these methods are interchangeable. So what is the problem with this version of these methods?
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().println("Hello, World Post!");
}
This of course caused no exception because doGet is present, but it will not do any work. When I remove doGet method it throws the exception.
Can you please tell me what exactly happens in the moment I use my code URL? http://localhost:8080/greeting
Why the client just cannot use the doPost method to obtain the data from the server when doGet is completely missing?
Thank you!
UPDATE WEB.xml file
<display-name>Hello World Application</display-name>
<servlet>
<servlet-name>helloServlet</servlet-name>
<servlet-class>com.wrox.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>/greeting</url-pattern>
</servlet-mapping>
If you do not specify the request method by default it will be GET which means doGet() will be called.
example: http://www.anywebsite.com is a default GET request.
But you have to specify your request is a POST request to execute doPost()
example:
<form action="/servlet" method="POST">
<input type="text" name="something"
</form>
if you have not mentioned in then default it call doGet method But if you have to specify your request is a POST in below code as like then tomcat call the service method where service method decide where request should go
<form action="/servlet" method="POST">
<input type="text" name="something"
</form>
The protected service method checks the type of request, if request type is get, it calls doGet method, if request type is post, it calls doPost method, so on. Let's see the internal code:
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String method = req.getMethod();
if(method.equals("GET"))
{
long lastModified = getLastModified(req);
if(lastModified == -1L)
{
doGet(req, resp);
}
//rest of the code
}
}

Wildcard path mapping /A/* should return 404 when path info is absent like /A

I am new in Servlets. I am trying to map a URL using the wildcard (*), but it's not working the way i expected.
Here is my servlet class.
#WebServlet(urlPatterns = {"/A/*"})
public class TestServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().write("Working...");
}
}
The above servlet is working for both example.com/A and example.com/A/car.
I want to work the servlet only for the the second option which is example.com/A/whatEver. How can i do that ?
In simple: I just want to work the servlet if there's anything after example.com/A.
Any help will greatly appreciated.
Just invoke HttpServletResponse#sendError() with SC_NOT_FOUND (404) when HttpServletRequest#getPathInfo() is null or empty or equals to /.
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String pathInfo = request.getPathInfo();
if (pathInfo == null || pathInfo.isEmpty() || pathInfo.equals("/")) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
// ... (continue)
}

How to prevent spam request in Servlet

I'm writing a small servlet to prevent spam requests from an J2ME app. But, i don't know how to do this.
Could you help me or suggest to me some links/posts about this?
I assume you have another Servlet that handles 'valid' requests and you want spam requests to be filtered out?
If that is so, then you need a Filter.
You would configure it in your web.xml (or by annotation) to be applied to all requests going to your actual Servlet and implement it like that:
public class SpamFilter implements Filter {
#Override
public void init(FilterConfig config) throws ServletException {
// maybe read some configuration, e.g. rules that say what is spam and what is not
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (isValidRequest(request)) {
chain.doFilter(request, response);
} else {
// request is spam, prevent further processing (so, do nothing)
}
}
#Override
public void destroy() {}
}

How can i send response to a request without having HttpServletresponse

Hi please some one help me in this issue.
I have a class which extends HttpServlet and a method called doGet(HttpServletRequest request)
But i dont have a HttpServletResponse .Now i want to respond to a request from a client as im not having response how can i respond to a request.Can i create able to create it dynamically in that class using reflections and is their any other way..My problems pseudo code looks as follows
protected void doGet(HttpServletRequest request)throws ServletException, IOException {//having only request as parameter in doGet()
//Want to respond to a jsp with out having a response
//how can i create a response object if i got a HttpServletResponse response the code looks as follows
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String name = request.getParameter("username");
String password = request.getParameter("password");
if(name.equals("James")&& password.equals("abc")){
response.sendRedirect("result.jsp");
}
else{
pw.println("u r not a valid user");
}
}
There is no such method protected void doGet(HttpServletRequest request) throws ServletException, IOException
The method signature is:
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException

Is it ok to make all methods called from a servlet doGet() static to avoid synchronization?

I have a servlet which performs various business logic. I want to avoid synchronisation like this:
#Override
protected void doGet(final HttpServletRequest _req, final HttpServletResponse _resp) throws ServletException, IOException {
synchronized (MyServlet.class) {
various();
calls();
and_logic(_req, _resp);
}
}
by making all called methods static and enforcing it like this:
#Override
protected void doGet(final HttpServletRequest _req, final HttpServletResponse _resp) throws ServletException, IOException {
_doGet(_req, _resp);
}
private static void _doGet(final HttpServletRequest _req, final HttpServletResponse _resp) throws ServletException, IOException {
various();
calls();
and_logic(_req, _resp);
}
I won't use any static variables and all my method calls are assumed to be thread-safe. Are there any non-obvious drawbacks?
I won't use any static variables and all my method calls are assumed to be thread-safe.
Under these conditions neither you don't need synchronization nor static methods. Just use instance methods of a servlet or some other service class.

Resources