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]"/>
Related
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;
}
}
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.
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.
i am new to spring mvc
i created a project using SpringTemplateProject and used hibernate in that.
i created a form and on post the values are getting inserted in database but the problem is i am not able to display those values on POST.
here is the code.
//Controller
package com.projects.data;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.projects.data.*;
#Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
#Autowired
ServiceImpl service;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String customer(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
return "home";
}
#RequestMapping(value = "/customer", method = RequestMethod.POST)
public String addCustomer(#ModelAttribute("customer") Customer customer,Model model)
{
service.addCustomer(customer);
return "customer/customer";
}
}
Home.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# page session="false" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<spring:url var="customer" value="/customer"/>
<form:form action="${customer}" method="post" modelAttribute="customer" commandName="custform">
<form:label path="custid">Id:</form:label>
<form:input path="custid"/> <br>
<form:label path="name">Name:</form:label>
<form:input path="name"/> <br>
<form:label path="age">Age:</form:label>
<form:input path="age"/> <br>
<input type="submit" value="Save"/>
</form:form>
</html>
customer.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>Submitted Information</title>
</head>
<body>
<h2>Submitted Information</h2>
<table>
<tr>
<td>Customer id</td>
<td>${custform.custid}</td>
</tr>
<tr>
<td>Name</td>
<td>${custform.name}</td>
</tr>
<tr>
<td>Age</td>
<td>${custform.age}</td>
</tr>
</table>
</body>
</html>
Data is getting inserted in the database but it is not getting displayed.Please help me resolve this.
I tried using #modelAttribute
model.addAttribute("custid",customer.getCustId());
model.addAttribute("name", customer.getName());
model.addAttribute("age", customer.getAge());
But this also does not seem to work.
Model Class
package com.projects.data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="customer")
public class Customer {
#Id
#Column(name="CUST_ID")
int custId;
#Column(name="NAME")
String name;
#Column(name="AGE")
int age;
public Customer(int custId,String name,int age)
{
this.custId=custId;
this.name=name;
this.age=age;
}
//getter and setter methods
public Customer() {
// TODO Auto-generated constructor stub
}
public int getCustId() {
return custId;
}
public void setCustId(int custId) {
this.custId = custId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Remove custform. from ${custform.age},${custform.name} and ${custform.custid} in jsp and keep yout model.addAttribute as it is in controller. You should be able to access age from customer using ${age} in jsp.
Controller:
#RequestMapping(value = "/customer", method = RequestMethod.POST)
public String addCustomer(#ModelAttribute("customer") Customer customer,Model model)
{
service.addCustomer(customer);
model.addAttribute("custid",customer.getCustId());
model.addAttribute("name", customer.getName());
model.addAttribute("age", customer.getAge());
return "customer/customer";
}
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>Submitted Information</title>
</head>
<body>
<h2>Submitted Information</h2>
<table>
<tr>
<td>Customer id</td>
<td>${custid}</td>
</tr>
<tr>
<td>Name</td>
<td>${name}</td>
</tr>
<tr>
<td>Age</td>
<td>${age}</td>
</tr>
</table>
</body>
</html>
OR
simply do model.addAttribute("custform",customer); in controller and leave everything else as it is.
Controller
#RequestMapping(value = "/customer", method = RequestMethod.POST)
public String addCustomer(#ModelAttribute("customer") Customer customer,Model model)
{
service.addCustomer(customer);
model.addAttribute("custform",customer);
return "customer/customer";
}
JSP
Keep it same as in question.
Try
#RequestMapping(value = "/customer", method = RequestMethod.POST)
public ModelAndView addCustomer(#ModelAttribute("customer") Customer customer)
{
service.addCustomer(customer);
Model model = new ModelMap();
model.addAttribute("custid",customer.getCustId());
model.addAttribute("name", customer.getName());
model.addAttribute("age", customer.getAge());
return new ModelAndView("customer/customer", model);
}
BTW: A better approach is to redirect (http code 303) to a customer show page, after the post. Then the user can Reload the Page (F5) without creating a new customer while each refresh.
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