Websphere file not found error - java

I'm a beginner in Java.
I have developed a jsp page that accepts the username and password and then a java page is executed that validates against a hardcoded value.
The issue is that it runs fine on Tomcat. The webpage displays the message from the java page. But the same thing does not work on IBM webshpere. When I click on submit button, I get a file not found error.
Please help.
Here's the JSP 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>Login Example</title>
</head>
<body>
<form name="loginform" action="login" method="post">
<p>Enter User Name: <input type="text" name="getusername"><br>
Enter Password: <input name="getpassword" type="password"><br>
<input type="submit">
</form>
</body>
</html>
================
Here's the Java file content
package test.ae;
import java.io.IOException;
import javax.servlet.ServletConfig;
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.*;
/**
* Servlet implementation class Login
*/
#WebServlet(description = "Login Servlet", urlPatterns = { "/login" })
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
public Login()
{
super();
}
public void init(ServletConfig config) throws ServletException {}
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Service method of the servlet");
String username = "user";
String password = "root";
String un= request.getParameter("getusername");
String pw= request.getParameter("getpassword");
String msg = "";
if(un.equals(username) && pw.equals(password))
{
msg = "Hello " + un;
}
else
{
msg = "Login failure";
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<font size='6' color=red>" + msg + "</font>");
}
}
======================

What version of WebSphere server are you using? Does it support #WebServlet annotation (Java Servlet 3.0 (JSR 315), which is part of Java EE 6)
You may use url-pattern in web.xml instead:
http://docs.oracle.com/cd/E13222_01/wls/docs81/webapp/web_xml.html

Related

how i do when ihave this issue JSP Problem: HTTP 500 Internal Server Error Status when handling action?

