Struts 2 radio button list [duplicate] - java

This question already has answers here:
Struts 2 select tag with values of a array list
(2 answers)
Closed 6 years ago.
am working on Struts 2 radio button.
I want to retrieve the list from my action class but it is giving following error
org.apache.jasper.JasperException: tag
'radio', field 'list', name
'user.yourGender': The requested list
key '#user.gender' could not be
resolved as a
collection/array/map/enumeration/iterator
type. Example: people or people.{name}
- [unknown location]
my action class & user class is as follow
HelloAction
package com.geekcap.struts2.action;
import com.geekcap.struts2.model.User;
import com.opensymphony.xwork2.ActionSupport;
import java.util.List;
import java.util.ArrayList;
public class HelloAction extends ActionSupport
{
private User user;
public String execute() throws Exception
{
return "success";
}
public void validate()
{
if(user.getName().length()==0)
{
addFieldError("user.name", "User Name is required");
}
if(user.getAge()==0)
{
addFieldError("user.age","Age is required");
}
if(user.getPassword().length()==0)
{
addFieldError("user.password","Please enter your password !");
}
/* if(user.getGender().equals("-1"))
{
addFieldError("user.gender","Please select gender !");
}*/
}
public User getUser()
{
return user;
}
public void setUser(User userbean)
{
user=userbean;
}
}
User class
package com.geekcap.struts2.model;
import java.util.List;
import java.util.ArrayList;
public class User
{
private String name,password;
// private List like;
private int age;
private List<String> gender;
private String yourGender;
public User()
{
gender= new ArrayList<String>();
gender.add("MALE");
gender.add("FEMALE");
gender.add("UNKNOWN");
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password=password;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age=age;
}
public List<String> getGender()
{
return gender;
}
public void setGender(List<String> gender)
{
this.gender=gender;
}
public void setYourGender(String yourGender)
{
this.yourGender=yourGender;
}
public String getYourGender()
{
return yourGender;
}
public String getDefaultGenderValue()
{
return "UNKNOWN";
}
helloForm.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!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>Welcome to Struts 2</title>
</head>
<body>
<s:form action="Hello">
<s:textfield name="user.name" label="User name" value="shahid"/>
<s:password name="user.password" label="Password"/>
<s:textfield name="user.age" label="Age"/>
<s:radio label="Gender" name="user.yourGender" list="user.gender" value="defaultGenderValue"/>
<s:submit/>
</s:form>
</body>
</html>
hello.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!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>Hello, Struts 2</title>
</head>
<body>
<h4>
Hello, <s:property value="user.name"/>!
<br>Your password :<s:property value="user.password"/></br>
<br>your age :<s:property value="user.age"/></br>
<br>Gender :<s:property value="user.yourGender"/></br>
</h4>
</body>
</html>

Are you sure the list gender is NOT null in the JSP?
If it is null, then struts will not see it and therefore think it isn't there

Related

getting null while using request.setattriubute value in struts2

I am working on struts2 but getting issue in the jsp while accessing a variable in form class using a set variable inside property tag.
Please find the below full code.
Testactionform.java
public class Testactionform {
String name = "india";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
TestAction.java
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;
public class TestAction implements SessionAware
{
public Testactionform test;
public Testactionform getTest() {
return test;
}
public void setTest(Testactionform test) {
this.test = test;
}
private Map<String, Object> session;
public Map<String, Object> getSession() {
return session;
}
public void setSession(Map<String, Object> session) {
this.session = session;
}
public String execute()
{
final HttpServletRequest request = ServletActionContext.getRequest();
test=new Testactionform();
request.setAttribute("name1", "name");
test.setName("london");
session.put("Testactionform",test);
System.out.println("execute() method called");
return"success";
}
}
Success.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>error page</h1>
<s:set var="name2" value="#request.name1"></s:set>
<s:property value="%{#session.Testactionform.name2}"/>
</body>
</html>
In JSP with below line, I want to access the name variable in Testactionform, but I get nothing in the response.
<s:property value="%{#session.Testactionform.name2}"/>
Below is the command which is working fine for me .
<s:property value="#session.Testactionform[#name2]"/>

how to iterate an ArrayList in JSP

I create a JSP which call a java method and get an object ArrayList. I want to display the result in a table but nothing appeared. The jsp is like below:
<%# 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"%>
<%# page import="SCOfetch.*" %>
<%# page import="java.util.ArrayList" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>First Page</title>
<% JCOtest connection1 = new JCOtest(); %>
<%
ArrayList<CompanyRecord> list = new ArrayList<CompanyRecord>();
list = connection1.step4QueryTable();
%>
</head>
<body>
<c:forEach var="row" items="${list.rows}">
<tr>
<td><c:out value="${row.getValue(Name)}"/></td>
<td><c:out value="${row.getValue(Code)}"/></td>
</tr>
</c:forEach>
</body>
</html>
The java code of CompanyRecord class is
public class CompanyRecord {
private String Code;
private String Name;
public void setValue(String value,String column)
{
if (column.equals("Code"))
{
Code=value;
}
else
{
Name=value;
}
}
public String getValue(String column)
{
if (column.equals("Code"))
{
return Code;
}
else
{
return Name;
}
}
}
what's the correct way to call an ArrayList lineitem's method? Thanks.
please find the below code for iterate ArrayList in JSP.
and please don't create the ArrayList in JSP.please create ArrayList and set before calling JSP from the servlet.
<%# 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"%>
<%# page import="SCOfetch.*" %>
<%# page import="java.util.ArrayList" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>First Page</title>
<% JCOtest connection1 = new JCOtest(); %>
<%
ArrayList<CompanyRecord> list = new ArrayList<CompanyRecord>();
list = connection1.step4QueryTable();
%>
</head>
<body>
<c:forEach items="${list}" var="row">
<tr>
<td>${row.Name}</td> <!-- use variable name same like in DTO -->
<td>${row.Code}</td>
</tr>
</c:forEach>
</body>
</html>
AND please generate getter methods in CompanyRecord DTO class the only this code will work fine.
public class CompanyRecord {
private String Code;
private String Name;
public void setValue(String value,String column)
{
if (column.equals("Code"))
{
Code=value;
}
else
{
Name=value;
}
}
public String getValue(String column)
{
if (column.equals("Code"))
{
return Code;
}
else
{
return Name;
}
}
public String getCode()
{
return this.Code;
}
public String getName()
{
return this.Name;
}
}

Spring MVC :how a form transfer an object to Controller?? Always 400 error

When i try to access http://localhost:8080/XX/articles/addArticle
and submit the form, there is always a "400 BAD REQUEST" error.
i've tried to look up for the reason, all i got is that object transfered from the form is not as same type as my model(, which is an Article object? here). However, i don't think i really get it..
All codes are here, the config is all good.
Here are 2 models:
Article.java
#Entity
#Table(name="article_inf")
public class Article {
private int articleId;
private String title;
private User author;
private String content;
public Article() {
}
public Article(String title, User author, String content) {
this.title = title;
this.author = author;
this.content = content;
}
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
public int getArticleId() {
return articleId;
}
public void setArticleId(int articleId) {
this.articleId = articleId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#ManyToOne(targetEntity=User.class)
#JoinColumn(name="author", referencedColumnName="userId", nullable=false)
public User getAuthor() {
return author;
}
public void setAuthor(User author) {
this.author = author;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
User.java
#Entity
#Table(name="agri_user_inf")
public class User {
private int userId;
private String userName;
private String password;
private String cellPhone;
private List<Article> articles;
public User() {
articles = new ArrayList<>();
}
public User(String userName, String password, String cellPhone) {
this.userName = userName;
this.password = password;
this.cellPhone = cellPhone;
}
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getCellPhone() {
return cellPhone;
}
public void setCellPhone(String cellPhone) {
this.cellPhone = cellPhone;
}
#OneToMany(targetEntity=Article.class, mappedBy="author")
public List<Article> getArticles() {
return articles;
}
public void setArticles(List<Article> articles) {
this.articles = articles;
}
controller
ArticleController.java
#Controller
#RequestMapping("articles")
public class ArticleController {
private ArticleDao articleDao;
#Autowired
public ArticleController(ArticleDao articleDao) {
this.articleDao = articleDao;
}
#RequestMapping(value="addArticle", method=GET)
public String addArticle(ModelMap modelMap) {
List<User> authors = userDao.getAllUsers();
// add all authors
modelMap.addAttribute("authors", authors);
return "articles/addArticleForm";
}
#RequestMapping(value="addArticle", method=POST)
public String addArticle(Article article) {
articleDao.addArticle(article);
return "redirect:/articles";
}
// other code
my form addArticleForm.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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>
<form method="post">
title: <input type="text" name="title"/><br/>
author: <select name="author">
<c:forEach items="${authors}" var="author">
<option value="${author}">${author.userName}</option>
</c:forEach>
</select>
<br/>
content: <input type="text" name="content"/><br/>
<input type="submit" value="add"/>
</form>
</body>
</html>
You are violating REST principles. Always use version in your endpoint and resource name after that. Example - /api/v1/articles. After that with help of HttpMethods access your resources. Example - If you want to
1.1 add new Article , use POST request to /api/v1/articles
1.2 delete existing Article, use DELETE request to /api/v1/articles/{articleId}
1.3 get one Article, use GET request to /api/v1/articles/{articleId}
1.4 get all Articles, use GET request to /api/v1/articles
1.5 update existing Article, use PUT request to /api/v1/articles/{articleId}
Never use your Entity which is going to be persisted in DB for all layers. It`s bad practice to connect Entity with your view, instead you can use DTO.
Use #ModelAttribute annotation in your controller layer with same name as in view to handle incoming Article object. Example
public String addArticle(#ModelAttribute("article") Article article )
To add new Article first you need to create endpoint which is returning empty Article object inside of ModelMap. Then you must handle this in your front end(JSP) and for submitting this form follow step 3.
Hope this will help.
I got solution :
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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>
<form method="post">
title: <input type="text" name="title"/><br/>
author: <select name="author.userId">
<c:forEach items="${authors}" var="author">
<option value="${author.userId}">${author.userName}</option>
</c:forEach>
</select>
<br/>
content: <input type="text" name="content"/><br/>
<input type="submit" value="add"/>
</form>
</body>
</html>
change name of <select> tag from "author" to "author.userId" . That works.

Why the class can use undefined members in JSTL?

I am reading JSP tutorial from a book and meeting a program that is hard to understand.
It has two beans, one is Message.java, another is MessageServies.java as below.
package com.jeecourse.model;
public class Message {
private String name;
private String text;
public Message() {
}
public Message(String name, String text) {
this.name = name;
this.text = text;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
And the MessageService.java
package com.jeecourse.model;
public class MessageService {
private Message[] fakeMessages;
public MessageService() {
fakeMessages = new Message[3];
fakeMessages[0] = new Message("Jimmy", "Jimmy's message!");
fakeMessages[1] = new Message("Jack", "Jack's message!");
fakeMessages[2] = new Message("Tom", "Tom's message!");
}
public Message[] getMessages() {
return fakeMessages;
}
}
And finnally the message.jsp with EL:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<jsp:useBean id="messageService" class="com.jeecourse.model.MessageService"/>
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8">
<title>NoteBook</title>
</head>
<body>
<table style="text-align: left; width: 100%;" border="1">
<tr>
<td>Name</td><td>Message</td>
</tr>
<c: forEach var="message" items="${messageService.messages}">
<tr>
<td>${message.name}</td><td>${message.text}</td>
</tr>
</c: forEach>
</table>
</body>
</html>
Please note here it uses messageService.messages in EL expression. It is very strange that messageService have neither such members, nor such functions. But it can work. Why?
When you write ${messageService.messages} it gets translated at compile time to messageService.getMessages. Just in the same way that ${message.text} is invoking actually message.getText().
For this kind of "magic" it is important to follow some conventions when naming your methods. If not, the compiler won't know which method it should call when you use the abbreviated version.
You can see more about EL here: https://stackoverflow.com/tags/el/info
This feature is at the top of the page.

addFieldError on Struts2 not displaying error on the fields

Hi I m very new to struts2. from some books and websites I got this example. In action class it use validate method to check logic. The method is called bcoz from the print statements. But the error is not shown near to the fields. Jst help me
Index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="/struts-tags" prefix="s"%>
<!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>Home</title>
</head>
<body>
<s:form action="LoginAction ">
<s:textfield name="username" label="Username" />
<s:textfield name="password" label="Password" />
<s:submit value="Login"></s:submit>
</s:form>
</body>
</html>
Struts.xml
<package name="default" extends="struts-default">
<action name="LoginAction" class="org.shammu.struts2.actions.LoginAction">
<result name="success">/welcome.jsp</result>
<result name="input">/index.jsp</result>
</action>
<action name="emptypassthrough">
<result>index.jsp</result>
</action>
</package>
LoginAction.java
package org.shammu.struts2.actions;
import org.shammu.struts2.beans.LoginBean;
import com.opensymphony.xwork2.ActionSupport;
#SuppressWarnings("serial")
public class LoginAction extends ActionSupport{
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String execute(){
LoginBean login = new LoginBean();
login.setPassword(password);
login.setUsername(username);
if (getUsername().equals("abcd")) {
return "success";
} else {
return "input";
}
}
#Override
public void validate() {
if (username.length() < 3) {
System.out.print("user err ok");
this.addFieldError(username, "Username Empty Pls provide");
}
if (password.length() < 3) {
System.out.print("Pass err ok");
this.addFieldError(password, "Password Empoty provride one pkls");
}
}
}
I m not considering execute method. I want jst the error msg printed near to fields... Help
To display fielderror you need to add <s:fielderror /> in your jsp.
It Render field errors if they exists. Specific layout depends on the particular theme. The field error strings will be html escaped by default.
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib uri="/struts-tags" prefix="s"%>
<!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>Home</title>
</head>
<body>
<s:form action="LoginAction ">
<s:textfield name="username" label="Username" /><s:fielderror fieldName="username"/>
<s:textfield name="password" label="Password" /><s:fielderror fieldName="password"/>
<s:submit value="Login"></s:submit>
</s:form>
</body>
</html>
You are not correctly using addFieldError method. The first parameter in that method is a name of the field. In your case it should be "username".
addFieldError("username", "Username Empty Pls provide");

Categories