Access ApplicationResource.properties file from Action Class in Struts 2 - struts2

can i access ApplicationResource.properties file keys from Action Class in Struts 2
and update the values of the key ?

I don't think you can update the values of those keys directly, that would kind of defeat the purpose of it being (static) resources.
You can however use placeholders.
ApplicationResources.properties
property.key=Hi {0}, there's a problem with {1}
MyAction.java
public ActionForward execute(ActionMapping mapping,
ActionForm form,
javax.servlet.ServletRequest request,
javax.servlet.ServletResponse response)
throws java.lang.Exception {
MessageResources msgResource = getResources(request);
String msg = msgResource.getMessage("property.key", "Sankar", "updating values in the resources.");
}

Yes its possible.
Lets say if you have a property error.login in applicationResources.properties file.
eg : error.login= Invalid Username/Password. Please try again.
then in the Action class you can access it like this : getText("error.login")
Complete example:
applicationResources.properties
error.login= Invalid Username/Password
LoginAction.java
package net.sumitknath.struts2;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport {
private String username;
private String password;
public String execute() {
if (this.username.equals("admin") && this.password.equals("admin123")) {
return "success";
} else {
addActionError(getText("error.login"));
return "error";
}
}
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;
}
}

Related

Join table issue in Spring Data JPA

I am trying to create a view with datas which combines two tables. I successfully implemented the join and datas are displaying properly by using spring data JPA join. Here my issue is that, when I am calling findAll() method from only one table, which returns all the data including joined table also,
I joined table Users model class like:
#Entity
#Table(name = "users")
public class Users implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Column(name = "username")
public String username;
#Column(name = "password")
public String password;
#Column(name = "privid")
public Integer privid;
#OneToMany(cascade = CascadeType.ALL,mappedBy="pid")
public Set<Privillages> priviJoin;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
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 Integer getPrivid() {
return privid;
}
public void setPrivid(Integer privid) {
this.privid = privid;
}
public Set<Privillages> getPriviJoin() {
return priviJoin;
}
public void setPriviJoin(Set<Privillages> priviJoin) {
this.priviJoin = priviJoin;
}
public Users() {
}
}
And my second model Privillages like,
#Entity
#Table(name = "Privillages")
public class Privillages implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public Integer Id;
#Column(name = "pname")
public String pname;
#ManyToOne(optional = false)
#JoinColumn(name = "pid", referencedColumnName = "privid")
public Users pid;
public Integer getId() {
return Id;
}
public void setId(Integer id) {
Id = id;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public Users getPid() {
return pid;
}
public void setPid(Users pid) {
this.pid = pid;
}
public Privillages(){
}
}
And repository containing,
#Query("select u from Users u JOIN FETCH u.priviJoin p")
Set<Users> findByUsername();
These are all my codes, here i added. The thing is that, join is properly working with expected resultset. But when I call findAll() method , the it returns all the structure including both joined table.
I called my findAll function like,
#RequestMapping("/check")
public List<Users> check() {
return (List<Users>) userRepo.findAll();
}
But result is like I previously mentioned.Here I added its screenshot,
In this figure we can see that it returns the both table values instead of users table data.
Why is it happening like this?
You defined your domain type Users to contain a reference so it gets loaded as specified.
If you want something similar to a Users object but without the reference, you have two options:
Change the Users type to not contain a reference.
Use a different type, similar to Users but without the reference. There are multiple ways to do that, but probably the simplest and most helpful in the current situation is to use a projection. See https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections

user should not logged in using query string

I used login application and it is validating form if userName and password is blank.
Now I am sending userName and password like this
http://localhost:8080/LoginApp/loginAction.action?userName=jagannath&password=123 then also logged in successfully instead of filling login.jsp form page. In this case user should not logged in. How can avoid it using Struts2.
There are 2 types of validations client side( Html/javascript_ and server side (Java Code).
As of now you are doing client side validation only. You need to server side validation as with url param javascript validation is not called - i.e. validation that you do on input. When param are passed you need to check in java code if they are valid or not. Sample code below
public class LoginAction extends ActionSupport {
private String userName;
private String password;
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;
}
public void validate() {
if (getUserName().length() == 0) {
addFieldError("userName", "UserName.required");
} else if (!getUserName().equals("Arpit")) {
addFieldError("userName", "Invalid User");
}
if (getPassword().length() == 0) {
addFieldError("password", getText("password.required"));
}
}
}
More details here

Restricting dropwizard admin page

