I am uploading a file in a form, that form also contains some textfields I enter some values in the textfields. I want this value to remain when I click upload button. And there is also a save button, when I click this button uploaded file should get saved in database. Can any one help me out?
JSP file is here:
<body>
<form action="./upload" enctype="multipart/form-data" >ID: <input type="text" name="id" value="" />Name: <input type="text" name="name" value="" />
<input name="uploaded" type="file" />
<input name="save" type="submit" value="Upload" />
<input type="submit" value="save1" name="save" /></form>
</body>
I need the bussiness logic in a servlet..
Your options are:
Persist the data to your back-end and re-populate the form
Persist the data to the the in-browser Storage (http://www.w3schools.com/html/html5_webstorage.asp)
Put the upload form in an IFRAME
The easiest option is the IFRAME.
Hey you are saying the text field values should be there while clicking Upload button. You don't have to do this thing. By default it will be there. You should it will venish man? Please mention your exact requirement.
See there is no provision to keep the file field data using value attribute.
See this link
package comunity.stackoverflow.test;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class TestController
*/
public class TestController extends HttpServlet {
private static final long serialVersionUID = 1L;
public TestController() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
process(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
process(request, response);
}
private void process(HttpServletRequest request,
HttpServletResponse response) {
storeInRequest(request, "id");
storeInRequest(request, "name");
storeInRequest(request, "uploaded");
// write your upload logic here then navigate to the same page;
try {
request.getRequestDispatcher("/test.jsp").forward(request, response);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void storeInRequest(HttpServletRequest request,String param){
String val = request.getParameter(param);
if(param!=null && !param.isEmpty()){
System.out.println(val);
request.setAttribute(param, val);
}
}
}
Use standard.jat and jstl.jar
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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="upload.do" enctype="multipart/form-data" >
ID: <input type="text" name="id" value="${id}"/>
Name: <input type="text" name="name" value="${name}" />
<input name="uploaded" type="file" />
<input name="save" type="submit" value="Upload" />
<input type="submit" value="save1" name="save" /></form>
</body>
</html>
Use this JSP file. It might solve your problem.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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="upload.do" enctype="multipart/form-data" >
ID: <input type="text" name="id" value="${id}"/><br/>
Name: <input type="text" name="name" value="${name}" /><br/>
<input type="file" id="selectedFile" style="display: none;" />
<input type="text" name="uploaded" id="uploaded" value="${uploaded}" readonly="readonly" size="60">
<input type="button" value="Browse..." onclick="mymethod()" /><br/>
<input name="save" type="submit" value="Upload" />
<input type="submit" value="save1" name="save" /></form>
</body>
<script type="text/javascript">
function mymethod(){
document.getElementById('selectedFile').click();
var val = document.getElementById('selectedFile').value;
document.getElementById('uploaded').value = val;
}
</script>
</html>
Related
I have a class Person with parameters: name, age, email also getter and setter. After that I have created class PersonStorage:
private static List<Person> personList = new ArrayList<Person>();
public void addPerson(Person person){
personList.add(person);
}
public List<Person> getAllPerson(){
return this.personList;
}
My HttpServlet - which getParameter: name, age, email and creating object Person and adding into list:
#WebServlet(urlPatterns = {"/addclientform.jsp"})
public class AddClientServlet extends HttpServlet {
private PersonStorage personList = new PersonStorage();
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
int age = Integer.parseInt(req.getParameter("age"));
String email = req.getParameter("email");
Person person = new Person(name, age, email);
personList.addPerson(person);
req.getRequestDispatcher("printmessage.jsp").forward(req,resp);
}
}
Below my jsp form:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Add Client Form</title>
</head>
<body>
<font size="5">Add Client Form</font><br/>
<br/>
<form action="printmessage.jsp" method="post">
Name: <input type="text" name="name"/><br/>
Age: <input type="text" size="1" name="age"/><br/>
Email: <input type="text" name="email"/><br/>
<br/>
<input type="submit" value="Add Client"/>
</form>
<form name="return" action="home" method='post'>
<input type='submit' value='Return Home'/>
</form>
</body>
</html>
Also I have created one more HttpServlet witch output list of users:
#WebServlet(urlPatterns = {"/clientList"})
public class SeeClient extends HttpServlet {
PersonStorage personStorage = new PersonStorage();
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("list", personStorage.getAllPerson());
req.getRequestDispatcher("clientList.jsp").forward(req,resp);
}
}
And last jsp file with forEach:
<%# page session="false" pageEncoding="UTF-8" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Clien Page</title>
</head>
<body>
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>Email</th>
</tr>
<c:forEach items="${list}" var="personlist">
<tr>
<td>${personlist.name}</td>
<td>${personlist.age}</td>
<td>${personlist.email}</td>
</tr>
</c:forEach>
</table>
<form name="home" action="home.jsp" method="post">
<input type="submit" value="back">
</form>
</body>
</html>
My printmessage jsp:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<html>
<head>
<title>Message</title>
</head>
<body>
<font size="5">Message...</font><br/>
<br/>
<font size="4">Operation completed successfully! </font><br/>
<br/>
<form name="return" action="home.jsp" method='post'>
<input type='submit' value='Return Menu'/>
</form>
</body>
</html>
But when I want to add new User and display them I cannot see anything.
How can I fix it? Can someone help me?
I have a problem with checkbox. I have such jsp page:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>All Photos</title>
</head>
<body>
<form action="/photos/deletePhotos">
<c:forEach var="photo" items="${photoList}">
<p><input type="checkbox" name="id" value="${photo.key}">${photo.key}</p>
<img src="/photos/photo/${photo.key}" width="300" height="200">
<br/><br/>
</c:forEach>
<input type="submit" value="Delete" />
</form>
</body>
</html>
and such controller:
#RequestMapping("/deletePhotos")
public ModelAndView deleteSomePhotos(#PathVariable(name = "id", required = false) long[] id) {
System.out.println(id);
return new ModelAndView("all", "photoList", photos);
}
problem is id==null, no matter checked checkbox or not. Where is my mistake?
#PathVariable is for path variable, like #RuquestMapping("/deletePhotos/{id}").
Use #RequestParam instead of #PathVariable.
Refer here : #RequestParam vs #PathVariable
Hey I am trying to create a voting app.
I have several counters in my servlets and I want to be able to display the value of those counters in my jsp file. How do I do it?
Please help me.
I want to display the total number of votes in each section and the winner after the election.
......................................................................................................................................................
servlet file
......................................................................................................................................................
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;
#WebServlet("/CastVote")
public class CastVote extends HttpServlet {
int javaCount, phpCount, pythonCount, othersCount;
public CastVote() {
super();
javaCount = 0;
phpCount = 0;
pythonCount = 0;
othersCount = 0;
// TODO Auto-generated constructor stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String choice = request.getParameter("language");
if("java".equals(choice))
{
javaCount++;
}
else if("php".equals(choice))
{
phpCount++;
}
else if("python".equals(choice))
{
pythonCount++;
}
else if("others".equals(choice))
{
othersCount++;
}
}
}
......................................................................................................................................................
Jsp File
......................................................................................................................................................
<%# 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>Vote now.</title>
</head>
<body>
<center>
<h2>Welcome to voting portal. Cast your vote.</h2>
</center>
<form action="CastVote" method="post">
Which of the following is the best language for backend programming? <br>
<input type="radio" name="language" value="java">1) Java <br>
<input type="radio" name="language" value="php">2) PHP <br>
<input type="radio" name="language" value="python">3) Python <br>
<input type="radio" name="language" value="others">4) Others <br>
<input type = "submit" value ="Vote">
</form>
</body>
</html>
I am a noob trying to learn what I can about JSPs. I am using Eclipse as my ide and have run into a small problem that I hope someone can help me out with. I have a dynamic web project with the following files:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Get Name</title>
</head>
<body>
<form action="saveName.jsp" method="post">
What is your name?
<input type="text" name="username" size="20">
<br>
What is your email address?
<input type="text" name="email" size="20">
<br>
What is your age?
<input type="text" name="age" size="4">
<br>
<input type="submit">
</form>
</body>
</html>
nextPage.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<jsp:useBean id="user" class="user.UserData" scope="session"></jsp:useBean>
<!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>Next Page</title>
</head>
<body>
You entered
<br>
Name: <%=user.getUserName()%>
<br>
Email: <%=user.getUserEmail()%>
<br>
Age: <%=user.getUserAge()%>
</body>
</html>
saveName.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<jsp:useBean id="user" class="user.UserData" scope="session"></jsp:useBean>
<jsp:setProperty property="*" name="user" />
<!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>Save Name</title>
</head>
<body>
Continue
</body>
</html>
userData.java
package user;
public class UserData {
String userName;
String userEmail;
String userAge;
/**
* #return the userName
*/
public String getUserName() {
return userName;
}
/**
* #param userName
* the userName to set
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* #return the userEmail
*/
public String getUserEmail() {
return userEmail;
}
/**
* #param userEmail
* the userEmail to set
*/
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
/**
* #return the userAge
*/
public String getUserAge() {
return userAge;
}
/**
* #param userAge
* the userAge to set
*/
public void setUserAge(String userAge) {
this.userAge = userAge;
}
}
This app runs just fine except that my nextPage.jsp has null for all of the values. I know this is is because the userData.java is not being called.
Here is how the project is set up the html and jsp files are in the WebContent folder. userData.java is in the Java Resources folder under the user package. I am pretty sure the class for userData is supposed to be copied into the WEB-INF folder but it is not and even if I place it there myself the project still does not run right. Can someone show me how to set this up in Eclipse so that it will run correctly and I can experiment more with JSPs.
The problem is the difference between you input name and the setter of UserData, please try to modify the index.html as:
<form action="saveName.jsp" method="post">
What is your name?
<input type="text" name="userName" size="20">
<br>
What is your email address?
<input type="text" name="userEmail" size="20">
<br>
What is your age?
<input type="text" name="userAge" size="4">
<br>
<input type="submit">
</form>
I have test it OK. Wish it helps.
I have three jsp GetAllEmployee,EmployeeFindByid,EmployeeFindByName ,now i have to code for EmployeeFindById ,EmployeeFindByName in one jsp, i have provide the button for all three in home page (index.jsp) as the user click on employeeFindbyid new pop window open and demanding for id after click on submit button output should be populate in index.jsp i have done with GetAllEmployeei m stucking in portion of EmployeeFindByid,EmployeeFindByName cause i have to write these in one jsp page as the user click on button one pop window should be open and taking the value then pop window should be closed automatically. I am not able to provide the conditon how to execute particular section of code of one jsp
this is my servlet package com.nousinfo.tutorial;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.nousinfo.tutorial.employee.service.model.bo.EmployeeBO;
import com.nousinfo.tutorial.service.bo.EmployeeService;
import com.nousinfo.tutorial.service.bo.impl.EmployeeServiceImpl;
import com.nousinfo.tutorial.service.exception.EmployeeServiceBOException;
import com.nousinfo.tutorial.service.exception.EmployeeServiceException;
/**
* Servlet implementation class GetEmployee
*/
public class GetEmployee extends HttpServlet {
private static final long serialVersionUID = 1L;
EmployeeService employeeService = new EmployeeServiceImpl();
/**
* #see HttpServlet#HttpServlet()
*/
public GetEmployee() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#service(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String name = request.getParameter("findbyid");
System.out.println(name);
RequestDispatcher dispatcher = null;
try {
if (request.getParameter("findbyid") != null) {
request.setAttribute("EmployeeObject", findEmployees(Long
.parseLong(request.getParameter("findbyid"))));
dispatcher = request.getRequestDispatcher("/jsp/employee.jsp");
} else {
request.setAttribute("employeeList", getAllEmployee());
dispatcher = request.getRequestDispatcher("/jsp/winopen.jsp");
}
if (dispatcher != null)
dispatcher.forward(request, response);
} catch (EmployeeServiceBOException e) {
e.printStackTrace();
}
}
private List<EmployeeBO> getAllEmployee() throws EmployeeServiceBOException {
return employeeService.getAllEmployees();
}
private EmployeeBO findEmployees(long id) throws EmployeeServiceBOException {
return employeeService.getEmployee(id);
}
private List<EmployeeBO> findEmployees(String name)
throws EmployeeServiceBOException {
return employeeService.findEmployees(name);
}
}
this is my index.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">
<link rel="stylesheet" href="../css/style.css" type="text/css"></link><title>Home</title>
</head>
<body>
<table width="951" height="116" border="0" align="center">
<tr>
<td width="661" height="112" align="center" bgcolor="#99CCFF"><h2>Project Management </h2></td>
<td width="266" height="112" align="center" bgcolor="#FFFFFF"><img src="../image/nous.jpg" alt="1" width="266" height="84" /></td>
</tr>
</table>
<p> </p>
<table width="949" height="183" border="0" align="center">
<tr>
<td height="42" align="center" bgcolor="#3366FF"><strong>Find Employee </strong></td>
</tr>
<tr>
<td height="43"><form id="form2" method="post" action="/EmployeeWeb/GetEmployee">
<input name="Submit2" type="submit" class="button" value="GetAllEmployee"/>
</form> </td>
</tr>
<tr>
<td width="943" height="43">
<input name="Submit" type="submit" value="getEmployee By ID"
onClick="window.open('file.jsp','mywindow','width=500,height=200 align=center,toolbar=no,resizable=yes,menubar=yes' )" />
</td>
</tr>
<tr>
<td height="43">
<input name="Submit2" type="submit" class="button" value="Get Employee By Name" onClick="window.open('winopen.jsp','mywindow','width=500,height=350,toolbar=no,resizable=yes,menubar=yes')"/>
</td>
</tr>
</table>
<p> </p>
</body>
</html>
this is my getAllEmployee.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>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%#page language="java" import="com.nousinfo.tutorial.employee.service.model.bo.*" %>
<%#page language="java" import="java.util.*" %>
<input name="employee id" value="">
<table >
<tr>
<th>EmployeeNumber</th>
<th>FirstName</th>
<th>LastName</th>
<th>Title</th>
<th>Address-1</th>
<th>Address-2</th>
<th>City</th>
<th>State</th>
<th>Pincode</th>
<th>Mobile_Number</th>
<th>Date_Of_Birth</th>
</tr>
<c:forEach var="employee" items="${employeeList}">
<tr>
<td>${employee.empNumber}</td>
<td>${employee.firstName}</td>
<td>${employee.lastName}</td>
<td>${employee.title}</td>
<td>${employee.address1}</td>
<td>${employee.address2}</td>
<td>${employee.city}</td>
<td>${employee.state}</td>
<td>${employee.pincode}</td>
<td>${employee.mobileNUmber}</td>
<td>${employee.dateOfBirth}</td>
</tr>
</c:forEach>
</table>
</body>
</html>