Problem with jsp/servlet page - java

I want to create a simple JSP page. I have an EJB, in this there is a session bean.
I have a JSP page and a Servlet, but I have a strange situation.
When I click execute on my page, this turns in a white page and don't give me the result.
I post here my code, can you help me please.
Servlet:
package web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import javax.naming.*;
import javax.servlet.*;
import javax.servlet.*;
import javax.servlet.http.*;
import ejb.calc;
/**
* Servlet implementation class calcServlet
*/
public class calcServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public calcServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session=request.getSession(true);
RequestDispatcher rd=this.getServletContext().getRequestDispatcher("/index.jsp");
float a=Float.parseFloat(request.getParameter("n1"));
float b=Float.parseFloat(request.getParameter("n2"));
char oper=request.getParameter("oper").charAt(0);
float result=0;
try {
Context ctx=new InitialContext();
// call the calcImpl class of the SimpleCalculator EJB with the mappedName
calc cl=(calc) ctx.lookup("Firstcalc");
switch(oper){
case '+': result=cl.sum(a, b); break;
case '-': result =cl.minus(a, b); break;
case '*': result =cl.mult(a, b); break;
case '/': result =cl.div(a, b); break;
}
session.setAttribute("result",result);
request.setAttribute("a", a);
request.setAttribute("b", b);
}
catch(NamingException e)
{session.setAttribute("erreur: ",e.getMessage());
}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
}
}
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>
<h2> <b> Hello World To The Simple Calculator </b> </h2> <% float a=2,b=1; if (request.getAttribute("a")!=null) a=Float.parseFloat(request.getAttribute("a").toString()); if( request.getAttribute("b")!=null) b=Float.parseFloat(request.getAttribute("b").toString()); %> <form method="post" action="calcServlet"> <b>Number 1:</b><input type='text' name='n1' value="<%=a%>" /> <br/>
<b>Number 2:</b><input type='text' name='n2' value="<%=b%>" /> <br/>
<u><b>Options:</b></u> <br/>
<ul>
<li><b>+</b><input type='radio' name="oper" value='+' checked /></li>
<li><b> -</b><input type='radio' name="oper" value='-' /></li>
<li><b>*</b><input type='radio' name="oper" value='*' /></li>
<li> <b>/</b><input type='radio' name="oper" value='/' /></li> </ul>
<b>-------------------------------------------</b> <br/>
<input type="submit" value="Executer" /> </form>
<font color='blue'><b>Result is: </b> <%=session.getAttribute("result")%> </font> <br/> <font color='red' >Error: <%=session.getAttribute("error")%></font>
</body>
</html>

A JSP will blank out when you use old fashioned scriptlets (those <% %> things) and one of such a scriptlet has thrown an exception while the response has already been committed. It's too late then to display the error page. The browser ends up with a halfbaked HTML page (the HTML generated by JSP is incomplete and the browser will usually go blank). You should read the server logs for the exception and fix the code accordingly.
Unrelated to the actual problem, your approach is pretty clumsy. You don't need scriptlets at all. Just use EL (those ${} things). It has instant access to request parameters. E.g.
<input type="text" name="n1" value="${param.n1}" />
(for extra course points: use JSTL fn:escapeXml() to prevent XSS)
You don't even need to duplicate them as request attributes in the servlet. You should also not store the result as session attribute (it would be shared among all browser windows/tabs in the same session, you don't want to have this for a request based variable). Store it as request attribute
request.setAttribute("result", result);
and access it by EL as follows, it has instant access to page/request/session/application scoped attributes by just its name:
<b>Result is: </b> ${result}
Related questions:
Simple calculator in JSP/Servlet (with optional Ajax)
How to avoid Java code in JSP files

Related

How do I upload JSP file content to textarea

