Cannot include jsp in servlet - java

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

Related

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"

404 when servlet is invoked but works directly when url to servlet is used from browser

Problem: When I invoke url (url-mapping) directly in the browser it works pretty well but when I use post method to invoke servlet from jsp file, it does not work but gives an error:
Type Status Report
Message /HelloWorld/myservlet
Description The origin server did not find a current representation
for the target resource or is not willing to disclose that one exists.
Jsp page:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Hello World</title>
</head>
<body>
<form method="post" action="myservlet">
<input type="submit" value ="send">
</form>
</body>
</html>
Web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>helloworld2</display-name>
<servlet>
<servlet-name>myservlet</servlet-name>
<servlet-class>apress.helloworld.HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myservlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Servlet code:
package apress.helloworld;
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 HelloWorld extends HttpServlet{
protected void doGet(HttpServletRequest request, HttpServletResponse response)
{
//System.out.println("Get Method Called");
try { response.setContentType("text/html");
`enter code here` PrintWriter printwriter = response.getWriter();
printwriter.println("<h2>");
printwriter.println("Hello World");
printwriter.println("</h2>");
}
catch
(IOException ex)
{ ex.printStackTrace(); }
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
try { resp.setContentType("text/html");
PrintWriter printwriter = resp.getWriter();
printwriter.println("<h2>");
printwriter.println("Hello World");
printwriter.println("</h2>");
}
catch
(IOException ex)
{ ex.printStackTrace(); }
}
}
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Hello World</title>
</head>
<body>
<form method="post" action="hello">
<input type="submit" value ="send">
</form>
</body>
</html>
use Above code
in HTML form action="url-mapping" you have to mention url pattern of servlet not servlet name refer your web.xml

How include servlet output to jsp file

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);
}
}

Requested Resource is not available error [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
I'm trying to build a twitter search using jsp, servlet, Tomcat-6.0.43 and eclipse and getting HTTP Status 404 error. Can anyone please check where am I going wrong.
My Code:
first.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="ServletValues.java" method="get">
Enter Twitter Search Details : <input type="text" name="first"><br>
<input type="submit">
</form>
</body>
</html>
TwitterServlet.java:
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
public class TwitterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public TwitterServlet() {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String CONSUMER_KEY = "[data]";
String CONSUMER_KEY_SECRET = "[data]";
String AccessToken = "[data]";
String AccessTokenSecret = "[data]";
response.setContentType("text/html");
String input1 = request.getParameter("first");
try{
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECRET);
AccessToken oathAccessToken = new AccessToken(AccessToken, AccessTokenSecret);
twitter.setOAuthAccessToken(oathAccessToken);
List<Status> status = twitter.getUserTimeline(input1);
for (Status status2 : status)
{
System.out.println("---Tweet---"+status2.getText());
}}catch (TwitterException te){
System.out.println("Error occured "+te);
}
super.doPost(request, response);
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>
Twitter12</display-name>
<servlet>
<description>
</description>
<display-name>
TwitterServlet</display-name>
<servlet-name>TwitterServlet</servlet-name>
<servlet-class>
TwitterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TwitterServlet</servlet-name>
<url-pattern>/TwitterServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
Error: HTTP Status 404 - /Twitter12/ServletValues.java
type Status report
message /Twitter12/ServletValues.java
description The requested resource is not available.
In your jsp file form action, Replace
<form action="ServletValues.java" method="get">
With
<form action="TwitterServlet" method="get">
Since in your web.xml your servlet mapping pattern is TwitterServlet for the Servlet class that you intend to call.
Also in your servlet you are just printing to System.out while you should write into the reponse stream using
response.getOutputStream().write("---Tweet---"+status2.getText());
so that it shows up in the response
Change your form action to:​
<form action="/TwitterServlet" method="get">
your servlet url is /TwitterServlet as you have defined
<servlet-mapping>
<servlet-name>TwitterServlet</servlet-name>
<url-pattern>/TwitterServlet</url-pattern>
</servlet-mapping>

Show E-Mail content on .jsp page / GAE

I am writing an application with Google App Engine.
The app can receiver eMails now and I can see these in the console.
What I want is that the three variables (summary, addresses and text) are visible in the frontend (guestbook.jsp).
I tried to various options (see commented code) but none of them showed me the information in the frontend.
By now I only tried to pass one variable (summary).
Later on I want to store the information in a database.
Servlet:
package com.example.mail;
import java.io.IOException;
import java.util.Properties;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.*;
import javax.mail.Address;
public class MailHandlerServlet extends HttpServlet {
#Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
try{
MimeMessage message = new MimeMessage(session, req.getInputStream());
String summary = message.getSubject();
Address[] addresses = message.getFrom();
String text = message.getContent().toString();
System.out.println("Subject: " + summary);
System.out.println("Sender: " + addresses);
System.out.println("Text: " + text);
req.setAttribute("summary",summary);
req.getRequestDispatcher("/mail.jsp").forward(req, resp);
} catch (Exception e) {
e.printStackTrace();
}
}
}
mail.jsp
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# page import="java.util.List" %>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<html>
<head>
<link type="text/css" rel="stylesheet" href="/stylesheets/main.css"/>
</head>
<body>
Hello World!
<p>E-Mail Summary '${summary}'.</p>
</body>
</html>
Web.xml:
<servlet>
<servlet-name>mailhandler</servlet-name>
<servlet-class>com.example.mail.MailHandlerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>mailhandler</servlet-name>
<url-pattern>/_ah/mail/string#appid.appspotmail.com</url-pattern>
</servlet-mapping>
Would be nice if someone could help me.
You need to use request.setAttribute("summary", summary); to add summary as a request attribute, and since a redirect isnt server side, it's client side, the attributes are no longer shown, you'll need to use req.getRequestDispatcher("mail.jsp").forward(req, resp);

Categories

Resources