I would like to print out my current variable value on my HTML page. I cannot seem to figure it out. On my HTML page, I want to print out the current Exchange rate.
This is my HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset="US-ASCII">
<title>Calculator</title>
</head>
<body>
<form action="Converter" method="get" name="frm">
Amount:
<input name="amount" type="text" />
Rate:
<input name="conversionRate" type="text" />
<input type="submit" value="Convert!" />
<br>Current Rate:
</form>
</body>
</html>
My Java Code
import java.io.IOException;
import java.io.PrintWriter;
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 Converter
*/
#WebServlet("/Converter")
public class Converter extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Converter() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
String n2 = "1.0";
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
String n1 = request.getParameter("amount");
String tempStr;
tempStr = request.getParameter("conversionRate");
if(!tempStr.isBlank()) {
n2 = tempStr;
}
if(n2.equals("tempStr")){
out.println((Integer.parseInt(n1) / Double.parseDouble(n2)));
}
else if(n2.equals(n2)){
out.println("test");
out.println((Integer.parseInt(n1) / Double.parseDouble(n2)));
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
How can I print out the current rate. Which in this case is n2 on my HTML page? I want it to update on each load of the website. But I cannot figure out how to print out the variable value through the HTML page.
You can use your PrintWriter instance to print the whole HTML into the response object, example:
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Bla</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>");
out.println("Your current rate is: ");
//Your Java code here
String n1 = request.getParameter("amount");
String tempStr;
tempStr = request.getParameter("conversionRate");
if(!tempStr.isBlank()) {
n2 = tempStr;
}
out.println(n2);
out.println("</h1>");
out.println("</body>");
out.println("</html>");
}
Hope that helps.
Related
Hello guys i'm facing a problem with my code, i have a jsp form that send a file into a servlet, and when i try to extract the file using request.getParts() it return null value wheni try to print it to the console, can anyone help me please. here is my code.
my jsp:
<!DOCTYPE html>
<html lang="en">
<head>
<title>File Upload</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form method="POST" action="/PartsServlet" enctype="multipart/form-data" >
File:
<input type="file" name="file" id="file" /> <br/>
Destination:
<input type="text" value="/tmp" name="destination"/>
</br>
<input type="submit" value="Upload" name="upload" id="upload" />
</form>
</body>
</html>
My servlet:
package Servv;
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;
/**
* Servlet implementation class PartsServlet
*/
#WebServlet("/PartsServlet")
public class PartsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public PartsServlet() {
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());
System.out.println("Get Parts "+request.getPart("file"));
System.out.println("Get Parts "+request.getPart("destination"));
}
/**
* #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);
}
}
Add #MultipartConfig annotation.
Always parse your request body only once and store it in a list.
so that one part cannot consume it.
List<Part> fileParts = request.getParts().stream().filter(part -> "file".equals(part.getName())).collect(Collectors.toList());
for (Part part : fileParts) {
}
File uploads = new File("/path/to/uploads");
File file = File.createTempFile("somefilename-", ".ext", uploads);
try (InputStream input = part.getInputStream()) {
Files.copy(input, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
Why am I getting null value while using "sendReditect" in servlet as per below
my code as per below : I am getting fname value null even in both FirstServlet and SecondServlet
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="FirstServlet" method="get">
username<input type="text" name="fname"></br> <input type="submit"
value="SUBMIT">
</form>
</body>
</html>
FirstServlet:
package com.naveen;
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;
/**
* Servlet implementation class FirstServlet
*/
#WebServlet("/FirstServlet")
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse res) throws ServletException, IOException {
String s3=request.getParameter("fname");
// TODO Auto-generated method stub
/*String s1=request.getParameter("t1");*/
/*RequestDispatcher rd=request.getRequestDispatcher("SecondServlet");
rd.forward(request, response);*/
res.sendRedirect("SecondServlet");
System.out.println("your output as per" +s3);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
SecondServlet:
package com.naveen;
import java.io.IOException;
import java.io.PrintWriter;
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 SecondServlet
*/
#WebServlet("/SecondServlet")
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String s3=request.getParameter("fname");
out.print("hi i am siddharth");
out.println(s3);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
why i am getting null value while using "sendReditect" in servlet as
per below my code as per below : i am getting fname value null even in
both FirstServlet and SecondServlet,
Because you're not setting any values to your request. You need to set the value to the request like this:
#WebServlet("/FirstServlet")
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse res) throws ServletException, IOException {
String s3=request.getParameter("fname"); //get the value you set in your jsp/html/url
request.setAttribute("fname", s3); // set the s3 value to the request
res.sendRedirect("SecondServlet");
System.out.println("your output as per" +s3);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
I'm assuming here you have sent the fname value via a form or something. If you call FirstServlet by just typing it in the url, you will get null.
But not if you set something, try it like this if you are not submitting a form:
/FirstServlet?fname=helloworld
EDIT:
just noticed in your form you're not actually setting fname with any value. You need to give it a value:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="FirstServlet" method="get">
username<input type="text" name="fname" value="helloworld"></br> //add value to your input!!
<input type="submit" value="SUBMIT">
</form>
</body>
</html>
I am getting an error HTTP Status 500 - java.io.FileNotFoundException:
C:\sam\IMAGES (Access is denied) while saving an image in the file 'IMAGES'.I tried all the things like changing the permission of the file and tried to save it in different folder.The strange thing is that my images are actually getting stored in the file which i mentioned above.But why still its shows the error?? how to resolve this error?Tomcat is under the ownership of user.
My Code:
MySampleUpload.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="FileUploadServlet" method="post"enctype="multipart/form-data">
<div class="btn btn-success btn-file">
<i class="fa fa-cloud-upload"></i>
Browse
<input type="file" name="file" />
</div>
<button type="submit" value="submit" name='submit'>submit</button>`
</form>
</body>
</html>
FileUploadServlet.java
import java.io.File;
import java.io.IOException;
import javax.imageio.stream.FileImageOutputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.RandomAccessFile;
/**
* Servlet implementation class FileUploadServlet
*/
#WebServlet("/FileUploadServlet")
#MultipartConfig(fileSizeThreshold=1024*1024*10, // 10 MB
maxFileSize=1024*1024*50, // 50 MB
maxRequestSize=1024*1024*100) // 100 MB
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
private static final String UPLOAD_DIR="IMAGES";
public FileUploadServlet() {
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 {
// TODO Auto-generated method stub
//gets absolute path of the web application
//String applicationPath=request.getServletContext().getRealPath("");
//construct path of the directory to save the uploaded file
String UploadFilePath="C:/sam"+File.separator+UPLOAD_DIR;
//creates the file directory if it doesn't exist
File FileSaveDir=new File(UploadFilePath);
if(!FileSaveDir.exists())
{
FileSaveDir.mkdirs();
}
System.out.println("Upload file Diiirectory"+FileSaveDir.getAbsolutePath());
String fileName=null;
//get all parts from request and write it to the file on the server
for(Part part:request.getParts())
{
fileName=getFileName(part);
part.write(UploadFilePath + File.separator + fileName);
}
System.out.println("File Uploaded successfully");
request.setAttribute("message",fileName+"file uploaded successfully");
getServletContext().getRequestDispatcher("/response.jsp").forward(request, response);
}
private String getFileName(Part part)
{
String ContentDisp=part.getHeader("Content-Disposition");
System.out.println("content-disposition-header"+ContentDisp);
String[] tokens = ContentDisp.split(";");
for (String token : tokens) {
if (token.trim().startsWith("filename")) {
return token.substring(token.indexOf("=") + 2, token.length()-1);
}
} return "";
}}
Your part object iterated 2 times , from that 1st time it get file name and 2nd time it is null.so check filename inside part for null.
Replace This Part.
for (Part part : request.getParts()) {
fileName = getFileName(part);
if (fileName != null && !"".equals(fileName)) {
part.write(UploadFilePath + File.separator + fileName);
}
}
You can use below code also , where form component and file component are separated.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
String fieldname = item.getFieldName();
String fieldvalue = item.getString();
// ... (do your job here)
} else {
// Process form file field (input type="file").
String fieldname = item.getFieldName();
String filename = FilenameUtils.getName(item.getName());
InputStream filecontent = item.getInputStream();
// ... (do your job here)
}
}
} catch (FileUploadException e) {
throw new ServletException("Cannot parse multipart request.", e);
}
// ...
}
I'm currently trying to complete a simple Web project using Activiti. I doing it in Eclipse using a Tomcat 7.0 server. I have a servlet that should display a tasks info but even if there's a problem there surely it should still display something.
I'm only starting to learn JSP so I apologise for any stupid mistakes I may have made in the code.
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Main Page</title>
</head>
<body>
<h1>Welcome.</h1>
<br />
<h3>Go to:</h3>
<ul>
<li>Request Loan</li>
<li>Management Tasks</li>
</ul>
</body>
</html>
My servlet:
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
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.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
/**
* Servlet implementation class ManagementTasks
*/
#WebServlet("/ManagementTasks")
public class ManagementTasks extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ManagementTasks() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Management Tasks</title</head><body>");
ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
TaskService taskService = processEngine.getTaskService();
List<Task> tasks = taskService.createTaskQuery()
.taskCandidateGroup("management").list();
if (tasks.size() > 0) {
out.println("<h1>You have " + tasks.size() + " task(s) to complete.</h1>");
Task t = tasks.get(0);
out.println("<br /><br /><h2>" + t.getDescription() + "</h2>");
out.println("<br />Do you want to approve this request?</h2><br />");
out.println("<form method=\"POST\" action=\"ManagementApproval\">");
out.println("<label for=\"approve\">Do you approve?</label>");
out.println("<select name=\"approve\">");
out.println("<option value=\"true\">Yes</option>");
out.println("<option value=\"false\">No</option>");
out.println("</select><br />");
out.println("<input type=\"hidden\" id=\"taskId\" name=\"taskId\" " + "value=\"" + t.getId() + "\" /><br/>");
out.println("<input type=\"submit\" value=\"Submit Form\" />");
out.println("<input type=\"reset\" value=\"Reset Form\" />");
out.println("</form>");
} else {
out.println("<h1>There are no tasks for you. </h1>");
}
out.println(" HOME ");
out.println("</body></html>");
out.close();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
I am creating a java servlet which should get a number from a textbox (created using using HTML) calculate its factorial and when i will press submit button (also created using HTML) it should calculate and display the factorial in another textbox which i have created.
Problem I have successfully retrieved the number from the first textbox (using request.getParameter) and calculated it factorial. Now the problem is that i am unable to post the calculated factorial in that 2nd textbox.
Plz help me what should i do?
Thank in advance!
Here is the code:
servlet:
package factorial;
import java.io.*;
import javax.servlet.Servlet;
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.apache.jasper.tagplugins.jstl.core.Out;
/**
* Servlet implementation class fact
*/
#WebServlet("/fact")
public class fact extends HttpServlet implements Servlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public fact() {
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
PrintWriter out = response.getWriter();
long number = Long.parseLong((request.getParameter("num")));
long fact=1;
while(number>1){
fact=fact*number;
number--;
}
//request.setAttribute("factorial", fact); //***this is not working***
//out.println(fact);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Factorial</title>
</head>
<body>
<form action="fact" method="get">
Enter a number: <input type="text" name="num">
<input type="submit"/>
Factorial <input type="text" id="factorial" name="factorial"/>
</form>
</body>
</html>
store the value in request or session attributes as request.setAttribute("name",value) or session.setAttribute("name", value). and in JSP, retrieve them using request.getAttribute("name") or session.getAttribute("name")