How include servlet output to jsp file - java

In my web application I have a main page that contain some information. This page is created by servlet and corresponding jsp file. Almost all other pages in my web application must contain the same information as main page plus some addition information. I don't want dublicate code, so I want to use output of main servlet in other jsp files. Below is a simple example of what I try to accomplish.
This is web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>servlet1</servlet-name>
<servlet-class>app.Servlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servlet1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>servlet2</servlet-name>
<servlet-class>app.Servlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servlet2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
This is java files:
servlet1.java
package app;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servlet1 extends HttpServlet {
#Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("servletAttribute", 1);
RequestDispatcher view = request.getRequestDispatcher("/servlet1.jsp");
view.forward(request, response);
}
}
servlet2.java
package app;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servlet2 extends HttpServlet {
#Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("servletAttribute", 2);
RequestDispatcher view = request.getRequestDispatcher("/servlet2.jsp");
view.forward(request, response);
}
}
This is jsp files:
servlet1.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
servlet1
<%
Integer servletAttribute = (Integer)request.getAttribute("servletAttribute");
out.print("<br>servletAttribute:" + servletAttribute);
%>
servlet2.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<jsp:include page="/servlet1" />
servlet2
<%
Integer servletAttribute = (Integer)request.getAttribute("servletAttribute");
out.print("<br>servletAttribute:" + servletAttribute);
%>
So servlet2.jsp must display output of servlet1. It display it, but it doesn/t display addition information from servlet2. And I get this error in Log file:
org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [servlet2] in context with path [/WebApplication3] threw exception [java.lang.IllegalStateException: Exception occurred when flushing data] with root cause
java.io.IOException: Stream closed
As I understant this error appears because when servlet2.jsp call "/servlet1" servlet1 sent response to client and servlet2.jsp doesn't have session anymore.
So my question is - How can I fix my code to accomplish what I want? Is it possible to include output of some servlet to some jsp file? If it's possible, is it a good or bad practice?

In servlet2.jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<jsp:include page="/servlet1" />
In servlet2.jsp, you have used jsp:include.
It is including the response of the servlet1 response.
But the servlet1, it is going to forward the response to another jsp. So that exception occurs.
To avoid this, in Servlet1 class should use view.include(request,response); instead of view.forward(request, response);.
package app;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servlet1 extends HttpServlet {
#Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("servletAttribute", 1);
RequestDispatcher view = request.getRequestDispatcher("/servlet1.jsp");
view.include(request, response);
}
}

Related

Servlets & IntelliJ

I created a test project under Intellij to start Java EE with Tomcat.
My server starts well, no worries aside.
I created a Servlet which contains my HTML code, as well as doPost and getPost.
When I want to run the servlet, the server launches fine but I end up with a blank page.
An idea ?
Code :
package com.octest.servlets;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
#WebServlet(name = "Test")
public class Test extends HttpServlet {
protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType ("text/html");
response.setCharacterEncoding ("UTF-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<meta charset=\"utf-8\" />");
out.println("<title>Test</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>Bonjour !</p>");
out.println("</body>");
out.println("</html>");
}
protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
Et le web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>Test</servlet-name>
<servlet-class>com.octest.servlets.Test</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Test</servlet-name>
<url-pattern>/app</url-pattern>
</servlet-mapping>
</web-app>
Thanks
The browser will make a GET request but your HTML page is in doPost method. You need to keep this page inside doGet method.

how can i resolve this : The method received in the request-line is known by the origin server but not supported by the target resource

I m receiving error as "HTTP Status 405 – Method Not Allowed" when trying to execute the below query, I am not sure what I can do to resolve this.
Also, someone could suggest me where can I get flight APIs for free for testing.
package com.Gmaps.web.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.Gmaps.web.DAO.GmapsDAOLayer;
import com.Gmaps.web.Model.GmapsModel;
/**
* Servlet implementation class GmUserData
*/
public class GmUserData extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response, String originAutocomplete) throws ServletException, IOException//, NumberFormatException
{
// String uid = request.getParameter("userid");
// GmapsDAOLayer dao = new GmapsDAOLayer();
// GmapsModel model = dao.getUser(uid);
RequestDispatcher rd = request.getRequestDispatcher("UserPage.jsp");
rd.forward(request, response);
// float orgin = Float.parseFloat(request.getParameter("desti"));
String orgin = request.getParameter("place");
GmapsDAOLayer dao = new GmapsDAOLayer();
GmapsModel model = dao.getUser(orgin);
System.out.println("origin: "+orgin);
}
}
And here is my index.html
<html>
<body>
<h2>Hello World!</h2>
<form action="getuserdata" method="get">
<input type= "text" name="userid"><br>
<input type= "text" name="firstname"><br>
<input type="submit">
</form>
</body>
</html>
Here is my web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>GmUserData</servlet-name>
<servlet-class>com.Gmaps.web.controller.GmUserData</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GmUserData</servlet-name>
<url-pattern>/getuserdata</url-pattern>
</servlet-mapping>
</web-app>
Help would be much appreciated!
try with this <form action="/getuserdata" or just this action="GmUserData"

