Java Servlet looping when forwarded to jsp - java

I'm trying to convert a Java class to be displayed on a web page. Using the top answer here as a guideline. The Java does what it's supposed to if I print everything out with System.out. When trying to forward to a jsp page, it loops (re-instantiates?), and doesn't stop (have to manually kill the process).
Connector.java
public class Connector extends HttpServlet {
private static URL url = https://my.server.com/WEB-INF/ws/service.php?wsdl");;
private static final String USERNAME = "JoeBoB";
private static final String PASSWORD = "1337pass";
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//login to my.server.com
try {
authToken = serverAPI.login(USERNAME, PASSWORD);
System.out.println("Logged into server with Token: " + authToken);
//this shows up in console over and over again, until manually killed
}
catch (Exception ex) {
ex.printStackTrace();
}
request.setAttribute("message","bacon");
request.getRequestDispatcher("/WEB-INF/draw.jsp").forward(request, response);
//line above appears to be the one that re-inits the class.
//commenting this out stops the looping
//but also prevents the data from showing on the webpage
serverAPI.logout(authToken);
WEB-INF/draw.jsp
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>This is my drawn page</title>
</head>
<body>
${message}
</body>
</html>
WEB-INF/web.xml
<web-app>
<display-name>Connector</display-name>
<servlet>
<servlet-name>Connector</servlet-name>
<servlet-class>com.company.package.Connector</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Connector</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
I have a feeling it's somewhat simple (something I forgot to configure, or misconfigured), but for the life of me can't figure out what.

By mapping /* to your servlet you are overriding the default handler for JSP requests. You need to use a more specific pattern, using a file extension or subdirectory.

Related

Getting more information about an object when clicking on a text in html using MVC

So I'm a making a small web app to get information about games, I have made a searchBar that request the search to an API and then I get the first 10 games with the most similar title to the search. But I only show the title.
This is an example of a search
The games have a lot of attributes, one of them is the ID, and it allows me to get all the info of a game using a controller.
Right now the app works like this:
1: You search the title of a game
2. A controller gives me a List of IDs and with the ids I get the rest of the info about the games, but I only show the titles.
Now, what I want to do:
3.When you click on a title you use a controller, and from the ID it request (again, I'm not sure if I can use the previous games objects) all the info from that game and Shows it.
The controllers works fine, but I'm having problems with the HTML.
This is the controller for the search:
...
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String query = request.getParameter("searchQuery");
RequestDispatcher rd = null;
log.log(Level.FINE, "Searching for games that contain " + query);
GameResource game = new GameResource();
GameSearch[] gameResults = null;
gameResults = game.getGameSearch(query);
//System.out.println(Arrays.toString(gameResults));
List<Game> listaBusqueda = new ArrayList<Game>();
if (gameResults.length!=0){
rd = request.getRequestDispatcher("/success.jsp");
for (GameSearch g : gameResults) {
listaBusqueda.add(game.getGame(g.getId().toString()));
}
request.setAttribute("games", listaBusqueda);
} else {
log.log(Level.SEVERE, "Game object: " + gameResults);
rd = request.getRequestDispatcher("/error.jsp");
}
rd.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
...
This is the controllers that gives me a game using an ID
...
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String gameId = request.getParameter("id");
GameResource resource = new GameResource();
RequestDispatcher rd = null;
log.log(Level.FINE, "Retrieving game");
Game game = resource.getGame(gameId);
if(game!=null) {
rd = request.getRequestDispatcher("/success.jsp");
request.setAttribute("Game", game);
request.setAttribute("Item", "gameID");
} else {
log.log(Level.SEVERE, "Cannot retrieve game: ");
rd = request.getRequestDispatcher("/error.jsp");
rd.forward(request, response);
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
Both of them works, in the last one the objects are created correctly and the ID is obtained.
Now, this is the html for success.jsp, and this is where the problem is:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Search results</title>
</head>
<body>
<fieldset id="IGDB">
<legend>
IGDB search for
<c:out value="${param.searchQuery}" />
</legend>
<c:forEach items="${requestScope.games}" var="game">
<article name="gameArticle" id="gameArticle"></article>
<a href="GameIdController?id=${game.id}"><c:out value="${game.name}"
/></a>
<br />
</c:forEach>
</fieldset>
<c:if test="${requestScope.Item=='gameID' }">
<c:forEach items="${requestScope.Game}" var="game">
<article name="gameArticle" id="gameArticle"></article>
<c:out value="${game.name}" />
<br />
</c:forEach>
$game = ${requestScope.Game}
<c:out value="${game.name}"/>
</c:if>
<article name = "gameByIDArticle" id = "gameByIDArticle">
</article>
</body>
</html>
When I click in a title, I get redirected to a blank webpage (http://localhost:8090/GameIdController?id=IdOfTheGame),as you can see the id is included in the URL, but it's completely blank and it should include the title again as is stated in my code.
I will also include my 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"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<servlet>
<description></description>
<display-name>GameSearchController</display-name>
<servlet-name>GameSearchController</servlet-name>
<servlet-class>aiss.controller.GameSearchController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GameSearchController</servlet-name>
<url-pattern>/GameSearchController</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>GamePopularityController</display-name>
<servlet-name>GamePopularityController</servlet-name>
<servlet-class>aiss.controller.GamePopularityController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GamePopularityController</servlet-name>
<url-pattern>/GamePopularityController</url-pattern>
</servlet-mapping>
<context-param>
<param-name>resteasy.servlet.mapping.prefix</param-name>
<param-value>/api</param-value>
</context-param>
<servlet>
<servlet-name>Resteasy</servlet-name>
<servlet-
class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
</servlet-
class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>aiss.api.GameApplication</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Resteasy</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/error.jsp</location>
</error-page>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>GameIdController</display-name>
<servlet-name>GameIdController</servlet-name>
<servlet-class>aiss.controller.GameIdController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GameIdController</servlet-name>
<url-pattern>/GameIdController</url-pattern>
</servlet-mapping>
</web-app>
Okay i think i understand why you are seeing a blank page. Everything is working as expected, the problem seems to be with this:
if(game!=null) {
rd = request.getRequestDispatcher("/success.jsp");
request.setAttribute("Game", game);
request.setAttribute("Item", "gameID");
} else {
log.log(Level.SEVERE, "Cannot retrieve game: ");
rd = request.getRequestDispatcher("/error.jsp");
rd.forward(request, response);
}
The reason why you are seeing a blank page is because your game variable is not null. And you don't have a forward statement in the first part of that if else block.
if(game!=null) {
rd = request.getRequestDispatcher("/success.jsp");
request.setAttribute("Game", game);
request.setAttribute("Item", "gameID");
rd.forward(request, response); // missing this!
} else {
log.log(Level.SEVERE, "Cannot retrieve game: ");
rd = request.getRequestDispatcher("/error.jsp");
rd.forward(request, response);
}
EDIT: In response to your other problem from the comment, i think the forEach is having problems because of this:
<c:forEach items="${requestScope.Game}" var="game">
change it to this:
<c:forEach items="${Game}" var="game">

how to send data from servlet to Jsp using request dispatcher

servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
System.out.println("Received Value: " + request.getRequestURL());
response.getWriter().append("Decoded string: ").append(
Utils.getDataFromFeedbackLink(request.getPathInfo().substring(1, request.getPathInfo().length())));
String decodeValue = Utils
.getDataFromFeedbackLink(request.getPathInfo().substring(1, request.getPathInfo().length()));
request.setAttribute("finalData", decodeValue);
RequestDispatcher rd = request.getRequestDispatcher(decodeValue);
rd.forward(request, response);
}
jsp:
<body>
Hello World ::::
<%=request.getAttribute("finalData")%>
</body>
web.xml
<servlet>
<servlet-name>SubmitFeedbackServlet</servlet-name>
<description></description>
<servlet-class>com.techjini.tfs.servlets.SubmitFeedbackServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SubmitFeedbackServlet</servlet-name>
<url-pattern>/submitfeedback/*</url-pattern>
</servlet-mapping>
i am getting value but when i try to send value from Servlet to Jsp then each time same servlet loaded so am unable to get value inside jsp please suggest me how to get value from servlet to jsp using request dispatcher or some thing i did wrong please point me where am doing mistake .
If you store some data in request attribute in will be seen on forwarded page. Just set req.setAttribute("key", "value") and it will be visible on destination page via ${"key"}
in the line "RequestDispatcher rd = request.getRequestDispatcher(decodeValue);"
the decodeValue should contain the name of the jsp file . can you check that by printing the value of decodeValue on console.

How to call servlet when button click [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 7 years ago.
As new to the jsp and servlet and only having basic idea of it and still learning .I want to know how can we call the servlet class on that button click.I m using button in place of submit button
Here is the page content:-
<%# 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>JSON DATA EXAMPLE</title>
<script type="text/javascript">
function callservlet() {
var servletname=document.getdata.fetchdata.value;
if(servletname== "")
{
alert("NO value..");
return false;
}
else
{
alert("value"+servletname);
document.location.href="JsonServlet";
return false;
}
}
</script>
</head>
<body>
<div>
<form name="getdata" action="JsonServlet" method="post">
<input type="button" name="fetchdata" value="CLick to get data" onclick="return callservlet();">
</form>
</div>
</body>
</html>
and here the servlet class content
public class JsonServlet extends HttpServlet
{
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
JsonParser parser=new JsonParser();
if(req.getParameter("fetchdata")!=null)
{
System.out.println("Button Clicked");
}
else
{
System.out.println("Button not clicked");
}
}
}
and here is the web.xml part
<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/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>JsonDataExample</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Jsonfetch</servlet-name>
<servlet-class>com.text.JsonServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Jsonfetch</servlet-name>
<url-pattern>/JsonServlet</url-pattern>
</servlet-mapping>
</web-app>
so is there any part i m write the method wrong because its gives me 404 error resource not found
so i want the concept that on that button click how can i call my servlet class.Thanks for any reply
try this :
function callservlet() {
var servletname=document.getdata.fetchdata.value;
if(servletname== "")
{
alert("NO value..");
return false;
}
else
{
alert("value"+servletname);
document.forms[0].action = "JsonServlet"
document.forms[0].submit();
}
}
You can't set the location to a servlet. Instead, what you should do to hit the servlet is to submit your form:
function callservlet() {
//do your processing.
document.getElementsByName('getdata')[0].submit();
}
Or you can simply use a submit type button.
You just need to submit your form - (Instead of document.location.href="JsonServlet";)
document.getElementByName('getdata').submit();
I want to know how can we call the servlet class on that button
click.I m using button in place of submit button
You don't need js here, you can do it with the existing form itself. Replace the input tag as follows:
<input type="submit" name="fetchdata" value="CLick to get data" />
If you still want to use js, try below script instead:
function callservlet() {
document.forms.getdata.submit();
}

How to send Data to JSP from a Servlet?

I am working on a project which has just one page(index.jsp) and initial load of the page an Ajax request is being sent and JSON data is retrieved. The AJAX call sent to my Servlet and Servlet returns JSON data,and i have only one Servlet. I am trying to send the some data to my JSP page to populate, so This is how i am writing my Servlet......
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out =response.getWriter();
String queryString = request.getQueryString();
ResourceBundle props = ResourceBundle.getBundle("jira");
XmlMerge xmlMerge = new XmlMerge();
String mergeFiles=xmlMerge.getJsonData();
out.println(mergeFiles);
out.close();
//Debug Statement
System.out.println(xmlMerge.getTodo());
// *THIS IS THE WAY I AM SEND DATA TO JSP PAGE.*
request.setAttribute("todo", xmlMerge.getTodo());
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
and in my index.jsp
<%=(String)request.getAttribute("todo")%>
I am trying to output the result.
What is going wrong?
I just performed this change and it displays what you need:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
request.setAttribute("todo", "10");
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
This is the generated index.jsp:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%=(String)request.getAttribute("todo")%>
</body>
</html>
There might be something wrong with your getTodo().. I don't know how it works but maybe this could help:
...
XmlMerge xmlMerge = new XmlMerge();
String todo = xmlMerge.getTodo();
...
request.setAttribute("todo", todo);
UPDATE:
PrintWriter out = response.getWriter();
out.println(...);
out.close();
This is your problem... you are getting the resource and close it. This might cause an illegal state exception issue..
You "don't need" the dispatcher to the index.jsp.. if you don't use a dispatcher but you want to render your page you can use something like this:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.getWriter().write("<html><body>"+getSomething()+"</body></html>");
}
Why isn't index.jsp a default call? because there might not even exists an index.jsp file and it may be the call for another servlet. You can have a configuration that maps the call to index.jsp to a servlet.
http://tutorials.jenkov.com/java-servlets/web-xml.html
I still don't know what is the purpose of using out.println but if you wanted it to be displayed in the jsp you can send it as argument as the "todo":
request.setAttribute("mergeFiles", mergeFiles);
And then print it in the jsp as the "todo".

Executing MySQL Commands from a Java Servlet

I'm trying to get my servlet to output the results of SQL commands entered by the user. Right now, the servlet correctly detects when a command does not include "SELECT", "INSERT", or "DELETE", and outputs an error message. When the command is valid, nothing is outputted. I know this means my problem is likely occurring either where I am trying to connect to the database, or where I am trying to print output to "out".
databaseServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
#SuppressWarnings("serial")
public class databaseServlet extends HttpServlet {
private Connection conn;
private Statement statement;
public void init(ServletConfig config) throws ServletException {
try {
Class.forName(config.getInitParameter("databaseDriver"));
conn = DriverManager.getConnection(
config.getInitParameter("databaseName"),
config.getInitParameter("username"),
config.getInitParameter("password"));
statement = conn.createStatement();
}
catch (Exception e) {
e.printStackTrace();
}
}
protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<xml version = \"1.0\"?>");
out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD " +
"XHTML 1.0 Strict//EN\" \"http://www.w3.org" +
"/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
out.println("<html xmlns = \"http://www.w3.org/1999/xhtml\">");
out.println("<head>");
out.println("<title>MySQL Servlet</title>");
out.println("<style type='text/css'>");
out.println("body{background-color: blue}");
out.println("</style>");
out.println("</head>");
out.println("<body>");
String query = request.getParameter("query");
if (query.toLowerCase().contains("select")) {
//SELECT Queries
try {
ResultSet resultSet = statement.executeQuery(query);
ResultSetMetaData metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
for(int i = 1; i<= numberOfColumns; i++){
out.printf("%20s\t", metaData.getColumnName(i));
}
out.println();
while (resultSet.next()){
for (int i = 1; i <= numberOfColumns; i++){
out.printf("%20s\t", resultSet.getObject(i));
}
out.println();
}
}
catch (Exception f) {
f.printStackTrace();
}
}
else if (query.toLowerCase().contains("delete") || query.toLowerCase().contains("insert")) {
//DELETE and INSERT commands
try {
conn.prepareStatement(query).executeUpdate(query);
out.println("\t\t Database has been updated!");
}
catch (Exception l){
l.printStackTrace();
}
}
else {
//Not a valid response
out.println("\t\t Not a valid command or query!");
}
out.println("</body>");
out.println("</html>");
out.close();
}
}
dbServlet.jsp
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- dbServlet.html -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>MySQL Servlet</title>
<style type="text/css">
body{background-color: green;}
</style>
</head>
<body>
<h1>Hello World!</h1>
<h2>This is the MySQL Servlet</h2>
<form action = "/database/database" method = "get">
<p>
<label>Enter your query and click the button to invoke a MySQL Servlet
<input type = "text" name = "query" />
<input type = "submit" value = "Run MySQL Servlet" />
</label>
</p>
</form>
</body>
</html>
I thought another potential failure point could be my path to the database file, which is initialized in my web.xml file. An example I found online included the port, but I'm wondering if I should remove the port number. Does anyone know the default port to use for MySQL?
This is the specific line I'm talking about from the xml file below:
jdbc:mysql://localhost:3309/project4
web.xml
<web-app 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" version="2.4">
<!-- General description of the web application -->
<display-name>
MySQL Servlet
</display-name>
<description>
This web application allows the user to connect to a database, sumbit queries, and make changes.
</description>
<!-- Servlet definitions -->
<servlet>
<servlet-name>database</servlet-name>
<description>
A servlet that handles SQL commands submitted by the user.
</description>
<servlet-class>
databaseServlet
</servlet-class>
<init-param>
<param-name>databaseDriver</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</init-param>
<init-param>
<param-name>databaseName</param-name>
<param-value>jdbc:mysql://localhost:3309/project4</param-value>
</init-param>
<init-param>
<param-name>username</param-name>
<param-value>root</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>pass</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>database</servlet-name>
<url-pattern>/database</url-pattern>
</servlet-mapping>
</web-app>
I was using port 3309, and needed to use port 3306.
PROBLEM
jdbc:mysql://localhost:3309/project4
SOLUTION
jdbc:mysql://localhost:3306/project4

Categories

Resources