Cannot use forward method in java servlet - java

I just started learning servlet and got the following problem.
I need to use forward method in my servlet and show the result in other frame.
But nothing is shown. When I use include method, it's shown me the result.
How can I shown my result with forward method?
frame.jsp
<%# page import="StudyC.C18_HelloWeb"%>
<%# page language="java" contentType="text/html; charset=Windows-31J"
pageEncoding="Windows-31J"%>
<html>
<head>
<title>検索画面</title>
</head>
<FRAMESET ROWS ="20%,80%" >
<FRAME SRC ="C18_HelloINPUT.jsp" NORESIZE scrolling = yes>
<FRAME SRC ="C18_HelloOUTPUT.jsp" NORESIZE scrolling = no name = frameOutput>
</FRAMESET>
C18_HelloINPUT.jsp
<%# page language="java" contentType="text/html; charset=Windows-31J"
pageEncoding="Windows-31J"%>
<%# page import = "javax.servlet.RequestDispatcher" %>
<html>
<script>
function validateForm() {
var x = document.forms['myForm']['dataName'].value;
if (x == null || x.match(/^\s*$/)) {
alert('空です');
return false;
}
}
</script>
<style>
h1 {text-align:center;}
</style>
<h1>入力画面</h1><br>
<form name='myForm' action="C18_HelloWeb" method="get"
onsubmit='return validateForm()'target='frameOutput' >
<input type='text' name='dataName'>
<input type='submit' value='クエリ送信'>
</form>
C18_HelloOUTPUT.jsp
<%# page language="java" contentType="text/html; charset=Windows-31J"
pageEncoding="Windows-31J"%>
<html>
<style>
h1 {text-align:center;}
</style>
<h1>出力画面</h1>
</html>
C18_HelloWeb.java
package StudyC;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class C18_HelloWeb extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public void init(ServletConfig config)
throws ServletException{
}
protected void doGet (HttpServletRequest request, HttpServletResponse respone)
throws ServletException, IOException {
respone.setContentType("text/html; charset=Windows-31J");
request.setCharacterEncoding("Windows-31J");
HttpSession session = request.getSession(true);
PrintWriter out = respone.getWriter();
RequestDispatcher rd = request.getRequestDispatcher("C18_HelloOUTPUT.jsp");
rd.forward(request,respone);
String firstName = request.getParameter("dataName");
#SuppressWarnings("unchecked")
ArrayList<String> dataList = (ArrayList<String>)session.getAttribute("PreviousItems");
if( dataList == null ) {
dataList = new ArrayList<String>();
session.setAttribute("PreviousItems", dataList);
}
dataList.add(firstName);
int i = 0;
do{
out.print(HTMLFilter.filter(dataList.get(i)) + "<br>");
i++;
} while(i<dataList.size());
}
protected void doPost(HttpServletRequest request, HttpServletResponse respone)
throws IOException, ServletException
{
doGet(request, respone);
}
}
I think there is a problem in the C18_HelloINPUT.jsp and C18_HelloWeb.java. Thank you!

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

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>

Websphere file not found error

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

Making link go to servlet to redirect to another page

SO first off let me begin by saying that my servlet loads the option lists in a form i have just fine. The problem is when i start from the index.jsp like i want, the lists dont load. So basically, i want to click a link on the index.jsp to take me to the servlet to then redirect me to the correct page based on the link clicked. Maybe I have been looking at this too long and just need fresh eyes but I cant get why it wont work.
I have included my Index.jsp and servlet
Index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# 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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form method="get" action="customerServlet">
Add Customer
<br/>
Add Pet
</form>
</body>
</html>
Servlet
package edu.witc.Assignment03.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//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 edu.witc.Assignment03.model.Customer;
import edu.witc.Assignment03.model.Phone;
import edu.witc.Assignment03.model.States;
#WebServlet(description = "servlet to get act as controller between form and models", urlPatterns = { "/customerServlet","/addCustomer","/addPet" })
public class CustomerServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public CustomerServlet() {
super();
}
private void processRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession session = request.getSession();
Phone phone = new Phone();
States state = new States();
Collection<Phone> phones = phone.getPhoneCollection();
Collection<States> states = state.getStateCollection();
session.setAttribute("phones", phones);
session.setAttribute("states", states);
request.getRequestDispatcher("/customerManagement.jsp").forward(request, response);
//}
}
private List<edu.witc.Assignment03.model.Customer> customers = new ArrayList<Customer>();
private void addCustomer(HttpServletResponse response, HttpServletRequest request)//redirect to index
throws IOException, ServletException {
String url = "/customerManagement.jsp";
processRequest(request, response);
request.getRequestDispatcher(url).forward(request,response);
}
private void addPet(HttpServletResponse response, HttpServletRequest request)//redirect to index
throws IOException, ServletException {
String url = "/pets.jsp";
request.getRequestDispatcher(url).forward(request,response);
}
private Customer getCustomer(int customerId) {
for (Customer customer : customers) {
if (customer.getCustomerId() == customerId) {
return customer;
}
}
return null;
}
private void sendEditCustomerForm(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
String url = "/customerManagement.jsp";
request.setAttribute("customers", customers);
request.getRequestDispatcher(url).forward(request,response);
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String uri = request.getRequestURI();
if (uri.endsWith("/addCustomer")) {
addCustomer(response, request);
} else if (uri.endsWith("/addPet")) {
addPet(response, request);
}
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
// update customer
int customerId = 0;
try {
customerId =
Integer.parseInt(request.getParameter("id"));
} catch (NumberFormatException e) {
}
Customer customer = getCustomer(customerId);
if (customer != null) {
customer.setFirstName(request.getParameter("firstName"));
customer.setLastName(request.getParameter("lastName"));
customer.setEmail(request.getParameter("email"));
customer.setPhone(request.getParameter("phone"));
customer.setAddress(request.getParameter("address"));
customer.setCity(request.getParameter("city"));
customer.setZip(request.getParameter("zip"));
}
}
}
It would be easier to use one parameter and check the value than to manually parse the URL:
Add Customer
<br/>Add Pet
In your servlet:
String action = request.getParameter("action");
if("addCustomer".equals(action)) { ... }
else if("addPet".equals(action)) { ... }
if you are using "forms", this could be the solution to send params to servlet.
<form action="ServletName" method="POST">
<input type="text" name="paramName">
<input type="submit" value="Add">
</form>
In Servlet:
String costumerName = request.getParameter("paramName");
If you just use a link like href, you should send the param like:
<a href="ServletName?ID=12345">
In servlet, same.
String costumerName = request.getParameter("ID");

Categories