When I try to fetch the values from class, which were set in jsp, null is shown.
Following error is observed in dev mode:
ERROR ParametersInterceptor Developer Notification (set struts.devMode to false to disable this message):
Unexpected Exception caught setting 'name' on 'class org.ravi.EmployeeAction: Error setting expression 'name' with value 't'
Below are my various pages
struts.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="default" extends="struts-default">
<action name="addEmployeeAction" class="org.ravi.EmployeeAction">
<interceptor-ref name="params" />
<interceptor-ref name="modelDriven"/>
<result name="success">/Add.jsp</result>
</action>
<action name="EmployeeAction" class="org.ravi.EmployeeAction" method="execute">
<interceptor-ref name="params" />
<interceptor-ref name="modelDriven"/>
<result name="success">/index.jsp</result>
</action>
</package>
</struts>
index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="java.util.*,java.io.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%#taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<s:form action="Add.jsp" name="addForm">
<table border="1" cellpadding="5">
<tr>
<th>Select</th>
<th>EmpID</th>
<th>Name</th>
<th>City</th>
<th>DoB</th>
</tr>
<tr>
<th><input type="radio" name="record"
onClick="radioValidate(this, 'record')" value="%{var}">
</th>
<th><s:property value="empid"/></th>
<th><s:property value="name"/></th>
<th><s:property value="city"/></th>
<th><s:property value="dob"/></th>
</s:form>
</body>
</html>
Add.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">
<%#taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Add New User</h1>
<s:form action="EmployeeAction" >
<s:textfield label="Emp Id" name="empid" />
<s:textfield label="Name" name="name" />
<s:textfield label="City" name="city" />
<s:textfield label="DoB" name="dob" />
<s:submit />
</s:form>
</body>
</html>
EmployeeAction.java
package org.ravi;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class EmployeeAction extends ActionSupport implements ModelDriven<Employee> {
private static final long serialVersionUID = -8136507522861159378L;
private Employee employee=new Employee();
public Employee getEmployee()
{
return employee;
}
public void setEmployee(Employee employee)
{
this.employee=employee;
}
public String execute() throws Exception
{
return SUCCESS;
}
#Override
public Employee getModel()
{
return employee;
}
}
Employee.java
package org.ravi;
import java.io.Serializable;
public class Employee implements Serializable{
static final long serialVersionUID = 1L;
private String empid;
private String name;
private String city;
private String dob;
public void setempid(String empid) {
this.empid = empid;
}
public void setname(String name) {
this.name = name;
}
public void setcity(String city) {
this.city = city;
}
public void setdob(String dob) {
this.dob = dob;
}
public String getempid() {
return this.empid;
}
public String getname() {
return this.name;
}
public String getcity() {
return this.city;
}
public String getdob() {
return this.dob;
}
}
public void setname(String name) {
this.name = name;
}
You need to name all of these properly, ie setName(String name)
same for setEmpId and so on. Struts cannot find your getters/setters because they don't follow naming conventions.
You're committing several errors, the worst is that
you're generating getters and setters manually (a lot of useless work), and you're also doing it wrongly: the first letter of the variable name must be capitalized:
setName( instead of setname( for variable name.
You should (for simplicity and consistency) also do it for every word of your variables with more than one word:
setEmpId( for variable empId.
You should also consider avoiding the redundancy when possible. If you have an ID field on a class Employee, just call it id, not empId... if it's inside Emp, it's obvious it's emp id and not something else id.
Use ModelDriven only if you enjoy pain. For any other purpose, it is as useful as a sausage in your pocket when facing a pack of hungry stray dogs.
Use the HTML5 DTD <!DOCTYPE html> also if you're targeting old browsers, there's no need to use 4.01 nowadays.
Never call JSPs directly like you do in your first form, always pass through actions first.
Start with this. There's plenty more.
Must read
Camel Case
Java Beans specifications
Related
I'm a beginner in STRUTS2 and I want to test two Actions.
The first Action Product work correctly. When I enter "hello" return success otherwise error.
But the second Action CatererTyp return always success.
Can somebody please explain me why?
Here is Product.java
package com.javatpoint;
import com.opensymphony.xwork2.ActionSupport;
public class Product extends ActionSupport {
private int id;
private String name;
private float price;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String execute() {
if(name.equals("hallo")){
return SUCCESS;
}
else{
return ERROR;
}
}
}
CatererType.java
package com.javatpoint;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.opensymphony.xwork2.ActionSupport;
public class CatererType extends ActionSupport {
private String description;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String excute() {
if (description.equals("hello")) {
return ERROR;
} else {
return SUCCESS;
}
}
}
accessdiened.jsp
<%# page contentType="text/html; charset=UTF-8" %>
<%# taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Access Denied</title>
</head>
<body>
You are not authorized to view this page.
</body>
</html>
welcome.jsp
<%# taglib uri="/struts-tags" prefix="s" %>
The Caterer Type: <s:property value="description"/> was inserted <br/>
adminpage.jsp
<%# taglib uri="/struts-tags" prefix="s" %>
<html>
<center>
<s:form action="caterertype">
<s:textfield name="description" label="Caterer Type"></s:textfield>
<s:submit value="save"></s:submit>
</s:form>
</center>
</html>
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts
Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<constant name="struts.devMode" value="false" />
<constant name="struts.custom.i18n.resources" value="ApplicationResources" />
<package name="default" extends="struts-default">
<action name="product" class="com.javatpoint.Product" method="execute">
<result name="success">welcome.jsp</result>
<result name="error">/AccessDenied.jsp</result>
</action>
<action name="caterertype" class="com.javatpoint.CatererType" method="execute">
<result name="success">welcome.jsp</result>
<result name="error">AccessDenied.jsp</result>
</action>
</package>
</struts>
I have tried many things, but not able to solve the issue of Error 404 while I click the submit button of the HR form. I need to get redirected to the output.jsp page as soon as I submit the form of HR. Can anyone help?
Web.Xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>input.jsp</welcome-file>
</welcome-file-list>
</web-app>
Struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"//Apache Software foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="default" extends="struts-default">
<action name="output" class="com.vcm.login.LoginAction" method="execute">
<result name="success">/output.jsp</result>
<result name="input">/input.jsp</result>
</action>
</package>
</struts>
LoginAction.java
package com.vcm.login;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
private String username;
private String password;
private String message;
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 getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String execute(){
if(username.equals("jyotsna")&& password.equals("jyotsna")){
return Action.SUCCESS;
}
else{
addActionError("NOT a VALID user");
return Action.LOGIN;
}
}
public void validate(){
if((username==null) || (username.trim().equals("")))
addFieldError("username","ID cannot be blank");
if(password==null || password.trim().equals(""))
addFieldError("password","password incorrect");
}
}
Input.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>
<table style="align:center">
<tr>
<td width="25%" style="background-color:#33CCFF">
<form action="output">
<p style="color:white"><b><i>HR LOGIN</i></b></p><br>
HR id:<input type="text" name="username" value="" /><br><br>
Psswd:<input type="password" name="password" value="" /><br><br>
<input type="submit" value="login">
</form>
</td>
<td width="70%">
<img src="https://assets.dice.com/external/images/empLogos/6fccd30f19c09f1afee9414a18 5fde3d.jpg" height="100%" width="100%"></td>
<td width="25%" style="background-color:#33CCFF">
<form method="post" action=" ">
<p style="align:center;color:white"><b><i>EMPLOYEE LOGIN</i></b></p><br>
Emp id:<input type="text" name="id" value="" /><br><br>
Psswd :<input type="password" name="psswd" value="" /><br><br>
<input type="submit" value="login">
</form>
</td>
</tr>
</table>
</body>
</html>
Output.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>output</title>
</head>
<body>
<p>
Page of a HR
</p>
</body>
</html>
Use the struts tags.
Load them by adding this at the beginning:
<%# taglib prefix="s" uri="/struts-tags" %>
Use them like this:
<s:form action="output" method="post">
<s:textfield key="username" label="HR id:" />
<s:textfield key="password" label="Psswd:" />
<s:submit type="button">login</s:submit>
</s:form>
Alter the layout by switching/altering the struts ui theme and by using css.
I want to create a simple login form in Struts 2 but I'm having problems at seeing the input fields for some reason and after I submit the name of the user doesn't appear.
Here is the code:
Struts redirects to my struts.xml.
my struts.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false"/>
<!-- devMode equals mode debug information and reload everything for every request -->
<constant name="struts.devMode" value="true" />
<package name="user" namespace="/User" extends="struts-default">
<action name="Login">
<result>Login.jsp</result>
</action>
<action name="DashboardAction" class="action.DashboardAction">
<result name="success">Dashboard.jsp</result>
</action>
</package>
</struts>
The Bean class
DashboardAction.java:
package action;
public class DashboardAction {
private String username;
public String execute(){
return "success";
}
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;
}
}
The JSPs
Login.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login</title>
</head>
<body>
<h1>Struts 2 Login Test</h1>
<form action="DashboardAction" id="form1" method="post" autocomplete="off">
<div class="input placeholder">
<s:textfield name="username" label="Utilizador"/>
</div>
<div class="input placeholder">
<s:password name="password" label="Password"/>
</div>
<div class="submit">
<s:submit value="Entrar" method="execute"/>
</div>
</form>
</body>
</html>
Dashboard.jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome User</title>
</head>
<body>
<h1>Hello
<s:property value="username"/>
</h1>
</body>
</html>
Why doesn't this work after I press submit? It's supposed to go to Dashboard.jsp?
Here you go :
<result name="success">/Dashboard.jsp</result>
You need to specify the full-path to the JSPs in your results. Notice the /. You need to do the same to your other result pages including Login.jsp
You should map the form to the action that accept data submitted. Use Struts tags
<%# taglib prefix="s" uri="/struts-tags" %>
<s:form action="Welcome" ...
<s:textfield name="username" ...
<s:password name="unknown" ...
couldn't map the password field because in your action there's not a property. May be if you create it
private String unknown;
public String getUnknown() {
return unknown;
}
public void setUnknown(String unknown) {
this.unknown = unknown;
}
Define property password in your action class like below.
DashboardAction.java
package action;
public class DashboardAction {
private String username;
private String password; // you don't have this line in your action class.
public String execute(){
return "success";
}
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;
}
}
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");
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