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.
Related
We all knows how to use s:action tag:
<s:action name="actionA" namespace="/namespaceA">
<s:param name="param" value="123"/>
</s:action>
now I want to write my own tag, extends from ActionTag, and I give a variable named 'url' to determine an action on my jsp pager:
<mytab:action url="/namespaceA/actionA.action?param=123"/>
Here are the Java Code:
public class ResultTag extends ActionTag {
private String url;//链接
protected void populateParams() {
super.populateParams();
ActionComponent action = (ActionComponent) this.component;
action.setNamespace(getNamespace(url));
action.setExecuteResult(true);
action.setName(getActionName(url));
}//other methods}
now I don't know where to set my parameters (param=123) on my java code, can anybody tell me how to do?thanks a lot!
I've got a Grails (2.3.8) project that's integrating with a few Java classes. When I attempt to dataBind a one to many relationship, I receive the following error:
{
"errors":
[
{
"object": "com.sample.Author",
"message": "No such field: referencedPropertyType for class: org.codehaus.groovy.grails.orm.hibernate.GrailsHibernateDomainClassProperty"
}
]
}
Does anyone know why the data binding function is trying to bind "referencePropertyType"?
I've included a simplified version of my project with an Author and Books added to the src/java folder.
Author.java
#Entity
public class Author {
private long _id;
private List<Books> _books;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "author")
public List<Book> getBooks() {
return _books;
}
// getters and setters
}
Book.java
#Entity
public class Book {
private long _id;
private Author author;
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "AUTHOR_ID", foreignKey = #ForeignKey(name = "author_fk"), nullable = false)
public Author getAuthor() {
return _author;
}
// getters and setters
}
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping class="com.sample.Author" />
<mapping class="com.sample.Book" />
</session-factory>
</hibernate-configuration>
AuthorController.groovy
class AuthorController {
def doSomething() {
def authorInstance = new Author(params)
if(authorInstance.hasErrors()) {
println authorInstance.errors as JSON
}
}
}
Does anyone know why the data binding function is trying to bind
"referencePropertyType"?
The data binding function is not trying to bind referencedPropertyType. The binder is trying to retrieve that value because the value helps the data binder figure out which types of objects need to be created during data binding.
It looks like there may be a bug with respect to Java domain models in certain circumstances when using the Hibernate plugin. If you file a bug report at https://jira.grails.org/browse/GRAILS and attach a simple sample app, we will get it straightened out.
Sorry for the trouble.
After upgrading my project from 2.3.8 to 2.4.0 the issue has been resolved. Looks like it was a bug, but upgrading the project fixed the issue.
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.
I have a few pages that needs a userId to work, thus the following code:
userpage.xhtml
<!-- xmlns etc. omitted -->
<html>
<f:metadata>
<f:viewParam name="userId" value="#{userPageController.userId}"/>
</f:metadata>
<f:view contentType="text/html">
<h:head>
</h:head>
<h:body>
<h:form>
<h:commandButton action="#{userPageController.doAction}" value="post"/>
</h:form>
</h:body>
</f:view>
userPageController.java
#Named
#ViewScoped
public class userPageControllerimplements Serializable {
private static final long serialVersionUID = 1L;
#Inject protected SessionController sessionController;
#Inject private SecurityContext securityContext;
#Inject protected UserDAO userDAO;
protected User user;
protected Long userId;
public UserPage() {
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
if(!FacesContext.getCurrentInstance().isPostback()){
User u = userDAO.find(userId);
this.userId = userId;
this.user = u;
}
}
public void doAction(){
}
}
However, after doAction is called, the view parameter in the url disappears. The bean still works due to its viewscoped nature, but it ruins my attempts of future navigation. When i search around, I get the impression that the view parameter should remain after a post thus reading userpage.jsf?userId=123, but this is not the case. What is really the intended behaviour?
Related to this, I've tried to implement automatic adding of view parameters when navigating to another page where I want to keep the userId. It seems to work for others, but for me, the userId in the ViewRoot is always null. Code below used to retrieve the viewparameter (i know i could use my temporarily stored userId in the bean for navigation, but this solution would be much fancier):
String name = "userId";
FacesContext ctx = FacesContext.getCurrentInstance();
ViewDeclarationLanguage vdl = ctx.getApplication().getViewHandler().getViewDeclarationLanguage(ctx, viewId);
ViewMetadata viewMetadata = vdl.getViewMetadata(ctx, viewId);
UIViewRoot viewRoot = viewMetadata.createMetadataView(ctx);
UIComponent metadataFacet = viewRoot.getFacet(UIViewRoot.METADATA_FACET_NAME);
// Looking for a view parameter with the specified name
UIViewParameter viewParam = null;
for (UIComponent child : metadataFacet.getChildren()) {
if (child instanceof UIViewParameter) {
UIViewParameter tempViewParam = (UIViewParameter) child;
if (name.equals(tempViewParam.getName())) {
viewParam = tempViewParam;
break;
}
}
}
if (viewParam == null) {
throw new FacesException("Unknown parameter: '" + name + "' for view: " + viewId);
}
// Getting the value
String value = viewParam.getStringValue(ctx); // This seems to ALWAYS be null.
One last thought is that the setter methods still seem to work, setUserId is called with the correct value on post.
Have I completly missunderstood how view parameters work, or is there some kind of bug here? I think my use case should be extremly common and have basic support in the framework.
When i search around, I get the impression that the view parameter should remain after a post thus reading userpage.jsf?userId=123, but this is not the case. What is really the intended behaviour?
This behaviour is correct. The <h:form> generates a HTML <form> element with an action URL without any view parameters. The POST request just submits to exactly that URL. If you intend to keep the view parameters in the URL, then there are basically 3 ways:
Bring in some ajax magic.
<h:commandButton action="#{userPageController.doAction}" value="post">
<f:ajax execute="#form" render="#form" />
</h:commandButton>
This way the initially requested page and thus also the request URL in browser's address bar remains the same all the time.
If applicable (e.g. for page-to-page navigation), make it a GET request and use includeViewParams=true. You can use <h:link> and <h:button> for this:
<h:button outcome="nextview?includeViewParams=true" value="post" />
However, this has an EL security exploit in Mojarra versions older than 2.1.6. Make sure that you're using Mojarra 2.1.6 or newer. See also issue 2247.
Control the generation of action URL of <h:form> yourself. Provide a custom ViewHandler (just extend ViewHandlerWrapper) wherein you do the job in getActionURL().
public String getActionURL(FacesContext context, String viewId) {
String originalActionURL = super.getActionURL(context, viewId);
String newActionURL = includeViewParamsIfNecessary(context, originalActionURL);
return newActionURL;
}
To get it to run, register it in faces-config.xml as follows:
<application>
<view-handler>com.example.YourCustomViewHandler</view-handler>
</application>
This is also what OmniFaces <o:form> is doing. It supports an additional includeViewParams attribute which includes all view parameters in the form's action URL:
<o:form includeViewParams="true">
Update: obtaining the view parameters of the current view programmatically (which is basically your 2nd question) should be done as follows:
Collection<UIViewParameter> viewParams = ViewMetadata.getViewParameters(FacesContext.getCurrentInstance().getViewRoot());
for (UIViewParameter viewParam : viewParams) {
String name = viewParam.getName();
Object value = viewParam.getValue();
// ...
}
Am I right that for solution 1 <f:ajax execute="#form" render="#form" /> to work one would also have to include something like
<f:param name="userId" value="#{userPageController.userId}"/>
inside the <h:commandButton>?
Like it is described in https://stackoverflow.com/a/14026995/811046
Has anyone managed to get nhibernate.search (Lucene) to work with S#arp Architecture? I think I have it all wired up correctly except Luke shows no records or indexes when I run my indexing method. The index files for the entity are created (segments.gen & segments_1) but both are 1kb in size which explains why Luke shows no data.
I execute no other code specific to getting search to work, am I missing some initialisation calls? I assume the listeners get picked up automatically by nhibernate.
In my Web project I have:
NHibernate.config
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.connection_string">Data Source=.\SQLEXPRESS;Database=MyDatabase;Integrated Security=True;</property>
<property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="show_sql">true</property>
<property name="generate_statistics">true</property>
<property name="connection.release_mode">auto</property>
<property name="adonet.batch_size">500</property>
<property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
<listener class='NHibernate.Search.Event.FullTextIndexEventListener, NHibernate.Search' type='post-insert'/>
<listener class='NHibernate.Search.Event.FullTextIndexEventListener, NHibernate.Search' type='post-update'/>
<listener class='NHibernate.Search.Event.FullTextIndexEventListener, NHibernate.Search' type='post-delete'/>
</session-factory>
</hibernate-configuration>
Web.Config
<configSections>
...
<section name="nhs-configuration" type="NHibernate.Search.Cfg.ConfigurationSectionHandler, NHibernate.Search" requirePermission="false" />
</configSections>
<nhs-configuration xmlns='urn:nhs-configuration-1.0'>
<search-factory>
<property name="hibernate.search.default.directory_provider">NHibernate.Search.Store.FSDirectoryProvider, NHibernate.Search</property>
<property name="hibernate.search.default.indexBase">~\Lucene</property>
</search-factory>
</nhs-configuration>
My entity is decorated as follows:
[Indexed(Index = "Posting")]
public class Posting : Entity
{
[DocumentId]
public new virtual int Id
{
get { return base.Id; }
protected set { base.Id = value; }
}
[Field(Index.Tokenized, Store = Store.Yes)]
[Analyzer(typeof(StandardAnalyzer))]
public virtual string Title { get; set; }
[Field(Index.Tokenized, Store = Store.Yes)]
[Analyzer(typeof(StandardAnalyzer))]
public virtual string Description { get; set; }
public virtual DateTime CreatedDate { get; set; }
...
}
And I run the following to create the index
public void BuildSearchIndex()
{
FSDirectory directory = null;
IndexWriter writer = null;
var type = typeof(Posting);
var info = new DirectoryInfo(GetIndexDirectory());
if (info.Exists)
{
info.Delete(true);
}
try
{
directory = FSDirectory.GetDirectory(Path.Combine(info.FullName, type.Name), true);
writer = new IndexWriter(directory, new StandardAnalyzer(), true);
}
finally
{
if (directory != null)
{
directory.Close();
}
if (writer != null)
{
writer.Close();
}
}
var fullTextSession = Search.CreateFullTextSession(this.Session);
// select all Posting objects from NHibernate and add them to the Lucene index
foreach (var instance in Session.CreateCriteria(typeof(Posting)).List<Posting>())
{
fullTextSession.Index(instance);
}
}
private static string GetIndexDirectory()
{
var nhsConfigCollection = CfgHelper.LoadConfiguration();
var property = nhsConfigCollection.DefaultConfiguration.Properties["hibernate.search.default.indexBase"];
var fi = new FileInfo(property);
return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fi.Name);
}
Found an answer to my question so here it is in case anyone else comes by this problem.
NHS configuration in web.config contained such lines:
<property name="hibernate.search.default.directory_provider">NHibernate.Search.Store.FSDirectoryProvider, NHibernate.Search</property>
<property name="hibernate.search.default.indexBase">~\SearchIndex</property>
First line should be removed because in this case NHS consider it as though index shares. It is known NHibernateSearch issue.
If the site is run from IIS, Network Service should have all permissions on search index directory.
Jordan, are you using the latest bits from NHContrib for NHibernate.Search? I just recently updated my bits and I am running into the same situation you are. It works for me on older bits, from about July. But I can't get my indexes to create either. Your config looks right, same as mine. And your indexing method looks good too.
Jordan, there is now an alternative to attribute based Lucene.NET mapping called FluentNHibernate.Search, this project is hosted on codeplex.
http://fnhsearch.codeplex.com/
public class BookSearchMap : DocumentMap<Book>
{
public BookSearchMap()
{
Id(p => p.BookId).Field("BookId").Bridge().Guid();
Name("Book");
Boost(500);
Analyzer<StandardAnalyzer>();
Map(x => x.Title)
.Analyzer<StandardAnalyzer>()
.Boost(500);
Map(x => x.Description)
.Boost(500)
.Name("Description")
.Store().Yes()
.Index().Tokenized();
}
}