struts 2 rest plugin client program - struts2

i am writing the client web jsp page just like having one form(get) with user name search text box and submit button
when the user submits it returns the json format of user
but the url looks like when i submit it
http://myhost.net:8080?user=pavan&method.execute=submit
how can i convert this url to below one in struts2 .
http://myhost.net:8080/user/pavan
is there any .htaccess file in struts2
#Results( { #Result(name = "success", type = "redirectAction") })
public class UsersController implements ModelDriven<Object>,
ServletRequestAware {
private String username;
private HttpServletRequest request;
private String representation;
// GET /users/{username}
public HttpHeaders show() {
String acceptHeader = request.getHeader("Accept");
String type = "xml";
if (acceptHeader == null || acceptHeader.isEmpty() ||
acceptHeader.equals("application/xml")) {
representation = UserBO.getXML(username);
} else if (acceptHeader.equals("application/json")) {
representation = UserBO.getJSON(username);
type = "json";
}
return new DefaultHttpHeaders(type).disableCaching();
}

You can use Parameters after the Action name.
To use parameters in the URL, after the action name, make sure this is set:
<constant name="struts.enable.SlashesInActionNames" value="true"/>
<constant name="struts.mapper.alwaysSelectFullNamespace" value="false"/>
Then the action mapping will look like:
<package name="edit" extends="struts-default" namespace="/edit">
<action name="/person/*" class="org.apache.struts.webapp.example.EditAction">
<param name="id">{1}</param>
<result>/mainMenu.jsp</result>
</action>
</package>
When a URL like /edit/person/123 is requested, EditAction will be called, and its "id" field will be set to 123.

Related

Feed validator in hybris?

I have used MultipartFile in my controller but it is not taking the file value. Could you please help me?
#RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
#ResponseStatus(value = HttpStatus.OK)
public String uploadFileHandler(
final Model model,
#ModelAttribute final FileUploadModel fileUploadModel,
final BindingResult bindingResult,
final ImportCSVSavedCartForm importCSVSavedCartForm
) {
final String file = fileUploadModel.getCsvFile();
if (!file.isEmpty()) {
uploadExcelFile(file);
}
You have to add your bean into the following part of the spring-filter-config.xml as a new entry in your storefront extension.
<alias name="defaultFileUploadUrlFilterMappings" alias="fileUploadUrlFilterMappings" />
<util:map id="defaultFileUploadUrlFilterMappings" key-type="java.lang.String" value-type="org.springframework.web.multipart.support.MultipartFilter">
<entry key="/import/csv/*" value-ref="importCSVMultipartFilter"/>
</util:map>
importCSVMultipartFilter bean will give you a clue on how to do that.

Globalization in MVCSiteMapProvider

Hi have a sitemap on my mvc 4 application like this:
<?xml version="1.0" encoding="utf-8" ?>
<mvcSiteMap
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://mvcsitemap.codeplex.com/schemas/MvcSiteMap-File-4.0"
xsi:schemaLocation="http://mvcsitemap.codeplex.com/schemas/MvcSiteMap-File-4.0 MvcSiteMapSchema.xsd">
<mvcSiteMapNode title="Users" controller="User" action="Index" area="" preservedRouteParameters="culture,projectid">
<mvcSiteMapNode title="New" controller="User" action="Create" area="" preservedRouteParameters="culture,projectid"/>
<mvcSiteMapNode title="Edit" controller="User" action="Edit" area="" preservedRouteParameters="culture,projectid,id"/>
<mvcSiteMapNode title="Profile" controller="User" action="Details" area="" preservedRouteParameters="culture,projectid,id"/>
</mvcSiteMapNode>
</mvcSiteMap>
I have few resources files in another project that i use for globalize my app, I need the resources files in a separate project because its used in few projects like ddl.
How can i implement globalization for my sitemap?
The approach I would take would be to switch to external DI and then implement a custom IStringLocalizer class that can read the resources from another assembly. Here is a working example. I have created a demo application on GitHub as well.
using System;
using System.Collections.Specialized;
using System.Resources;
namespace MvcSiteMapProvider.Globalization
{
public class ResourceManagerStringLocalizer
: IStringLocalizer
{
public ResourceManagerStringLocalizer(
ResourceManager resourceManager
)
{
if (resourceManager == null)
throw new ArgumentNullException("resourceManager");
this.resourceManager = resourceManager;
}
protected readonly ResourceManager resourceManager;
/// <summary>
/// Gets the localized text for the supplied attributeName.
/// </summary>
/// <param name="attributeName">The name of the attribute (as if it were in the original XML file).</param>
/// <param name="value">The current object's value of the attribute.</param>
/// <param name="enableLocalization">True if localization has been enabled, otherwise false.</param>
/// <param name="classKey">The resource key from the ISiteMap class.</param>
/// <param name="implicitResourceKey">The implicit resource key.</param>
/// <param name="explicitResourceKeys">A <see cref="T:System.Collections.Specialized.NameValueCollection"/> containing the explicit resource keys.</param>
/// <returns></returns>
public virtual string GetResourceString(string attributeName, string value, bool enableLocalization, string classKey, string implicitResourceKey, NameValueCollection explicitResourceKeys)
{
if (attributeName == null)
{
throw new ArgumentNullException("attributeName");
}
if (enableLocalization)
{
string result = string.Empty;
if (explicitResourceKeys != null)
{
string[] values = explicitResourceKeys.GetValues(attributeName);
if ((values == null) || (values.Length <= 1))
{
result = value;
}
else if (this.resourceManager.BaseName.Equals(values[0]))
{
try
{
result = this.resourceManager.GetString(values[1]);
}
catch (MissingManifestResourceException)
{
if (!string.IsNullOrEmpty(value))
{
result = value;
}
}
}
}
if (!string.IsNullOrEmpty(result))
{
return result;
}
}
if (!string.IsNullOrEmpty(value))
{
return value;
}
return string.Empty;
}
}
}
Then you can inject it into your DI configuration module (StructureMap example shown, but any DI container will do).
First of all, you need to specify not to register the IStringLocalizer interface automatically by adding it to the excludeTypes variable.
var excludeTypes = new Type[] {
// Use this array to add types you wish to explicitly exclude from convention-based
// auto-registration. By default all types that either match I[TypeName] = [TypeName] or
// I[TypeName] = [TypeName]Adapter will be automatically wired up as long as they don't
// have the [ExcludeFromAutoRegistrationAttribute].
//
// If you want to override a type that follows the convention, you should add the name
// of either the implementation name or the interface that it inherits to this list and
// add your manual registration code below. This will prevent duplicate registrations
// of the types from occurring.
// Example:
// typeof(SiteMap),
// typeof(SiteMapNodeVisibilityProviderStrategy)
typeof(IStringLocalizer)
};
Then provide an explicit registration of the ResourceManagerStringLocalizer (and its dependencies) instead.
// Configure localization
// Fully qualified namespace.resourcefile (.resx) name without the extension
string resourceBaseName = "SomeAssembly.Resources.Resource1";
// A reference to the assembly where your resources reside.
Assembly resourceAssembly = typeof(SomeAssembly.Class1).Assembly;
// Register the ResourceManager (note that this is application wide - if you are
// using ResourceManager in your DI setup already you may need to use a named
// instance or SmartInstance to specify a specific object to inject)
this.For<ResourceManager>().Use(() => new ResourceManager(resourceBaseName, resourceAssembly));
// Register the ResourceManagerStringLocalizer (uses the ResourceManger)
this.For<IStringLocalizer>().Use<ResourceManagerStringLocalizer>();
Then it is just a matter of specifying the resources appropriately. You need to start them with the Base Name (in this case SomeAssembly.Resources.Resource1), and then specify the key of the resource as the second argument.
<mvcSiteMapNode title="$resources:SomeAssembly.Resources.Resource1,ContactTitle" controller="Home" action="Contact"/>
Or
[MvcSiteMapNode(Title = "$resources:SomeAssembly.Resources.Resource1,ContactTitle", Controller = "Home", Action = "Contact)]
Note that getting the BaseName right is the key to making it work. See the following MSDN documentation: http://msdn.microsoft.com/en-us/library/yfsz7ac5(v=vs.110).aspx

struts2 + jfreechart + jsp : lost request parameters in action which generates Jfreechart

1)I called action which generates jfreechart using next jsp(using tiles) code :
<s:url var="chart" action="resultChart"/>
<img src="<s:property value="%{chart}"/>"/>
2)struts.xml
<package name="chart" extends="jfreechart-default" namespace="/">
<action name="resultChart" class="com.examples.actions.ChartAction">
<result name="success" type="chart">
<param name="width"> 1200 </param>
<param name="height"> 600 </param>
</result>
</action>
</package>
3)to generate chart - I use request parameters from previous action :
public class ChartAction extends ActionSupport implements RequestAware {
private static final long serialVersionUID = 1L;
private Map request;
private JFreeChart chart;
public String execute() throws Exception {
DataBean dataBean = (DataBean)request.get("dataBean");
.....
}
My problem next : I cant draw chart because request return null(dataBean=null)
NOTE : Without passing request parameters all works fine
My research - I used next code in ChartAction(before request.get) to investigate problem:
ValueStack valuestack = ActionContext.getContext().getValueStack();
System.out.println("valuestack.size() = " + valuestack.size());
System.out.println("valuestack root = " + valuestack.getRoot().toString());
And I saw that in ValueStack no records from action which put parameter(dataBean) into request
Please help

Struts2 addActionError setting result to input automatically on redirect result

I have a struts2 action, which sets some error using addActionError something like below
public String del() {
if (new OrdersService().get(idorder) == null) {
addActionError("Order not found");
} else {
new OrdersService().remove(idorder);
addActionMessage("Order deleted successfully");
}
return SUCCESS;
}
So the above method NO MATTER WHAT always return "success" result.
But in struts.xml I've used the redirect result-type to redirect to another action
and that action is never executed instead I'm getting result "input", I'm unable to understand what's going wrong ?
Is it something like
If an action sets an actionError, another action can't be executed and straight away "input" result will be thrown. But it doesn't make sense (at least to me)!
[EDIT] including some part of struts.xml
<action name="/order/{idorder:[0-9]+}/del" class="actions.OrderAction" method="del">
<interceptor-ref name="store">
<param name="operationMode">AUTOMATIC</param>
</interceptor-ref>
<interceptor-ref name="defaultStack" />
<result name="success" type="redirect">orders</result>
</action>
The default stack includes the "workflow" interceptor.
If there are action or field errors this interceptor returns the "input" result, because there was an error.
Reading some documentation will point you in the right direction. Note that your errors will be lost on a redirect anyway, unless you specifically save them.
Also, if you want to redirect to an action, use the "actionRedirect" result type.
public String del() {
if (new OrdersService().get(idorder) == null) {
addActionError("Order not found");
return ERROR;
} else {
new OrdersService().remove(idorder);
addActionMessage("Order deleted successfully");
return SUCCESS;
}
}
Also include return type 'error' as you have done for return type 'success' in your action mapping in struts.xml

How to exclude action methods from validation in struts2

My Action class have the following methods,
1.add
2.edit
3.loadEdit
4.remove
5.list
6.execute
in this i need to apply validation for add and edit..how do need to config in struts.xml.I followed,
<action name="editComment" method="edit"
class="com.mmm.ehspreg2.web.action.product.CommentAction">
<result name="success">/jsp/propertyManager/loadList.jsp</result>
</action>
<action name="removeComment" method="remove"
class="com.mmm.ehspreg2.web.action.product.CommentAction">
<interceptor-ref name="validation">
<param name="excludeMethods">remove</param>
</interceptor-ref>
<result type="tiles">listComment</result>
<result type="tiles" name="input">listComment</result>
</action>
When I configure it like this, remove action method is not getting called. I don't understand the problem. Please assist.
you can also use #SkipValidation before method initialization in action class
e.g.
#SkipValidation
public String save() {
String result = super.save();
if (result.equals(SAVE)) {
setMessage1(getText("save.successful"));
} else {
setMessage1(getText("save.unsuccessful"));
}
jsonResponse = new Hashtable<String, Object>();
jsonResponse.put(FIELD_JSONRESPONSE_STATUS,
KEY_JSONRESPONSE_MESSAGE_SUCCESS);
jsonResponse.put(FIELD_JSONRESPONSE_MESSAGE,
KEY_JSONRESPONSE_EMPTY_STRING);
jsonResponse.put(FIELD_JSONRESPONSE_VALUE, domainModel.getId());
// System.out.println("domainModel>>>>>>" + domainModel.getId());
return result;
}
Simply list all the methods you don't want to be run through the validation framework in the excludeMethods parameter. Since you only want add and edit validated, list the other 4 as follows:
<interceptor-ref name="validation">
<param name="excludeMethods">loadEdit,remove,list,execute</param>
</interceptor-ref>
You can read more about it in the Validation Interceptor docs.

Resources