I want to edit an jsp file from textarea in browser. So i need to upload jsp content to textarea.
For example i have a readMe.jsp file like that:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<h1>Read Me</h1>
<p> This is read me content</p>
I want this edit like that:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<h1>Read Me</h1>
<p> This is read me content</p>
<hr>
<h2>Read Me Second Head</h2>
<p>This is read me content 2</p>
The way I think to be able to do this in the browser is to upload the jsp content to textarea and edit it from there. Does anyone know how I can do this?
If I have a way to edit a jsp file differently from the browser, it can also be.
Thanks.
This is just an example how a JSP page can be edited from a browser.
webapp/readme.jsp is a page to edit.
<%# page contentType="text/html;charset=UTF-8" %>
<html>
<head>
<title>Read Me</title>
</head>
<body>
<h1>Read Me</h1>
<p> This is read me content</p>
<p>Edit this page</p>
</body>
</html>
webapp/edit/readme.jsp contains a form within that a content of a readme.jsp page can be edit.
<%# page contentType="text/html;charset=UTF-8" %>
<html>
<head>
<title>Edit | Read Me</title>
</head>
<body>
<h1>'Read Me' edit page</h1>
<form method="post" action="${pageContext.request.contextPath}/edit/readme">
<label>
<textarea name="newContent" cols="96" rows="16">${content}</textarea>
</label>
<br><br>
<button type="submit">Save</button>
</form>
</body>
</html>
EditReadMe.java is a servlet.
The method doGet is triggered by the Edit this page link from the webapp/readme.jsp. It read content from the webapp/readme.jsp file and passes it to the webapp/edit/readme.jsp.
The method doPost is responsible for working with the form from the webapp/edit/readme.jsp and updating content for the webapp/readme.jsp file.
package com.example.editjsp;
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.nio.file.Files;
import java.nio.file.Path;
#WebServlet(name = "readMeEditor", value = "/edit/readme")
public class EditReadMe extends HttpServlet {
private static final String RESOURCE_PATH = "/readme.jsp";
private Path pathToFile;
#Override
public void init() {
pathToFile = Path.of(getServletContext().getRealPath(RESOURCE_PATH));
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String contentToEdit = Files.readString(pathToFile);
req.setAttribute("content", contentToEdit);
req.getRequestDispatcher("/edit/readme.jsp").forward(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
Files.writeString(pathToFile, req.getParameter("newContent"));
resp.sendRedirect(req.getContextPath() + RESOURCE_PATH);
}
}

Show session history

I've created a small mortg. calc. and it's working correctly, however i would like to have let's say three last calculations shown on the right side and the ability to remove (clear) them (like a small history log or similar). Whatever I try previous results get deleted. Quite new to servlets and sessions.
.jsp
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!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>
<body>
<div style="width:100%;">
<div style="float:left; width:20%;">
<form id="mortgage" action="mocalc" " method="post">
<p>
Principal:
<input name="principal">
Interest rate (%):
<input name="interest_rate">
Monthly payment:
<input name="monthly_payment">
<input name="calculate" type="submit" value="Calculate" />
</form>
<form id="clear" action="index.jsp" method="get"/>
<input name="clear" type="submit" value="CE"/></form>
</p>
</div>
<div style="float:right; width:80%; ">
<p>
<table>
<tr><td>Principal:</td>
<td align="right">${pr}</td>
<tr><td>Interest Rate:</td>
<td align="right">${ir}</td>
<tr><td>Monthly Payment:</td>
<td align="right">${mp}</td>
</tr></table>
<p>
It will take ${y} years and ${m} months to payoff the loan
<p>
Total interest to be paid: $${i}
</div>
</div>
</body>
</html>
.java
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
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;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class MoCalc
*/
#WebServlet("/mocalc")
public class MoCalc extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public MoCalc() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Float pr=Float.valueOf(request.getParameter("principal"));
Float ir = Float.valueOf(request.getParameter("interest_rate"));
Float mp = Float.valueOf(request.getParameter("monthly_payment"));
String inter=null, pri=null, ira,mpa;
DecimalFormat format = new DecimalFormat("#,##0.##");
//Payoff time in months calculation
double months=(Math.log10(mp)-Math.log10(mp-pr*(ir/100)/12))/(Math.log10(1+(ir/100)/12));
int a = (int) (months + 0.5);
Integer years=a/12;
Integer month=a%12;
//Total interest calculation
double interest=mp*months-pr;
//Format values
inter=format.format(interest);
pri="$"+format.format(pr);
ira = format.format(ir)+"%";
mpa="$"+format.format(mp);
HttpSession session=request.getSession();
session.setAttribute("y",years);
session.setAttribute("m",month);
session.setAttribute("i", inter);
session.setAttribute("pr", pri);
session.setAttribute("mp", mpa);
session.setAttribute("ir", ira);
RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
dispatcher.forward(request, response); }
}

J2ee The requested resource is unavailable

Hello I know That this question has been asked before But unfortuanetly I didn t find among the answers proposed the one suitable for me
I m still new with J2ee lookin' forward for ur help
This is my code
login.jsp
<!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>Login page</title>
</head>
<body>
<form action="" method="post"/>
<br> UserId: <input type="text" name="userId"/>
<br> password<input type="password" name="password"/>
<br><input type="submit"/>
</form>
</body>
</html>
LoginServlet.java
package org.islem.login;
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 org.islem.login.service.LoginService;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String userId,password;
userId= request.getParameter("userId");
System.out.println(userId);
password= request.getParameter("password");
LoginService loginService= new LoginService();
boolean result= loginService.authenticate(userId, password);
if (result)
{
response.sendRedirect("home.jsp");
return;
}
else
{
response.sendRedirect("login.jsp");
return;
}
}
}
LoginService.java
package org.islem.login.service;
public class LoginService {
public boolean authenticate (String userId,String password)
{
if (password ==null || password.trim() =="") {
return false;
}
else return true;
}
}
Your form action is empty, you should fill it your servlet name in your case it should be like:
<form action="LoginServlet" method="post"/>
I assume you already define your servlet name at your web.xml
You need to specify some controller name within the action:
<form action="LoginServlet " method="post"/>
<br> UserId: <input type="text" name="userId"/>
<br> password<input type="password" name="password"/>
<br> <input type="submit"/>
</form>
Remember: This action specifies where the data submitted by the form will be received.

