Struts 2.0 error - struts2

I am developing a simple HelloWorld struts application. I am doing the configuration using struts.xml file. the welcome page is displayed but when I click on the form submit button, it gives 404 error.
Kindly provide some pointers.
action class:
package client;
public class Hello {
public String name;
public String message;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String execute() {
message = "Hello " + name;
return "success";
}
}
namecollect.jsp
<s:form action="hello" method="post">
<s:textfield name="name">Enter name</s:textfield>
<s:submit></s:submit>
</s:form>
struts.xml
<package name="default" namespace="/" extends="struts-default">
<action name="hello" class="client.Hello">
<result name="success">hello.jsp</result>
</action>
</package>
This is the package structure:

Your config file is in the wrong place.
By default struts.xml is expected to be at the root of your classpath.

Related

File upload not working with Struts2 Model-Driven Interface

When I am using Model driven interface, my file upload operation is not working.
It is not popping any error, nor it is generating any log.
My code is attached hereby,
I want to know for file, do we have to generate its getters/setters in Model or Action with Model-Driven interface.
Atleast it should get uploaded to temp folder, as with struts by default uploads to temp.
Action
ProductAction.java
package com.fileupload.action;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.fileupload.model.FileUploadModel;
/**
* Action class to requests
* #package com.fileupload.action
*/
public class FileUploadAction extends ActionSupport implements ModelDriven<Object>{
FileUploadModel fileModel = new FileUploadModel();
#Override
public Object getModel() {
return fileModel;
}
}
Model ProductModel.java
package com.fileupload.model;
import java.io.File;
/**
* Model class to handle data
* #package com.fileupload.model
*/
public class FileUploadModel {
private String employeeName;
private File image;
private String imageFileName;
private String imageFileCotentType;
public File getImage() {
return image;
}
public void setImage(File image) {
this.image = image;
}
public String getImageFileName() {
return imageFileName;
}
public void setImageFileName(String imageFileName) {
this.imageFileName = imageFileName;
}
public String getImageFileCotentType() {
return imageFileCotentType;
}
public void setImageFileCotentType(String imageFileCotentType) {
this.imageFileCotentType = imageFileCotentType;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
}
Configuration struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<constant name="struts.devMode" value="true"/>
<package name="FileUploadStruts" extends="struts-default">
<action name="index">
<result>/index.jsp</result>
</action>
<action name="submitForm" class="com.fileupload.action.FileUploadAction">
<result name="success">/result.jsp</result>
</action>
</package>
</struts>
View CreateProduct.jsp
<%--
Document : index
Created on : Nov 26, 2017, 12:50:38 PM
Author : owner
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File upload example</title>
</head>
<body>
<h1>Fill the form below</h1>
<s:form action="submitForm" enctype="multipart/form-data" name="employeeform">
<s:textfield name="employeeName"/>
<s:file name="image"/>
<s:submit value="Submit"/>
</s:form>
</body>
</html>
Of,course,your file upload operation can working When you using Model
driven interface but you made a few mistake:
public class FileUploadModel {
private String employeeName;
private File image;
private String imageFileName;
// YourCode was wrong : private String imageFileCotentType;
private String imageFileContentType;
(get set)...
And then,you need to add a piece of code to your code for upload like
this:
#Namespace("/")
#ParentPackage("struts-default")
public class FileUploadAction extends ActionSupport implements ModelDriven<FileUploadModel> {
private static final long serialVersionUID = 1L;
FileUploadModel fileModel = new FileUploadModel();
#Override
public FileUploadModel getModel() {
return fileModel;
}
#Action(value = "submitForm", results = {
#Result(name = "success", location = "/result.jsp") })
public String submitForm() {
HttpServletRequest request = ServletActionContext.getRequest();
String tomcatPath = ServletActionContext.getServletContext().getRealPath("/");
String projectName = request.getContextPath();
projectName = projectName.substring(1);
String filePath = tomcatPath.substring(0, tomcatPath.indexOf(projectName)) + "uploadFile";
File dest = new File(filePath, fileModel.getImageFileName());
try {
FileUtils.copyFile(fileModel.getImage(), dest);
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
}
if you implements the function based on my answer,please reply to
me,smile.

How to map json payload to model bean in struts2

Is there any way to map json payload to Model bean.? If possible, please provide me an example.
Following are the classes I am using.
package com.sample;
import java.io.Serializable;
public class Employee implements Serializable{
private String firstName;
private String lastName;
private int id;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Employee [firstName=").append(firstName)
.append(", lastName=").append(lastName).append(", id=")
.append(id).append("]");
return builder.toString();
}
}
Following is my action class.
package com.sample.controller;
import com.opensymphony.xwork2.ModelDriven;
import com.sample.Employee;
public class EmployeeController implements ModelDriven<Employee> {
private String name = "Hari krishna";
Employee emp = new Employee();
public String addEmployee() {
System.out.println(emp);
return "success";
}
#Override
public Employee getModel() {
return emp;
}
}
Following is 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>
<package name="default" extends="json-default">
<interceptors>
<interceptor-stack name="jsonStack">
<interceptor-ref name="json">
<param name="enableSMD">true</param>
</interceptor-ref>
</interceptor-stack>
</interceptors>
<action name="addEmployee" class = "com.sample.controller.EmployeeController" method = "addEmployee">
<interceptor-ref name="jsonStack"></interceptor-ref>
<result type="json" />
</action>
</package>
</struts>
When I call the action "addEmployee", with json data "{"firstName":"Hari","id":123,"lastName":"assds"}" I am getting following response. I set content type to text/json.
{
"model": {
"firstName": null
"id": 0
"lastName": null
}-
}
I am posting data using Advanced Rest Client.
when you send the json data from client to server, send them as string and in action class create a normal String variable to receive and hold the json's string.
Then, you can manually populate your bean from string using json parser,
or use a lib like google gson that has a build in features for this purposes.
Google Gson is a Java serialization/deserialization library that can convert Java Objects into JSON and back.
You can create your own struts Interceptor to wrap this process or implements it directly inside your action class.

displaytag not working with struts 2 use tiles

In my application using struts 2 framework and tiles.
Now, I want to use displaytag to display the data in a database table. I did the following:
in my struts.xml:
<action name="users_admin" class="com.controller.admin.UserAction">
<interceptor-ref name="checkSession" />
<result name="login">/login.jsp</result>
<result type="tiles" name="none">/users_admin.tiles</result>
</action>
In file UserAction:
public class UserAction extends ActionSupport{
private List<Users> listUsers;
private String myActionName;
public String getMyActionName() {
return myActionName;
}
public void setMyActionName(String myActionName) {
this.myActionName = myActionName;
}
public List<Users> getListUsers() {
return listUsers;
}
public void setListUsers(List<Users> listUsers) {
this.listUsers = listUsers;
}
#Override
public String execute() throws Exception {
listUsers = UserServices.selectAll();
return NONE;
}
}
And In file user_admin.jsp(file use in tiles):
<s:actionerror cssStyle="color:red"/>
<div class="well">
<display:table name="listUsers" id="listUsers" requestURI="/UserAction" cellpadding="5px;"
cellspacing="5px;" style="margin-left:50px;margin-top:20px;">
<display:column property="EMAIL" title="Email"/>
<display:column property="NAME" title="Name"/>
</display:table>
</div>
File user model:
package com.model;
public class Users {
private String EMAIL;
private String NAME;
public String getEMAIL() {
return EMAIL;
}
public void setEMAIL(String EMAIL) {
this.EMAIL = EMAIL == null ? null : EMAIL.trim();
}
public String getNAME() {
return NAME;
}
public void setNAME(String NAME) {
this.NAME = NAME == null ? null : NAME.trim();
}
}
When I run the application error occurs in apache tomcat log
org.apache.catalina.core.ApplicationDispatcher.invoke Servlet.service() for servlet jsp threw exception
java.lang.ClassNotFoundException: org.apache.commons.collections.IteratorUtils
Who can help me point out why the error, in the solution to overcome it?
Add commons-collections-3.1.jar to your libraries.
Note that you are using only one Interceptor, unless checkSession is the name of your stack.
EDIT
Interceptor checkSession to check my log on the website. How should I use.
You can define a custom interceptor stack, and then reference it, or include your custom interceptor AND another stack (for example, the default one) for a single action, like this:
<action name="users_admin" class="com.controller.admin.UserAction">
<interceptor-ref name="checkSession" />
<interceptor-ref name="defaultStack" />
<result name="login">/login.jsp</result>
<result type="tiles" name="none">/users_admin.tiles</result>
</action>

Input values from jsp are null in Struts action class. How to access the registration form input values in Action class

Registration.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>
<center>
<%# taglib uri="/struts-tags" prefix="s"%>
<s:form action="getRegistered.action" method="post" validate="true">
<div>
<table>
<s:textfield label="First Name" key="firstname" />
<s:textfield label="Last Name" key="lastname" />
<s:password label="Create your password" key="regpassword" />
<s:password label="Confirm your password" key="conpassword" />
<s:textfield label="Email" key="regemail1" />
<s:textfield label="Re-Type Email" key="conemail" />
<s:textfield label="Phone" key="phone" />
<tr>
<td><s:submit value="Register" theme="simple"/></td>
<td><s:submit value="Cancel" theme="simple" onclick="document.forms[0].action='login.jsp';" /></td>
</tr>
</table>
</div>
</s:form>
</center>
</body>
</html>
I'm passing the register input values to Action class.
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>
<package name="default" extends="struts-default">
<action name="getLogin" class="login.action.LoginAction"
method="login">
<result name="success">/Success.jsp</result>
<result name="input">/LoginError.jsp</result>
</action>
<action name="getRegistered" class="login.action.LoginAction"
method="register">
<interceptor-ref name="validation">
<param name="excludeMethods">register</param>
</interceptor-ref>
<result name="success">/Success.jsp</result>
<result name="input">/login.jsp</result>
</action>
</package>
</struts>
This is the struts xml
LoginAction.java:
package login.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import com.opensymphony.xwork2.ActionSupport;
import login.service.LoginDao;
import login.service.RegisterDao;
#SuppressWarnings("serial")
public class LoginAction extends ActionSupport implements ServletRequestAware,
ServletResponseAware {
private String username;
private String password;
private HttpServletRequest httpServletRequest;
private String firstname;
private String lastname;
private String regpassword;
private String conpassword;
private String regemail;
private String conemail;
private String phone;
public String register(){
RegisterDao rdao = new RegisterDao();
System.out.println("firstname action::: "+firstname);
rdao.registerdao(firstname,lastname,regpassword,conpassword,regemail,conemail,phone);
return SUCCESS;
}
public String login() {
httpServletRequest.getSession().setAttribute("key", username);
httpServletRequest.getSession().setAttribute("key", password);
LoginDao db = new LoginDao();
Boolean validate = db.loginresult(username, password);
if (validate == true) {
return SUCCESS;
} else {
return INPUT;
}
}
public HttpServletRequest getHttpServletRequest() {
return httpServletRequest;
}
public void setHttpServletRequest(HttpServletRequest httpServletRequest) {
this.httpServletRequest = httpServletRequest;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getRegpassword() {
return regpassword;
}
public void setRegpassword(String regpassword) {
this.regpassword = regpassword;
}
public String getConpassword() {
return conpassword;
}
public void setConpassword(String conpassword) {
this.conpassword = conpassword;
}
public String getRegemail() {
return regemail;
}
public void setRegemail(String regemail) {
this.regemail = regemail;
}
public String getConemail() {
return conemail;
}
public void setConemail(String conemail) {
this.conemail = conemail;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public void setServletRequest(HttpServletRequest request) {
this.httpServletRequest = request;
}
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;
}
#Override
public void setServletResponse(HttpServletResponse arg0) {
// TODO Auto-generated method stub
}
}
When i submit the registration form , the input values pass to Action class is null. How can i access the registration values in action class under register() method.
The above issue is resolved .
Now i'm facing another strange issue .. When i submit the form action = getLogin.action , its always returning INPUT from the interceptor . I dont wish to exclude the method login from the validator.
How could i resolve it ?
When i change the struts xml like below , its redirecting to success jsp . But i dont want to exclude the login method from validation
<action name="getLogin" class="login.action.LoginAction"
method="login">
<interceptor-ref name="defaultStack">
<param name="validation.excludeMethods">login</param>
</interceptor-ref>
<result name="success">/Success.jsp</result>
<result name="input">/LoginError.jsp</result>
</action>
You are using only one Interceptor, you need to use the whole Stack:
Change this:
<interceptor-ref name="validation">
<param name="excludeMethods">register</param>
</interceptor-ref>
to this
<interceptor-ref name="defaultStack">
<param name="validation.excludeMethods">register</param>
</interceptor-ref>

can not login when using Interceptor in struts2

I have a small application to learn Struts2 Application
I write a admin page and inside that , my code will check if user logged or not, if not it will redirect to login page.
I write interceptor to check for all pages that user try to access but not login, it will redirect this user to login page. Everything is work well, but when i enter username and password correct with database, it can not login, when i remove interceptor i can be logged into admin page
Cause maybe interceptor check session of user before and after login, but maybe some cases i dont know why my application, session get null althought my username and password is true but it till null when i set session.
My code bellow will show you what i said:
Login Action
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.dejavu.software.view;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
import org.dejavu.software.dao.UserDAO;
import org.dejavu.software.model.GroupMember;
import org.dejavu.software.model.User;
/**
*
* #author Administrator
*/
public class AdminLoginAction extends ActionSupport {
private static final long serialVersionUID = -1457633455929689099L;
private User user;
private String username, password;
private String role;
private UserDAO userDAO;
private GroupMember group;
public AdminLoginAction() {
userDAO = new UserDAO();
}
#Override
public String execute() {
String result = null;
System.out.println(getUsername());
if (getUsername().length() != 0 && getPassword().length() != 0) {
setUser(userDAO.checkUsernamePassword(getUsername(), getPassword()));
if (getUser() != null) {
for (GroupMember g : getUser().getGroups()) {
boolean admincp = g.getAdminpermission().contains("1");
if (admincp == true) {
Map session = ActionContext.getContext().getSession();
session.put("userLogged", getUsername());
session.put("passwordLogged", getPassword());
result = "success";
} else {
result = "error";
}
}
}
}
return result;
}
#Override
public void validate() {
if (getUsername().length() == 0) {
addFieldError("username", "Username is required");
}
if (getPassword().length() == 0) {
addFieldError("password", getText("Password is required"));
}
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public GroupMember getGroup() {
return group;
}
public void setGroup(GroupMember group) {
this.group = group;
}
}
My custom interceptor Code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.dejavu.software.interceptor;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import java.util.Map;
import org.apache.struts2.StrutsStatics;
/**
*
* #author Anministrator
*/
public class LoginInterceptor extends AbstractInterceptor implements StrutsStatics {
private static final long serialVersionUID = -3874262922233957387L;
#Override
public void destroy() {
}
#Override
public void init() {
}
#Override
public String intercept(ActionInvocation ai) throws Exception {
Map<String, Object> session = ai.getInvocationContext().getSession();
Object user = session.get("userLogged");
if (user == null) {
return "login";
} else {
return ai.invoke();
}
}
}
my struts config
<?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>
<package name="default" namespace="/" extends="struts-default">
<action name="index" class="org.dejavu.software.view.HomeAction">
<result>home.jsp</result>
</action>
<action name="about" class="org.dejavu.software.view.AboutHomeAction">
<result>about.jsp</result>
</action>
</package>
<package name="admincp" namespace="/admincp" extends="struts-default">
<interceptors>
<interceptor name="login" class="org.dejavu.software.interceptor.LoginInterceptor" />
<interceptor-stack name="stack-with-login">
<interceptor-ref name="login"/>
<interceptor-ref name="defaultStack"/>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="stack-with-login"/>
<global-results>
<result name="login">login.jsp</result>
</global-results>
<action name="logincp" class="org.dejavu.software.view.AdminLoginAction">
<result name="success">dashboard.jsp</result>
<result name="input">login.jsp</result>
<result name="error">login.jsp</result>
</action>
</package>
</struts>
When i enter correct username and password match to database it till redirect to login.jsp page
and i have no idea about that
please help me
Thank you very much
You must configure your login action to use default interceptor stack or it will NOT execute your method because your interceptor will return login result.
<action name="logincp" class="org.dejavu.software.view.AdminLoginAction">
<interceptor-ref name="defaultStack" />
<result name="success">dashboard.jsp</result>
<result name="input">login.jsp</result>
<result name="error">login.jsp</result>
</action>
you also have to check whether user is trying to log in for first time or not.
Because when user tries to log in first time, the session will always be null it will redirect to login page.
For this you can use one other parameter in your login form to check whether user is trying to log in for first time inside interceptor and if yes then invoke the action.
for example:
<form action='' method=''>
<input type='hidden' name='firstLogin' value='1'/>
<input type='text' name='username'/>
<input type='password' name='password'/>
</form>
I used plain html in this code may be you are using struts2-tags so you can implement in that way also.
And inside your Interceptor check.
request = ai.getInvocationContext().get(HTTP_REQUEST);
if(user == null)
{
if(!StringUtils.isEmpty(request.getParameter('firstLogin'))){
return ai.invoke();
}
return "login";
}
else{
return ai.invoke();
}

Resources