tomcat PrintWriter has no output - java

i just installed Tomcat via Netbeans and created a new project. I just want to print some text on screen but only "Hello World!" is shown. Do i have to something specific to show text on screen?
EDIT: [SOLVED] I do not know what the problem was. I just changed my IDE from Netbeans to Eclipse, now everything works.
System: Ubunut 16.04 LTS 64Bit
#WebServlet(name = "MicStreamReciever", urlPatterns = {"/MicStreamReciever"})
public class MicStreamReciever extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("processRequest");
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
PrintWriter out = response.getWriter();
out.println("doGet");
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}

Related

Servlet gives a blank page when it should be redirecting

I'm having a problem in my servlet ("maakservlet"), the maakservlet should redirect automatically to welkom.jsp but instead it just gives me a blank page.
I have tried requestdispatches, response.sendRedirect etc.
Here is my code from the servlet:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int code = 1;
String voornaam = request.getParameter("voornaam");
String achternaam = request.getParameter("achternaam");
String eerstebezoek = request.getParameter("eerstebezoek");
String meerderebezoeken = request.getParameter("meerderebezoeken");
String attractie = request.getParameter("attractie");
String naamattractie = request.getParameter("naamAttractie");
String naampretpark = request.getParameter("naampretpark");
Bezoeker bezoeker = new Bezoeker(voornaam, achternaam);
if (attractie == "geen") {
;
} else {
bezoeker.voegToeAanWishlist(attractie);
}
if (eerstebezoek == null && meerderebezoeken == null) {
bezoeker.setPretparkcode(1000);
} else if (meerderebezoeken != null) {
bezoeker.setPretparkcode(code);
code += 1;
}
String destination = "welkom.jsp";
RequestDispatcher requestDispatcher = request.getRequestDispatcher(destination);
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
String welkom = "welkom.jsp";
response.sendRedirect("welkom.jsp");
RequestDispatcher rd = request.getRequestDispatcher("welkom.jsp");
rd.forward(request, response);
}
To redirect the request to a completely different page you have to use your response:
response.sendRedirect(destination);
See: https://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/http/HttpServletResponse.html#sendRedirect(java.lang.String)

StandardWrapperValve[web.dbServlet]: Servlet.service() for servlet web.dbServlet threw exception java.lang.NullPointerException