HTTP Status 404. description The requested resource is not available [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've got a page here. When I click the submit button, I get the 404 page saying:
HTTP Status 404 - /Email/EmailGet
type Status report
message /Email/EmailGet
description The requested resource is not available.
Apache Tomcat/7.0.47
Code:
<%# 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="EmailGet" method="GET">
Email: <input type="text" name="email"> <br> Password: <input
type="password" name="password"> <br> <input
type="submit" value="Submit">
</form>
</body>
</html>
Here's the EmailGet code:
package email;
import java.io.IOException;
import javax.mail.Session;
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;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class Controller
*/
#WebServlet("/EmailGet")
public class EmailGet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public EmailGet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Gets the entered email and password
String username = request.getParameter("email");
String password = request.getParameter("password");
//Creates the session and sets the session attributes
HttpSession session = request.getSession();
session.setAttribute("username", username);
session.setAttribute("password", password);
RequestDispatcher dispatcher;
//Calls the setCredentials method to check if entered credentials are valid
boolean result = SendSMTPMail.setCredentials(username, password);
//if valid, forwards to send page
if (result == true) {
dispatcher = request.getRequestDispatcher("send.jsp");
dispatcher.forward(request, response);
}
//if not valid, forwards to index page with error message displayed
else {
dispatcher = request.getRequestDispatcher("indexerror.jsp");
dispatcher.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
}
}
Any ideas? It used to forward the page fine, but seems not to be working now.
Each jsp page runs fine individually, it's just the forwarding that isn't working.
It seems. . . that the requested page does not exist. I don't know the names of you files, so i can only guess that you have a typo somewhere, try to check your url bar and check if this is really the url you wanted.

How do JSP's and Servlets interact with each other

I am creating a Java Web Application on Eclipse and am unsure exactly how you can link jsp pages with Servlets. Example if your jsp page displays forms for the user to enter their First Name and age and then once they click submit, re-directing to the Servlet to handle the data.
Here is intro.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>Hello World</title>
<style>.error { color: red; } .success { color: green; }</style>
</head>
<body>
<form action="intro" method="post">
<h1>Hello</h1>
<p>
<label for="name">What's your name?</label>
<input id="name" name="name">
<span class="error">${messages.name}</span>
</p>
<p>
<label for="age">What's your age?</label>
<input id="age" name="age">
<span class="error">${messages.age}</span>
</p>
<p>
<input type="submit">
<span class="success">${messages.success}</span>
</p>
</form>
</body>
</html>
Here is IntroductionServlet.java:
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
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("/intro")
public class IntroductionServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Preprocess request: we actually don't need to do any business stuff, so just display JSP.
request.getRequestDispatcher("/WEB-INF/intro.jsp").forward(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Postprocess request: gather and validate submitted data and display result in same JSP.
// Prepare messages.
Map<String, String> messages = new HashMap<String, String>();
request.setAttribute("messages", messages);
// Get and validate name.
String name = request.getParameter("name");
if (name == null || name.trim().isEmpty()) {
messages.put("name", "Please enter name");
} else if (!name.matches("\\p{Alnum}+")) {
messages.put("name", "Please enter alphanumeric characters only");
}
// Get and validate age.
String age = request.getParameter("age");
if (age == null || age.trim().isEmpty()) {
messages.put("age", "Please enter age");
} else if (!age.matches("\\d+")) {
messages.put("age", "Please enter digits only");
}
// No validation errors? Do the business job!
if (messages.isEmpty()) {
messages.put("success", String.format("Hello, your name is %s and your age is %s!", name, age));
}
request.getRequestDispatcher("/WEB-INF/intro.jsp").forward(request, response);
}
}
According to my understanding, form action = "intro" should re-direct the intro.jsp page to the IntroductionServlet once the submit button has been clicked.
However, I receive a requested resource is not available error in Eclipse. It seems like it searches for an intro.jsp file instead. I am running Dynamic Web Module 3.0 so I thought that mapping the servlets is not required in web.xml since I have the "#WebServlet("/intro")" tag.
Basically, I want to know how to retrieve information from a text field once the submit button has been pressed and use it as a variable in my application.
you can also submit your form by manually define your servlet,
i have used that in my application.
following is the code :-
$("#SubmitButton").click(function()
{ var HashedPass=Sha1.hash($("#userPassword").val());
$("#userPassword").val(HashedPass);
$('#loginForm').attr('method','post');
$('#loginForm').attr('action','SignupServlet');
$('#loginForm').submit();
});
Did you try giving it like this(the conventional way):
action="<%=request.getContextPath() %>/IntroductionServlet"
For your second question: Once the control reaches the servlet from the jsp page, the textfield content can be accessed via request.getparameter(textfieldname) in the servlet.
Hope this is useful.
try :
request.getRequestDispatcher("WEB-INF/intro.jsp").forward(request, response);
to receive parameters you should use :
request.getParameter("<name of input text>");
send parameters :
request.setAttribute("myobject", myobjetc);
and to access this variable from jsp using :
${myobject.atribute}
If the servlet not works add this to form (It is not necessary but you can try):
<form action="${pageContext.request.contextPath}/intro" method="POST">

Categories

Resources