Java: HTTP Status 405 - using RequestDispatcher and doPost()

I have a simple program which get username and password, if the password is servlet then it will forward to the welcome page, else, it will show a message and includes html login form.
When I enter username and password and click on login, no matter what, it always shows me the "HTTP Status 405 : HTTP method GET is not supported by this URL" error.
I have read a lot of questions and answers here, none of them helped me to solve this problem.
Here's my code:
Simple.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;
public class Simple extends HttpServlet {
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String p=request.getParameter("userPass");
if(p.equals("servlet")){
RequestDispatcher rd=request.getRequestDispatcher("welcome");
rd.forward(request, response);
}
else{
out.print("Sorry username or password error!");
RequestDispatcher rd=request.getRequestDispatcher("index.html");
rd.include(request, response);
}
}
}
WelcomeServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class WelcomeServlet extends HttpServlet {
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
}
}
index.html
<form action="go" method="post">
Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPass"/><br/>
<input type="submit" value="login"/>
</form>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>Simple</servlet-name>
<servlet-class>Simple</servlet-class>
</servlet>
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Simple</servlet-name>
<url-pattern>/go</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>

404 Apache tomcat in a Java project

So this is my project:
Where Registro.java is:
package Ejer2;
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;
import javax.servlet.http.HttpSession;
import javax.servlet.*;
#SuppressWarnings("deprecation")
#WebServlet(urlPatterns="/Registro")
public class Registro extends HttpServlet implements SingleThreadModel{
private static final long serialVersionUID = 1L;
public Registro() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
HttpSession session=req.getSession(true);
Usuario miuser=(Usuario)session.getValue(session.getId());
if(miuser==null){
miuser=new Usuario(req.getParameter("user"),req.getParameter("password"));
session.putValue(session.getId(),miuser);
}
res.setContentType("text/html");
String user=req.getParameter("user");
//String pass = req.getParameter("pass");
PrintWriter toClient = res.getWriter();
toClient.println("<html>");
toClient.println("<title>REGISTRO REALIZADO</title>");
toClient.println("Usuario "+user+" registrado con exito");
toClient.println("</html>");
toClient.close();
}
}
And registro.html is:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Registro</title>
</head>
<body>
<form action="/Ejer2/Registro" method="POST">
<input type=hidden name=registro value=resultadoRegistro>
<BR><BR>Username: <input type=text name=user>
<BR><BR>Password: <input type=password name=pass>
<BR><BR><input type=submit value="Enviar"><input type=reset>
</form>
</body>
</html>
When I run registro.html everything goes as expected:
But when I enter an username and a password it doesnt work:
4
It seems as if it doesnt find the Registro.java. I have tried changing the action="/Ejer2/Registro" to many other things like just /Registro orthe full http://... but still doesnt work.
This is my web.xml:
What can be the problem?
I guess you are missing servlet mapping in your web.xml. You need to register your servlet in web.xml (open web.xml file and at the bottom change tab to see actual source code not designer) add following code and you should be good to go
<servlet>
<servlet-name>RegistroServlet</servlet-name>
<servlet-class>Ejer2.Registro</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegistroServlet</servlet-name>
<url-pattern>/Registro</url-pattern>
</servlet-mapping>
I also suggest you to step back and start with basic java before attemping to write web application. You have several newbie issueses with your code:
1) name of packages should start with lower case !
2) also url mapping should be with lower case like this /registro
in your form action change url to match urlmapping. In your case it's
form action="/Registro" ...
Ejer2 is name of package it has nothing to do with url mapping. Hope it helps to resolve your problem

Cannot include jsp in servlet

I need to include .jsp file in my servlet.
I have written simple jsp file, which i have put in dir WEB-INF/jsps/:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="ISO-8859-1"%>
<html>
<head>
<title> Galleries </title>
</head>
<body>
Test
</body>
</html>
and servlet:
package photoGallery;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#SuppressWarnings("serial")
public class GalleriesServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
try
{
System.out.println("Test");
//get the request dispatcher
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/jsps/galleries.jsp");
//forward to the jsp file
if (dispatcher != null)
dispatcher.forward(request, response);
else
System.err.println("Error: dispathcer is null");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
in web.xml I have added next lines:
<servlet>
<display-name>Gallery Servlet</display-name>
<servlet-name>GalleryServlet</servlet-name>
<servlet-class>photoGallery.GalleriesServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GalleryServlet</servlet-name>
<url-pattern>/galleries/*</url-pattern>
</servlet-mapping>
When I'm openning page
http://localhost:8080/PhotoGallery/galleries
then in console it prints "Test", but in browser I see "HTTP Status 404 - Not Found"
Where I have made mistake?
I have found my mistake.
There was other servlet which was mapped to "/*", and because of that appeared errors

Categories

Resources