How to authenticate Dropwizard admin portal, so as to restrict normal users from accessing it?
Please help
In your config, you can set adminUsername and adminPassword under http like so:
http:
adminUsername: user1234
adminPassword: pass5678
For DW 0.7 my approach would be:
public class AdminConstraintSecurityHandler extends ConstraintSecurityHandler {
private static final String ADMIN_ROLE = "admin";
public AdminConstraintSecurityHandler(final String userName, final String password) {
final Constraint constraint = new Constraint(Constraint.__BASIC_AUTH, ADMIN_ROLE);
constraint.setAuthenticate(true);
constraint.setRoles(new String[]{ADMIN_ROLE});
final ConstraintMapping cm = new ConstraintMapping();
cm.setConstraint(constraint);
cm.setPathSpec("/*");
setAuthenticator(new BasicAuthenticator());
addConstraintMapping(cm);
setLoginService(new AdminMappedLoginService(userName, password, ADMIN_ROLE));
}
}
public class AdminMappedLoginService extends MappedLoginService {
public AdminMappedLoginService(final String userName, final String password, final String role) {
putUser(userName, new Password(password), new String[]{role});
}
#Override
public String getName() {
return "Hello";
}
#Override
protected UserIdentity loadUser(final String username) {
return null;
}
#Override
protected void loadUsers() throws IOException {
}
}
and using them in the way:
environment.admin().setSecurityHandler(new AdminConstraintSecurityHandler(...))
Newer Jetty versions do not have MappedLoginService, so #Kamil's answer no longer works. I have modified their answer to get it working as of Dropwizard 1.2.2:
public class AdminConstraintSecurityHandler extends ConstraintSecurityHandler {
private static final String ADMIN_ROLE = "admin";
public AdminConstraintSecurityHandler(final String userName, final String password) {
final Constraint constraint = new Constraint(Constraint.__BASIC_AUTH, ADMIN_ROLE);
constraint.setAuthenticate(true);
constraint.setRoles(new String[]{ADMIN_ROLE});
final ConstraintMapping cm = new ConstraintMapping();
cm.setConstraint(constraint);
cm.setPathSpec("/*");
setAuthenticator(new BasicAuthenticator());
addConstraintMapping(cm);
setLoginService(new AdminLoginService(userName, password));
}
public class AdminLoginService extends AbstractLoginService {
private final UserPrincipal adminPrincipal;
private final String adminUserName;
public AdminLoginService(final String userName, final String password) {
this.adminUserName = Objects.requireNonNull(userName);
this.adminPrincipal = new UserPrincipal(userName, new Password(Objects.requireNonNull(password)));
}
#Override
protected String[] loadRoleInfo(final UserPrincipal principal) {
if (adminUserName.equals(principal.getName())) {
return new String[]{ADMIN_ROLE};
}
return new String[0];
}
#Override
protected UserPrincipal loadUserInfo(final String userName) {
return adminUserName.equals(userName) ? adminPrincipal : null;
}
}
}

Returning value from a web browser

I had created 4 classes for the restlet. However, When I hit on the browser, http://localhost:8182/firstSteps/hello, it returns me UserName = userName, Password = password. Which class should I change in order to get the intended url such as http://localhost:8080/restletTest?p1=abc&p2=def??
package firstStep;
import org.restlet.Component;
import org.restlet.data.Protocol;
public class Mainone {
public static void main(String[] args) throws Exception {
// Create a new Component.
Component component = new Component();
// Add a new HTTP server listening on port 8182.
component.getServers().add(Protocol.HTTP, 8182);
// Attach the sample application.
component.getDefaultHost().attach("/firstSteps", new FirstStepsApplication());
// Start the component.
component.start();
}}
package firstStep;
import org.restlet.Application;
import org.restlet.Restlet;
import org.restlet.routing.Router;
public class FirstStepsApplication extends Application{
public Restlet createInboundRoot(){
Router router = new Router(getContext());
router.attach("/hello",FirstServerResource.class);
return router;
}}
package firstStep;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;
public class FirstServerResource extends ServerResource {
Contact contact = new Contact("userName","Password");
//Contact contactTwo = contact.retrieve();
// #Get
// public Contact retrieve() {
// return contact;
// }
#Get
public String toString() {
return contact.toString();
}
}
package firstStep;
public class Contact {
private String userName;
private String password;
//Constructor
public Contact(String userName,String password){
this.userName = userName;
this.password = password;
}
public Contact retrieve(){
System.out.println("Contact retrieve():"+this.userName+"|"+this.password);
return this;
}
public String toString(){
return "Username:\t"+this.userName+"\nPassword:\t"+this.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;
}}
When you hit http://localhost:8182/firstSteps/hello
the #Get toString()-method of contact is called and the output
UserName: userName
Password: Password
is correct.
So The value is returned from the server correctly.
What else do you want to do?

Struts2 Iteration of ArrayList with JavaBean

This Question may be asked in several threads...but could not fine the correct answer
a Java Bean
package com.example;
public class Document {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
An ArrayList creation of JavaBean as displayed below
package com.example;
import java.util.ArrayList;
public class classdocs {
public ArrayList getData() {
ArrayList docsmx = new ArrayList();
Document d1 = new Document();
d1.setName("user.doc");
Document d2 = new Document();
d2.setName("office.doc");
Document d3 = new Document();
d3.setName("transactions.doc");
docsmx.add(d1);
docsmx.add(d2);
docsmx.add(d3);
return docsmx;
}
}
an Action Class
package com.example;
import java.util.ArrayList;
import com.opensymphony.xwork2.ActionSupport;
public class FetchAction extends ActionSupport {
private String username;
private String message;
private ArrayList docsmx = new ArrayList();
public ArrayList getDocuments() {
return docsmx;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String execute() {
classdocs cx = new classdocs();
if( username != null) {
docsmx = cx.getData();
return "success";
} else {
message="Unable to fetch";
return "failure";
}
}
}
Jsp with Struts2 Iterator Tag
Documents uploaded by the user are:</br>
<s:iterator value="docsmx">
<s:property value="name" /></br>
</s:iterator>
Question Why the ArrayList of Bucket containing JavaBean not displayed when Iterated ...
Am I doing some thing wrong ???
with regards
karthik
Depending your version, you should either provide a getter for docsmx (preferred, pre-S2.1.mumble), or make docsmx public (not as preferred, S2.1+).
Or, based on your code, use the correct getter:
<s:iterator value="documents">
<s:property value="name" /></br>
</s:iterator>
A couple of notes: documents should likely be declared a List, not ArrayList, although in this case it almost certainly doesn't matter. It's a good habit to get in to, though, coding to an interface when the implementation doesn't matter.
I'd also consider tightening up the code a little bit:
public String execute() {
if (username == null) {
message = "Unable to fetch";
return "failure";
}
docsmx = cs.getData();
return "success";
}
This allows a more natural reading, makes it more clear what the two states are (success and failure), keeps them very distinct, and slightly shorter.

Resources