I try to insert some information in the table, but get such an error (NullPointerException). Maybe it causes of empty request, but I'm not sure.
Here is a log with error:
enter image description here
First Servlet:
#WebServlet("/clientServlet")
public class clientServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
Client client = new Client();
client.setName(request.getParameter("name"));
client.setSurname(request.getParameter("surname"));
HttpSession session = request.getSession();
session.setAttribute(sessionKey.client, client);
response.sendRedirect("addTour.html");
}
The second one:
#WebServlet("/tourServlet")
public class tourServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
Tour tour = new Tour();
tour.setCountryTo(request.getParameter("countryTo"));
tour.setAmountOfDays(request.getParameter("amountOfDays"));
session.setAttribute(sessionKey.tour, tour);
response.sendRedirect("final.jsp");
}
Problem appears in this Servlet:
#WebServlet("/dbServlet")
public class dbServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public dbServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
IRepositoryCatalog catalog = new RepositoryCatalog("jdbc:hsqldb:hsql://localhost/workdb");
HttpSession session = request.getSession();
Client client = (Client) session.getAttribute(sessionKey.client);
Tour tour = (Tour) session.getAttribute(sessionKey.tour);
catalog.Clients().add(client);
catalog.saveAndClose();
catalog.Tours().add(tour);
catalog.saveAndClose();
catalog.saveAndClose();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException a) {
a.printStackTrace();
}
}
At first impression i can say that maybe the first and second servlet are for a POST method so doing a doGet and trying to 'getParameter' you will get empty object and so throw a NullPointerException. Can you post something about your view?
(I would comment but i can't yet)

how can i get json data from java servlet to jquery

this is my servlet: json array have objects "esquina". esquina have two attributes double coordX and double coordY
package servlets;
#WebServlet("/Mapa")
public class ServletMapa extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ServletMapa() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Sistema instanciaSys = Sistema.darInstancia();
instanciaSys.inicializarSistema(6);
Esquina[] esquinas = instanciaSys.getEsquinas();
JSONArray json =new JSONArray();
JSONObject jO = null;
for (Esquina esquina : esquinas) {
jO = new JSONObject(esquina);
json.put(jO);
System.out.println(json);
}
request.setAttribute("esquinas", esquinas);
request.setAttribute("json", json);
request.getRequestDispatcher("/gui/Mapa.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
i need to get the data from jsonArray to jquery, i tried getJSON() function , but didnt work.
hereĀ“s the code
function cargarMarcadores() {
var x=$("#iniSistema");
x.click(function(){
$.getJSON('localhost:8080/Carpuleame/Mapa',function(data){
alert("data");
});
});
}
there are antoher way to do it ?
You probably want something like this:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Sistema instanciaSys = Sistema.darInstancia();
instanciaSys.inicializarSistema(6);
Esquina[] esquinas = instanciaSys.getEsquinas();
JSONArray json =new JSONArray();
for (Esquina esquina : esquinas) {
JSONObject jO = new JSONObject();
jO.put("coordX", esquina.getCoordX());
jO.put("coordY", esquina.getCoordY());
json.put(jO);
}
// tell the client that JSON is coming
response.setContentType("application/json");
resposne.setCharacterEncoding("UTF-8");
json.write(response.getWriter());
}
There are a bunch of frameworks that'll take away a lot of the "brute-force"-iness of this code, but this is very close to your starting position.

Mockito test returning NullInsteadOfMockException

I am trying to test my servlet for login page but the Mock test is throwing an exception
LoginServlet
/**
* #see HttpServlet#HttpServlet()
*/
public LoginServlet() {
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
HttpSession session = request.getSession(true);
boolean result = false;
String username = request.getParameter("username");
String password = request.getParameter("password");
result = obj.validateLogin(username, password);
if (result) {
session.setAttribute("username", username);
response.sendRedirect("UserHome.jsp");
} else {
response.sendRedirect("login.jsp");
}
return;
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
MockTest : this is the test case I have written for login
public class LoginServletMockTest {
#Test
public void testServlet() throws Exception {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
HttpSession session = request.getSession(true);
when(request.getParameter("username")).thenReturn("garwitauday");
when(request.getParameter("password")).thenReturn("123");
when(request.getSession()).thenReturn(session);
doNothing().when(session).setAttribute("username", "garwitauday");
doNothing().when(response).sendRedirect("Userhome.jsp");
LoginServlet loginservlet = new LoginServlet();
loginservlet.doPost(request, response);
verify(session).setAttribute("username", "garwitauday");
verify(response).sendRedirect("Userhome.jsp");
}
}
I am not able to resolve this issue
Create the mockito object for HttpSession also and set the mockito session object in request.
And continue your same do(..).when(..) or when(..).thenReturn(..) to mock the calls.
Make sure to set the attributes and parameters in request and session objects for easy testing.
If your's is mvc based servet, better to use MockMvc and it's builder objects.

How to test non-Spring controllers using Spring test framework

Can anybody please provide me some guidance or code sample on how to do this?
HomePageController.java
public class HomePageController extends HttpServlet {
private static final Logger log = Logger.getLogger(HomePageController.class);
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
log.debug("Into the HomePageController...");
showPage(request, response, HOME_PAGE_URL);
}
private void showPage(HttpServletRequest request, HttpServletResponse response, String viewName) throws ServletException, IOException {
log.debug("Displaying " + viewName + " page now...");
String url = TEMPLATE_PAGE_URL + "?gotoPage=" + viewName;
//forward the request to the page
request.getServletContext().getRequestDispatcher(url).forward(request, response);
}
}

Categories

Resources