How to compile and run a JSP Beans project using Eclipse - java

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.

Related

Spring checkbox parameters

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

How to instantiate an object out of a template of a class (String)

i want to make a webpage where people can register, build their own AI on the Ultimatum-Game as a Java Class and compete each other. The can edit their Class in a textarea, which get stored in a database.
My problem is now getting an object from a class that is just a String yet.
I hope someone can help me.
best regards
test.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>random</title>
</head>
<body>
<form action="test2.jsp" method="post">
<div>
<label for="text">Klasse</label>
<textarea id="text" name="text" cols="100" rows="50">
public class test {
String teststring;
public test() {
this.teststring ="Hallo";
}
}
</textarea>
<input type="submit" value="Senden" />
</div>
</form>
</body>
</html>
test2.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>random</title>
</head>
<body>
<form action="test2.jsp" method="post">
<div>
<label for="text">Klasse</label>
<textarea id="text" name="text" cols="100" rows="50">
public class test {
String teststring;
public test() {
this.teststring ="Hallo";
}
}
</textarea>
<input type="submit" value="Senden" />
</div>
</form>
</body>
</html>

Extrating data from jsp form to controller and saving them to database

Hello I am trying to save data from a form to database however I have no idea how to continue now. I have this following code.
I tried using the request.getParameter("id") in the controller which gave me an compiler error.
So how do I get the data from the jsp form to the controller and then save them to the MySQL database ?
jsp file
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="ProductController" method="post">
<p>Enter product name :</p> <input id="productName" type="text" name="username"> <BR>
<p>Enter product serial number :</p> <input id="serialNumber" type="password" name="password"> <BR>
<input type="submit" placeholder="Submit" />
</form>
</body>
</html>
The controller
#Controller
#RequestMapping("/product")
public class ProductController {
#Autowired
private ProductService productService;
#RequestMapping("/list")
public ModelAndView list() {
ModelAndView modelAndView = new ModelAndView("product/list");
System.out.println("Count:" + productService.getProducts().size());
modelAndView.addObject("test", "mytest");
modelAndView.addObject("count", productService.getProducts().size());
modelAndView.addObject("products", productService.getProducts());
return modelAndView;
}
}
and product DAO
#Override
public void saveProduct(Product product) {
//persist(product);
Session session = this.sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.persist(product);
tx.commit();
session.close();
}
you have to use name attribute of html element to get value, like request.getParameter("username");

how to persist value in text field after refresh?

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>

POST an array of custom objects to a Struts 2 action

How do I POST an array of custom objects to a Struts 2 action in Java?
For example if I have the following Java object:
public class Person {
private String name;
private String lastName;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
And the following Action:
public class SavePersons extends ActionSupport {
private List<Person> persons;
#Override
public String execute() throws Exception {
// Do something
return SUCCESS;
}
public void setPersons(List<Person> persons) {
this.persons = persons;
}
}
I'd like to do something like this in an HTML form:
<html>
<body>
<form method="POST" action="http://postHere">
<input type="text" name="persons[0].name" value="Name1"/>
<input type="text" name="persons[0].lastName" value="LastName1"/>
<input type="text" name="persons[1].name" value="Name2"/>
<input type="text" name="persons[1].lastName" value="LastName2"/>
<input type="submit" />
</form>
</body>
</html>
Any tips?
What you have looks good. It does not make a difference to struts2 if you post or get as far as setting values.
Using the same SavePersons class, except that I added a public List<Person> getPersons() method. This is required to make the solution work.
And using essentially the same form, except I prefer to write my forms using s2 tags where it makes sense (what puts some people off the form tags is the default s2 theme, you can globally set the theme to simple, the label attribute will not work but the UI tags will work just like you'd expect similar html elements to behave):
<%#taglib prefix="s" uri="/struts-tags"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Person Form</title>
</head>
<body>
<h1>Person Form</h1>
<s:form action="person-test" method="post">
<s:textfield name="persons[0].name" label="fName 1"/>
<s:textfield name="persons[0].lastName" label="lName 1"/>
<s:textfield name="persons[1].name" label="fName 2"/>
<s:textfield name="persons[1].lastName" label="lName 2"/>
<s:submit/>
</s:form>
</body>
</html>
Note that method="post" is not needed, it is the default.
Here is the page used to display the form data.
<%#taglib prefix="s" uri="/struts-tags"%>
<%#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>List of People</h1>
<s:iterator value="persons">
<s:property value="name"/> <s:property value="lastName"/><br/>
</s:iterator>
</body>
</html>
And it worked just fine.

Categories

Resources