how to return different actions in struts2 - struts2

I am coding login module, based on the role I want to return different action. I am having code for the different actions in my struts.xml:
if (role == 1) {
Sysyem.out.println("I am a admin");
return "adminaction";
} else if (role == 2) {
Sysyem.out.println("I am a Manager");
return "adminaction";
} else if (role == 3) {
Sysyem.out.println("I am a BA");
return "adminaction";
}
Is there any other way to handle this struts 2. In struts 1 we used to do it by actionforward. We assign some value to action forward and finally return it.

youractionClass
if (role == 1) {
Sysyem.out.println("I am a admin");
return "admin";
} else if (role == 2) {
Sysyem.out.println("I am a Manager");
return "manager";
} else if (role == 3) {
Sysyem.out.println("I am a BA");
return "ba";
}
Now inside struts.xml simply mention the string in the name attribute of result as follows
<action name="loginAction" class="youractionClass">
<result name="admin" type="redirect">adminaction</result>
<result name="manager" type="redirect">managerAction</result>
<result name="ba" type="redirect">baAction</result>
</action>

Related

Setting varible in action class and fetching value in JSP using struts2

I am calling struts2 action class through a ajax call from javascript, which redirect it to b.jsp on success return. In action class I am setting a parameter called dummyValue, for which i have defined getter and setter in the action class. But when i try to display the value of this dummyValue using it does not shows any value.
struts.xml
<package name="AbcAction" namespace="/" extends="struts-default">
<action name="abcAction" class="com.AbcAction">
<result type="stream">
<param name="contentType">text/html</param>
<param name="inputName">stream</param>
</result>
<result name="input" type="dispatcher">/errorPage.jsp</result>
</action>
Setting the result type as stream on purpose.
AbcAction class
public class AbcAction extends ActionSupport {
private InputStream stream;
private String dummyValue;
public String execute() {
dummyValue = "Hello";
try
String str = "success";
stream = new ByteArrayInputStream(str.getBytes());
return SUCCESS;
}
catch (Exception e) {
e.printStackTrace();
String str = "error";
stream = new ByteArrayInputStream(str.getBytes());
return ERROR;
}
}
public InputStream getStream() {
return stream;
}
public void setStream(InputStream stream) {
this.stream = stream;
}
public String getDummyValue() {
return dummyValue;
}
public void setDummyValue(String dummyValue) {
this.dummyValue = dummyValue;
}
}
Javascript function to call action class
function callAbcAction() {
$.ajax({
url : "abcAction",
type: 'post',
data: { },
success : function(result){
if (result == "success") {
window.location='b.jsp';
}
else {
window.location='errorPage';
}
},
});
}
Tag to print dummyMsg in b.jsp
<div class="col-md-3">
<p>Dummy Value is : <s:property value="dummyValue"/></p>
</div>
It is redirecting to b.jsp on success return, but println only "Dummy Value is : " no value is coming.
Please help.
Thanks,
Savvy

MVC5 routing Programming C#

public static CustomerInfo Customer
{
get
{
if (System.Web.HttpContext.Current.Session["CustomerData"] == null)
{
System.Web.HttpContext.Current.Response.Redirect("~/Account/Login");
return new CustomerInfo();
}
else
{
return (CustomerInfo)System.Web.HttpContext.Current.Session["CustomerData"];
}
}
set
{
System.Web.HttpContext.Current.Session["CustomerData"] = value;
}
}
Whenever HttpContext.Current.Session["CustomerData"] is null, instead of redirecting to Login view in Account controller it is giving exception.
You can use
Return RedirectToAction("Login", "Account");
to redirect to another controller and method
Try:
if (System.Web.HttpContext.Current.Session["CustomerData"] == null)
{
Session["CustomerLogin"] = "True";
return new CustomerInfo();
}
else
{
Session["CustomerLogin"] = "False";
return (CustomerInfo)System.Web.HttpContext.Current.Session["CustomerData"];
}
Then in your controller check:
if(Convert.ToString(Session["CustomerLogin"]) == "True"){
return RedirectToAction("Login", "Account");
}

Struts2 return in action cant find another class file

public class Login extends ActionSupport {
//connection made
PreparedStatement pstmt = con.prepareStatement("select * from register1 where username=? and password=?");
pstmt.setString(1, username);
pstmt.setString(2, pwd);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
String role = rs.getString(3);
if (role == null || role.equals("user")) {
session.setAttribute("username", username);
return "Cart"; //here i want to go for another .java file
}
}
Struts.xml
<action name="Login" class="mypack.Login">
<result name="Cart" type="dispatcher">
<param name="location">mypack.CartSelect</param>//Another .java file which support Action Support
</result>
</action>
Class 3:
public class CartSelect extends ActionSupport implements ServletContextAware {
public String execute() throws Exception {
I think what you need is not a dispatcher but instead a redirect.
Here is the reference for redirect action result type.

Struts2 - Annotation for having multiple action methods

Within in same action class, struts2 supports multiple action methods.
One sample of struts.xml - How to convert it to annotation ?
<action name="import"
class="com.action.MainAction" method="importFiles">
<result name="success">main.jsp</result>
<result name="error">error.jsp</result>
</action>
<action name="resourceRowAction"
class="com.action.MainAction" method="resourceRowAction">
<result name="success">main.jsp</result>
<result name="error">erro.jsp</result>
</action>
Annotation solution for above Dynamic Method Invocation can be found here :
http://struts.apache.org/release/2.1.x/docs/convention-plugin.html#ConventionPlugin-Actionannotation
In Action:
#Action(value="default")
#Override
public String execute()
{
return SUCCESS;
}
#Action(value="import")
public String importFiles()
{
return SUCCESS;
}
#Action(value="resourceRowAction")
public String resourceRowAction()
{
return SUCCESS;
}

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