Solved

simple servlet issue

Posted on 2013-01-25
12
377 Views
Last Modified: 2013-02-14
I wrote below simple servlet


package com.gp.java;

import java.io.IOException;
import java.io.PrintWriter;

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 SimpleServlet
 */
@WebServlet(description = "SimpleServlet desc", urlPatterns = { "/SimpleServletUP" })
public class SimpleServlet extends HttpServlet {
      private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SimpleServlet() {
        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
            response.setContentType("type/html");
            System.out.println("hello from get");
            PrintWriter writer=response.getWriter();
            writer.println("<h3>hello in html</h3>");
            
      //      String userNam=request.getParameter("userName");
      //      writer.println("heello"+userNam);
            
      }

      /**
       * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
       */
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
      }

}


When I run instead of printing
'hello in html' in the page and
'hello from get' on console
It is trying to open the servet source as in the attachment. How can i fix this issue.

 please advise.
Any links resources, sample code, ideas highly appreciated. Thanks in advance
SimpleSErvlet.jpg
0
Comment
Question by:gudii9
  • 5
  • 4
  • 2
  • +1
12 Comments
 
LVL 27

Accepted Solution

by:
rrz earned 350 total points
Comment Utility
>response.setContentType("type/html");  
Remove that line or try using
response.setContentType("text/html");
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
>response.setContentType("type/html");  

response.setContentType("text/html");

both above lines you mentioned are same right. Please advise
0
 
LVL 27

Expert Comment

by:rrz
Comment Utility
No, they are not the same. You must specify the MIME type of the content.  
Look at list towards the bottom of the following page.
http://en.wikipedia.org/wiki/Internet_media_type
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
>>No, they are not the same. You must specify the MIME type of the content.  

How they are different.

For me they look same as below

>>response.setContentType("type/html");  
>>Remove that line or try using
>>response.setContentType("text/html");


How should i modify the servlet code. can you please post whole servlet code

package com.gp.java;

import java.io.IOException;
import java.io.PrintWriter;

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 SimpleServlet
 */
@WebServlet(description = "SimpleServlet desc", urlPatterns = { "/SimpleServletUP" })
public class SimpleServlet extends HttpServlet {
      private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SimpleServlet() {
        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
            response.setContentType("type/html");
            System.out.println("hello from get");
            PrintWriter writer=response.getWriter();
            writer.println("<h3>hello in html</h3>");
           
      //      String userNam=request.getParameter("userName");
      //      writer.println("heello"+userNam);
           
      }

      /**
       * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
       */
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
      }

}
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 50 total points
Comment Utility
Does any servlet work on the same container?
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
yes. other servlets are working fine. For example below servlet worked perfect

package com.gp.java;

import java.io.IOException;
import java.io.PrintWriter;

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 XmlServlet
 */

public class XmlServlet extends HttpServlet {
      private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public XmlServlet() {
        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("hello from get of xml serv");
            PrintWriter writer=response.getWriter();
            writer.println("<h3>hello in html of xml serv</h3>");
      
                  String userNam=request.getParameter("userName");
                  writer.println("heello"+userNam);
                  String[] location=request.getParameterValues("location");
                  writer.println("u at"+location.length+"places");
      }
      

      /**
       * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
       */
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
            System.out.println("hello from post of xml serv");
            PrintWriter writer=response.getWriter();
            writer.println("<h3>hello in html of xml serv</h3>");
      
                  String userNam=request.getParameter("userName");
                  writer.println("heello"+userNam);
                  String[] location=request.getParameterValues("location");
                  writer.println("u at"+location.length+"places");
      }

}
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 7

Author Comment

by:gudii9
Comment Utility
even below worked perfect

package com.gp.java;
 
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
@WebServlet(description = "ParameterName desc", urlPatterns = { "/ParameterNameUP" })
public class ParameterName extends javax.servlet.http.HttpServlet implements
        javax.servlet.Servlet {
 
    public ParameterName() {
        super();
    }
 
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {/*
         
        PrintWriter pw = response.getWriter();
 
                //
                // Let's obtains parameters name here!
                //
        Enumeration enumeration = request.getParameterNames();
        while (enumeration.hasMoreElements()) {
            String parameterName = (String) enumeration.nextElement();
            pw.println("Hello Parameter = " + parameterName);
        }
        pw.close();
    */
          
    response.setContentType("text/html");
    PrintWriter writer=response.getWriter();
    String userName=request.getParameter("name");
    HttpSession session=request.getSession();
    if( userName!="" & userName != null){
          session.setAttribute("savedUserName", userName);
    }
   
    writer.println("Hellllooo request"+userName);
    writer.println("Hellllooo session"+(String)session.getAttribute("savedUserName"));
   
   
   
    }
 
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
    }
}
0
 
LVL 16

Expert Comment

by:Valeri
Comment Utility
As I can see the servlets that work as you expecting don't have this line!
Btw try to remove "response.setContentType("type/html");" and to replace it with:

response.setHeader("Cache-Control", "no-cache");
response.setHeader("Content-Type", "text/xml;charset=UTF-8");
0
 
LVL 16

Assisted Solution

by:Valeri
Valeri earned 100 total points
Comment Utility
ops, sorry... the second line must be:
response.setHeader("Content-Type", "text/html;charset=UTF-8");
0
 
LVL 27

Expert Comment

by:rrz
Comment Utility
>When I run instead of printing
>'hello in html' in the page and
>'hello from get' on console
>It is trying to open the servet source as in the attachment. How can i fix this issue.

The problem is the following line
>response.setContentType("type/html");  
The browser doesn't know what to do with the response of  that content type. It asks the Operating System of the client to take control.

The working code you posted at
http://www.experts-exchange.com/Programming/Languages/Java/Q_28009529.html#a38824265  
doesn't send a content type. Therefore the content type is assumed to be text/html
The last code you posted has the line  
response.setContentType("text/html");  
Thus, the browser understands what to do with that response.
0
 
LVL 7

Author Comment

by:gudii9
Comment Utility
>>response.setContentType("text/html");  

I am confused bit. should  i keep above line or not. I believe you are suggesting to remove.What is the use of that line.
when i have to put it, when i should not put it. please advise
0
 
LVL 27

Expert Comment

by:rrz
Comment Utility
>>response.setContentType("text/html");    
The default type is   text/html  .   Therefore the above line is not necessary.
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Fibonacci challenge 11 82
bunnyEars2 challenge 6 66
count7 challenge 12 67
json example 39 110
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues undeā€¦
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
The viewer will learn how to implement Singleton Design Pattern in Java.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now