I have searched the forums a lot for a solution to my problem but so far nothing. So I need your help!
Currently I am taking the Java EE course: "Develop websites with Java EE" on openclassrooms and arrived on JDBC I am blocked.
The principle consists of reading data in the database from the Java code and displaying them at the level of the JSP. But the display poses a problem at the JSP level. Thank you for your help! Here is my code for the JSP.
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>titre</title>
</head>
<body>
<h1>Bienvenue dans mon site</h1>
<ul>
<c:forEach var="utilisateur" items="${ utilisateurs }" >
<li><c:out value="${ utilisateurs.prenom }" /><c:out value="${ utilisateurs.nom }" /></li>
</c:forEach>
</ul>
</body>
</html>
import java.io.IOException;
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 sn.mballo.bdd.Personnes;
#WebServlet("/bonjour")
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
public Test() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Personnes tablePersonnes = new Personnes();
request.setAttribute("utilisateurs", tablePersonnes.recupererUtilisateurs());
this.getServletContext().getRequestDispatcher("/WEB-INF/bonjour.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

Load Data into JSP Page from MySQL without Form

I am trying to load data into JSP page from MySQL database using Eclipse and Tomcat 8 server. My .jsp file looks as follows:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# page import="java.util.ArrayList"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<jsp:forward page="/ProductDisplay" />
<table border="2">
<tr>
<td>Id</td>
<td>First Name</td>
<td>Last Name</td>
<td>Email</td>
<td>Phone Number</td>
</tr>
<c:forEach var="patients" items="${patients}">
<tr>
<td>${patients.getPatientId()}</td>
<td>${patients.getPatientfName()}</td>
<td>${patients.getPatientlName()}</td>
<td>${patients.getPatientEmail()}</td>
<td>${patients.getPatientPhone()}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
The .java servlet file:
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
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 ProductDisplay
*/
#WebServlet("/ProductDisplay")
public class ProductDisplay extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ProductDisplay() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
PatientsDao p = new PatientsDao();
ArrayList<Patient> patients = p.getPatients();
request.setAttribute("patients", patients);
request.getRequestDispatcher("/Patient.jsp").forward(request, response);
}
}
And the database connector class looks as follows:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class PatientsDao {
DBConnection mt = new DBConnection();
Connection myConn = mt.myConn;
private class DBConnection {
public Connection myConn;
public DBConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
myConn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/PatientsDB", "root", "");
} catch (Exception exc) {
exc.printStackTrace();
}
}
}
public ArrayList<Patient> getPatients() {
ArrayList<Patient> patients = new ArrayList<>();
try {
PreparedStatement pst =
myConn.prepareStatement("select * from Patients");
ResultSet r = pst.executeQuery();
while(r.next()) {
Patient p = new Patient();
p.setId(r.getInt("id"));
p.setfName(r.getString("fName"));
p.setlName(r.getString("lName"));
p.setEmail(r.getString("Email"));
p.setPhone(r.getString("Phone"));
patients.add(p);
}
}
catch (SQLException exc) {
System.out.println("An error occured. Error: " + exc.getMessage());
}
return patients;
}
}
Correct me if I'm wrong but I believe that upon running the Tomcat server the .java servlet class is invoked and information from the database is loaded into JSP page without any action needed. However, this does not happen in my case. Once I start Tomcat server and navigate to the Patient.jsp page the only thing that is displayed is the table header (which does not come from database). No data from MySQL database is displayed.
I know that this is not a MySQL problem as I can load all the data successfully if I add a form and use a button. Once the button is clicked and doGet method is invoked everything is loaded successfully.
My question is, how would I load the data automatically, without clicking a button or a link? I was doing research and apparently all info is supposed to load automatically. This, however, does not happen in my case. Am I missing something? Thank you in advance!
No, you mistake.
Servlet load first time when you call it(for examle go to Patient.jsp).
But when you go to Patient.jsp work only servlet Patient.jsp(jsp page convert to servlet class automatically), and you servlet /ProductDisplay dont work at all.
Your request attribute is empty when you call Patient.jsp beacause ProductDisplay don`t work.
You have three ways:
1) You should start with /ProductDisplay page
2) Or add index.jsp page and start with this page.
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<jsp:forward page="/ProductDisplay" />
</body>
</html>
3) And bad variant - add scriptlet to page Patient.jsp with code and start whith this page
PatientsDao p = new PatientsDao();
ArrayList<Patient> patients = p.getPatients();
request.setAttribute("patients", patients);
And remember never call servlets directly. Only through any servlet.
This is bad practice

How to pass Objects from servlets to JSP? [duplicate]

This question already has answers here:
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
(6 answers)
Closed 6 years ago.
I can pass Integer, String, Float, etc.. but when I am passing my defined object (Employee) the JSP is receiving it as null.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="com.rahul.model.bean.*"%>
<!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>Search Result</title>
</head>
<body>
<%
Employee record = (Employee) request.getAttribute("searchResult");
out.println(record);
%>
<table border="1">
<tr>
<th>Id</th>
<th>Name</th>
<th>Designation</th>
<th>Department</th>
<th>Salary</th>
</tr>
</table>
</body>
</html>
And My Controlleer doGet is:
protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
EmployeeDAO dao = new EmployeeDAOImpl();
Employee result = dao.search(request.getParameter("id"));
// PrintWriter pw=response.getWriter();
// pw.println(result);
ServletContext app = getServletContext();
app.setAttribute("searchResult", result);
System.out.println("Emp= "+result);
response.sendRedirect("./searchview.jsp");
}
Try this:
GreetingsServlet.java
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/greetings")
public class GreetingsServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String message = "Hello, World";
req.setAttribute("message", message);
RequestDispatcher dispatcher = req.getServletContext().getRequestDispatcher("/WEB-INF/jsp/greetings.jsp");
dispatcher.forward(req, resp);
}
}
greetings.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1><%= request.getAttribute("message") %></h1>
</body>
</html>
This cannot work with sendRedirect though as you're basically making a round-trip between the client and server, spanning over 2 requests, not one. The first request has your parameter, but since your client does not store it, it is lost when the redirection occurs. You should forward to your JSP unless what's done by the servlet should not be executed over and over again (like a database insertion). Look here if you really need to redirect.

Out.Print method not working?

Here is my code
LoginController.java
package mvc.demo.control;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mvc.demo.model.Authenticate;
public class LoginController extends HttpServlet {
private static final long SerialVersionUID=1L;
public LoginController()
{
super();
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String s1=req.getParameter("username");
String s2=req.getParameter("password");
RequestDispatcher rd=null;
Authenticate au=new Authenticate();
String result=au.authorise(s1, s2);
if(result.equals("success"))
{
rd=req.getRequestDispatcher("/success.jsp");
}
else
{
//This is the point where i try to print error message on jsp.
PrintWriter out = resp.getWriter( );
out.print("Sorry UserName or Password Error!");
rd=req.getRequestDispatcher("/login.jsp");
rd.include(req, resp);
}
rd.forward(req, resp);
}
}
login.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>
<title>Login Page</title>
</head>
<body>
<form method="post" action="LoginController" >
UserName: <input type="text" name="username"><BR><BR>
PassWord: <input type="password" name="password"><BR><BR>
<input type="submit" />
</form>
</body>
</html>
Please check the else block of loginController class where i am trying to print error message on my jsp file currently the "out.print" method is unable to reflect on my login.jsp file.
Kindly help me to sort this issue Thanks in advance.
You can set the error message in request attribute and can fetch it in JSP
String errorMsg = "UserName or Password is invalid !";
req.setAttribute("errorMsg", errorMsg);
req.getRequestDispatcher("/login.jsp").forward(req, res);
Now on your JSP
<h2>${errorMsg}</h2> // Print wherever you need it
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mvc.demo.model.Authenticate;
public class LoginController extends HttpServlet {
private static final long SerialVersionUID=1L;
public LoginController()
{
super();
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String s1=req.getParameter("username");
String s2=req.getParameter("password");
RequestDispatcher rd=null;
Authenticate au=new Authenticate();
String result=au.authorise(s1, s2);
if(result.equals("success"))
{
rd=req.getRequestDispatcher("/success.jsp");
//The error was with this line
rd.forward(req, resp);
}
else
{
PrintWriter out = resp.getWriter( );
out.print("Sorry UserName or Password Error!");
rd=req.getRequestDispatcher("/login.html");
rd.include(req, resp);
}
}
}
I can't see out.close() in your code. You must close the PrintWriter object in the end.
If u want to print the error message in Jsp and first Set the Error msg in request
req.setAttribute("msg","error msg configure here");
and now you can get the same in jsp by using EL Expression.
${msg}
or You can get it by using scripting language.
<%Object obj=request.getAttribute("msg");%>
Typecast the Obj into String and print by using this
<%=str%>
Note:- Recommended to use El expression.

Cannot set property 'innerHTML' of null. Issue with AJAX (java)

So I want to learn AJAX and I wanted to make identical app like the one in here
and I pretty much copied it but it doesn't work. I don't know why, I was trying to solve it on my own but can't find any solution.
My .js file is :
function ajaxAsyncRequest(reqURL) {
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", reqURL, true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
// How to get message
alert('It\'s K');
document.getElementById("message").innerHTML = xmlhttp.responseText;
alert(xmlhttp.responseText);
} else {
alert('Something is wrong !');
}
}
};
xmlhttp.send(null);
}
The index .jsp is:
<%# 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>
<script type="text/javascript" src="javascript.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<input type="button" value="Show Server Time" onclick='ajaxAsyncRequest("getTime")' />
</body>
</html>
and my servlet code is:
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDate;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/getTime")
public class GetTimeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public GetTimeServlet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void doGet (HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
PrintWriter out = response.getWriter();
LocalDate currentTime= LocalDate.now();
String message = "Currently time is "+currentTime.toString();
out.write(message);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
But when I click on the button I get the message which I pointed in the title in the line document.getElementById("message").innerHTML = xmlhttp.responseText;
in .js file.
I'm running it through http://localhost:8080/HelloAjax/, so no local, It loads later than the page, so I have no idea what can it be.
document.getElementById("message") is null because there is no element with id 'message' in the DOM. Try changing your HTML:
<body>
<div id="message"></div>
<input type="button" value="Show Server Time" onclick='ajaxAsyncRequest("getTime")' />
</body>

Categories