POST an array of custom objects to a Struts 2 action - java

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.

Related

How to fix "Exception evaluating SpringEL expression" error after submitting a variable Spring/Thymeleaf

I am using Spring Boot/Thymeleaf to create a form that accepts an email address, redirects to a results page that displays the accepted email and sends it to a third party API (authenticated with Oauth2). I am having trouble with the form portion, I am attempting to use Thymeleaf to accept the input to display it on the result.html page. I am receiving an error when trying to display it on the results page, full error is:
[THYMELEAF][http-nio-8080-exec-4] Exception processing template "result.html": Exception evaluating SpringEL expression: "signup.email" (template: "result.html" - line 10, col 4)
I was attempting to follow the examples provided here:
https://spring.io/guides/gs/handling-form-submission/
I have attempted to modify the controller from #PostMapping and #GetMapping to #RequestMapping and add commenting described in a workaround such as:
<!--/*#thymesVar id="signup" type="com.mainconfig.controller1"*/-->
Here is the signup.html code containing the form:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<html>
<head>
<title>My Jmml</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body style="background-color: #2B2B2B">
<br /><br />
<h2 style="text-align:center">Contact Information</h2>
<!-- Input Form -->
<!--/*#thymesVar id="signup" type="com.mainconfig.controller1"*/-->
<form action="#" th:action="#{/signup}" th:object="${signup}" method="post">
<div align="center">
<label>Email Address</label><br /><br />
<!--/*#thymesVar id="email" type="String"*/-->
<input type="text" th:field="*{email}" placeholder="Email" required />
<br />
<br />
<input class="submitbutton" type='submit' value='Submit'/>
<br />
</div>
</form>
</body>
</html>
Results page that should display the email (result.html):
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Thank you for your submission!</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Thank you for your submission!</h1>
<p th:text="'Email: ' + ${signup.email}" />
Submit another message
</body>
</html>
Controller:
#Controller
public class controller1 {
#RequestMapping (value = "/home")
public String home(Model model) {
return "index.html";
}
#RequestMapping(value = "/signup", method= RequestMethod.GET)
public String signupForm(Model model) {
model.addAttribute("signup", new emailInput());
return "signup.html";
}
#RequestMapping(value = "/signup", method= RequestMethod.POST)
public String signupSubmit(#ModelAttribute("email") emailInput email) {
return "result.html";
}
}
Expected output should be the email variable displayed on the results page after it being gathered in the signup form.
If you have a recommendation on how to better do what I am attempting, I am open to suggestions! I am very new to Spring/Thymeleaf but have had experience with Java/Jsp. Thank you for any help, please let me know if you need anything else to help!
Hopefully this will be a starting point for you.
Make sure you place the html files under /resources/templates.
I changed a bit your signup html and result.html as follows, they are still not perfect(avoid using inline styles and use an external stylesheet!):
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<title>My Jmml</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body style="background-color: #2B2B2B">
<br /><br />
<h2 style="text-align:center">Contact Information</h2>
<!-- Input Form -->
<!--/*#thymesVar id="signup" type="com.mainconfig.controller1"*/-->
<form th:action="#{/signup}" th:object="${signup}" method="post">
<div align="center">
<label>Email Address</label><br /><br />
<!--/*#thymesVar id="email" type="String"*/-->
<input type="text" th:field="*{email}" placeholder="Email" />
<br />
<br />
<input class="submitbutton" type="submit" value="Submit"/>
<br />
</div>
</form>
</body>
and the result.html looks like this
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<title>Thank you for your submission!</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Thank you for your submission!</h1>
<p th:text="'Email: ' + ${email}" />
Submit another message
</body>
</html>
I also created a form object, add additional fields here if you want
public class SignUpForm {
//you can put some annotations here if you want for validating the email
//for e.g #NotEmpty or a #Pattern(regexp to validate the email)
private String email;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
and in the end your Controller. I pass the email from the signup post request to the result.html via a flash attribute:
#Controller
public class Controller1 {
#RequestMapping(value = "/signup", method= RequestMethod.GET)
public String signupForm(#ModelAttribute("signup") SignUpForm form) {
return "/signup";
}
#RequestMapping(value = "/signup", method= RequestMethod.POST)
public String signupSubmit(#ModelAttribute("signup") SignUpForm form, RedirectAttributes redirectAttributes) {
//validate form first -> check bindingResult documentation
//do what you need with your form object
redirectAttributes.addFlashAttribute("email", form.getEmail());
return "redirect:/result";
}
#RequestMapping(value = "/result", method= RequestMethod.GET)
public String result() {
return "/result";
}
}

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 get values from array in jsp

I want to show the data from an array using JSP.
I have three files:
index.jsp:
<%#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>Hello World! </h1>
<form name="Input Name Form" action="response.jsp"/>
<p> Enter your name:</p>
<input type="text" name="name"/>
<input type="submit" value="ok" />
</form>
</body>
</html>
response.jsp:
<%#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>Hello World!</h1> <br>
<jsp:useBean id="aaa" scope="page" class="A.a" />
<jsp:setProperty name="aaa" property="name" value="<%= request.getParameter("name")%>" />
<jsp:getProperty name="aaa" property="name" />
</body>
</html>
a.java:
public class a {
public a ()
{}
private String name;
ArrayList() array_list = new ArrayList();
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
//some magic to fill array_list with values
}
}
My question is:
What statement should I use in jsp to get values from array_list in a.java?
I know that there is statement
<c:forEach> </c:forEach>
but I am not sure how to use it.
<c:forEach items="${dataDetail}" var="data" varStatus="item">
<c:out value="${data.id}"/>
</c:forEach>
Here "dataDetail" is name of the key where you have set your list in controller.
(session or request ).setAttribute("dataDetail",---List of Data of type Class Data---);
Above code is similar to
for(Data data : dataDetail){
System.out.println(data.getId());
}
A similar question has been asked here: Iterate ArrayList in JSP
Long story short:
<c:forEach items="${aaa.array_list}" var="item">
${item}
</c:forEach>
use JSTL.
Try this out:
Have this at top of your JSP:
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
And code for displaying data
<c:forEach begin="0" end="${fn:length(array_list) - 1}" var="index">
<tr>
<td><c:out value="${array_list[index]}"/></td>
</tr>
</c:forEach>

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 compile and run a JSP Beans project using Eclipse

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.

Categories

Resources