I'm building Web application using AngularJs, trying to use angular-translate for my app.
Here is Doc:
http://www.ng-newsletter.com/posts/angular-translate.html
$translateProvider.useStaticFilesLoader({
prefix: 'assets/resources/',
suffix: '.json'
});
I have 2 json file in my project directory
webapp/assets/resources/locale-en_US.json
webapp/assets/resources/locale-ru_RU.json
When I Run my app in browser, I'm getting this error
Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:8080/assets/resources/locale-ru_RU.json
I tried to load .js file and also .jpg from the same directory where is located my json files
webapp/assets/resources/foo.jpg
everything works fine, I cant load only JSON files from local. I Tried to make $http request but no result.
$http.get('assets/resources/locale-en_US.json' ).success(function(data) {
console.log(data);
});
Looks like my project ignores json files from local. I made researchs and fount some suggestions to add mapping to web.xml. No Result
<mime-mapping>
<extension>json</extension>
<mime-type>application/json</mime-type>
</mime-mapping>
Any Idea what to Do?
Regards,
Gari.E
I had servlet-mapping in my web.xml
<servlet-mapping>
<servlet-name>shemoGeServlet</servlet-name>
<url-pattern>*.json</url-pattern>
</servlet-mapping>
which was searching jsno files in WEB-INF directory, but my jsno files were in assets directory. Here is my servlet-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<mvc:annotation-driven/>
<mvc:resources location="/assets" mapping="/assets/**"/>
<context:component-scan base-package="ge.shemo"/>
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1" />
<property name="contentNegotiationManager">
<bean class="org.springframework.web.accept.ContentNegotiationManager">
<constructor-arg>
<bean class="org.springframework.web.accept.PathExtensionContentNegotiationStrategy">
<constructor-arg>
<map>
<entry key="json" value="application/json"/>
<entry key="xml" value="application/xml"/>
</map>
</constructor-arg>
</bean>
</constructor-arg>
</bean>
</property>
<property name="defaultViews">
<list>
<!-- JSON View -->
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
<bean class="org.springframework.web.servlet.view.xml.MarshallingView">
<constructor-arg>
<bean class="org.springframework.oxm.xstream.XStreamMarshaller">
<property name="autodetectAnnotations" value="true" />
</bean>
</constructor-arg>
</bean>
</list>
</property>
</bean>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource" p:basename="messages"></bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" p:order="0"/>
</beans>
That's why I was getting
Failed to load resource: the server responded with a status of 404 (Not Found)
I removed servlet and the problem gone
<servlet-mapping>
<servlet-name>shemoGeServlet</servlet-name>
<url-pattern>*.json</url-pattern>
</servlet-mapping>
Related
I have been trying out Apache Synapse and been trying to use the JavaScript mediator to set the JSON payload. But the ScriptMessageContext class doesn't contain any method for reading a JSON payload or setting a JSON payload. But there has been numerous examples of setting and getting JSON Payload in WSO2 such as mc.getPayloadJSON(); and mc.setPayloadJSON(response). Is there anyway to workaroud this in Apache Synapse?
I found the answer for myself.Synapse process every data by converting it into soap.So first I needed to convert the flow flie to soap. Then processed the data using javascript and convert the script back to json using xslt.
The complete xml code is shown below.Here I used synapse as proxy to send a get response from another server. then the data from that api is converted to soap and then processed in javascript and converted back from soap to json and send back to client.
<definitions xmlns="http://ws.apache.org/ns/synapse">
<localEntry key="jsonScript" src="file:repository/conf/sample/resources/script/sampleJson.js"/>
<proxy name="SampeJsonProxy">
<target>
<endpoint>
<address uri="http://localhost:8081/kafka/publish/hello" format="json" methods="GET"/>
</endpoint>
<inSequence>
<log level="full"/>
</inSequence>
<outSequence>
<xslt key="in_transform"/>
<property name="messageType" scope="axis2" value="text/xml"/>
<script language="js" key="jsonScript" function="transformResponse"/>
<xslt key="out_transform"/>
<property name="messageType" scope="axis2" value="application/json"/>
<send/>
</outSequence>
</target>
</proxy>
<localEntry key="in_transform">
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:fn="http://www.w3.org/2005/02/xpath-functions"
xmlns:m0="http://services.samples" version="2.0" exclude-result-prefixes="m0 fn">
<xsl:output method="xml" omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="*">
<xsl:element name="{local-name()}" namespace="http://services.samples">
<xsl:copy-of select="attribute::*"/>
<xsl:apply-templates/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
</localEntry>
<localEntry key="out_transform">
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" version="1.0" encoding="UTF-8"/>
<xsl:template match="*">
<xsl:element name="{local-name()}">
<xsl:apply-templates/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
</localEntry>
</definitions>
I have tried below answer but it didn't work..
How include an external JS file in a JSP page
I have been searching on google but couldn't find anything useful...my JS file is at same level as that of WEB-INF..any help would be appreciated...
Below is the code that I'm using to include my JS file in JSP :-
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.18.0/jquery.validate.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/formValidation.js"></script>
below code is in web.xml :-
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</context-param>
Below code is in dispatcher-servlet.xml file :-
<context:component-scan base-package="com.programcreek.helloworld.controller" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
You might want to add ResourceHandler to resolve your static resources like js/css directory
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/js/**")
.addResourceLocations("/js/")
.setCachePeriod(3600)
.resourceChain(true)
.addResolver(new PathResourceResolver());
}
This method apply for java configuration class extends WebMvcConfigurerAdapter
The xml version should look like this
<mvc:resources mapping="/js/**" location="/js/"/>
This will resolve any .js file under /webapp/js/ directory, using something like below in .jsp file
<script src="js/custom.js"></script>
for help you can see this github link click here
I hope it will help you
and this is the project structure
I'm getting what appears to me to be a strange error when I load my JSP. Spring is a Java framework, so why would I need a mapping for a JavaScript file? The JavaScript in my page is not working.
org.springframework.web.servlet.PageNotFound.noHandlerFound No mapping found for HTTP request with URI [/ghs1986/js/javascript.js] in DispatcherServlet with name 'ghs1986'
For what it's worth, here is my applicationContext.xml.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
<mvc:annotation-driven />
<mvc:resources location="WEB-INF/pages/images/" mapping="/images/**" />
<mvc:view-controller path="/" view-name="home" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp" />
</bean>
This is how I'm trying to access the JavaScript in my JSPs.
<script type="text/javascript" src="js/javascript.js"></script>
And here is my web.xml.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<web-app version="4.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_4_0.xsd">
<display-name>Granada High School Class of 1986</display-name>
<servlet>
<servlet-name>ghs1986</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ghs1986</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>home.jsp</welcome-file>
</welcome-file-list>
</web-app>
In much the same way as you have a mapping to allow the spring controller to know about images with
<mvc:resources location="WEB-INF/pages/images/" mapping="/images/**" />
you need to add a similar mapping to let it know about your javascript files. Something like,
<mvc:resources location="WEB-INF/pages/js/" mapping="/js/**" />
The issue is the same in both cases, the front end controller of Spring doesn't know how to find your js files without that.
I'm writing a webapp with Spring MVC, Velocity and AngularJS. I face a problem with I18n strings.
In html output sometimes translated tags are static so i can use a custom velocity call to put a translated text from a properties files, something like this:
<h2>#springMessageText('main.section.title')</h2>
But sometimes the text in render dinamically in client using javascript so i have many translations_xx_XX.js files to store those translations:
var _i18n = {
'lang': 'gl-ES',
'lang.short': 'gl',
'serverError.message':'Erro no servidor.',
'yes': 'Sí',
'no': 'Non',
...
}
So i load those translations in client with whith a javascript function when needed:
myCtrl.i18n['serverError.message'];
All works fine but i face the problem that many labels are duplicated in both *.properties files and translations_xx_XX.js files and it's hard to maintain.
So my question: Is there a way to render inside js files using velocity tags, so the translations_xx_XX.js file is filled with translations from *.properties files? Somthing like this:
var _i18n = {
'lang': '#springMessageText("lang")',
'lang.short': '#springMessageText("lang.short")',
...
}
Doing this i have to deal only with one source for translation tags.
Edited:
I found where the problem is. Velocity was configured along with Spring MVC in webapp-config.xml:
<bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
<property name="resourceLoaderPath" value="/view/"/>
<property name="velocityProperties">
<props>
<prop key="input.encoding">utf-8</prop>
<prop key="output.encoding">utf-8</prop>
</props>
</property>
</bean>
<!-- bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
<property name="cache" value="true"/>
<property name="prefix" value=""/>
<property name="suffix" value=".html"/>
<property name="exposeSpringMacroHelpers" value="true"/>
<property name="contentType" value="text/html; charset=UTF-8"/>
<property name="toolboxConfigLocation" value="/WEB-INF/velocity-toolbox.xml" />
</bean>
So only html files under /view folder are parsed by Velocity. My question is if there is a way to add the same Velocity behaviour to *.js files under /resources folder? Can i define two velocityConfig and two viewResolver?
Possibly you can move the translations_xx_XX.js into the Velocity template folder. And the translations_xx_XX.js needs to be imported in the .vm file.
P.S. This solution assumes that the view is generated using Velocity View Servlet.
Edited: 05:22AM 28 Aug,2015 IST
As mentioned in your post, <property name="resourceLoaderPath" value="/view/"/>, here view is Velocity template folder/directory. You will have to move the translations_xx_XX.js file(s) into this folder. Now you need to use the .vm to import the .js so that velocity macros could be parsed. e.g.
page.vm:
<script>
#parse("translations_xx_XX.js")
</script>
Can i define two viewResolver?
Yes, all you need to do is add <property name="order" value="<order_no>"/>, lower order value has a higher priority, e.g.
<bean class="org.springframework.web.servlet.view.XmlViewResolver">
<property name="location">
<value>/WEB-INF/spring-views.xml</value>
</property>
<property name="order" value="0" />
</bean>
<bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basename" value="spring-views" />
<property name="order" value="1" />
</bean>
Finally i managed to make it possible.
First of all, you need two view resolvers configured in the Spring web configuration file:
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
<property name="resourceLoaderPath" value="/view/"/>
<property name="velocityProperties">
<props>
<prop key="input.encoding">utf-8</prop>
<prop key="output.encoding">utf-8</prop>
</props>
</property>
</bean>
<bean id="htmlViewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
<property name="order" value="0" />
<property name="cache" value="true"/>
<property name="prefix" value=""/>
<property name="suffix" value=".html"/>
<property name="exposeSpringMacroHelpers" value="true"/>
<property name="contentType" value="text/html; charset=UTF-8"/>
<property name="toolboxConfigLocation" value="/WEB-INF/velocity-toolbox.xml" />
</bean>
<!-- Resolver velocity for js files to be rendered on server side. Should be included in /view/ to avoid problems with other static content inside /resources/ for example. -->
<bean id="jsViewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
<property name="order" value="1" />
<property name="cache" value="true"/>
<property name="prefix" value=""/>
<property name="suffix" value=".js"/>
<property name="exposeSpringMacroHelpers" value="true"/>
<property name="contentType" value="text/javascript; charset=UTF-8"/>
<property name="toolboxConfigLocation" value="/WEB-INF/velocity-toolbox.xml" />
</bean>
It's very important to notice that you must put the js you want to render inside the resourceLoaderPath defined in the VelocityConfigurer. Also notice that this must not clash with the mvc:resources path to avoid Spring serve your js file statically.
Then create your js file as a normal velocity file (in this case inside the /views/ forder). In my case it declares a hash of translations depending on server locale:
var _i18n = {
'lang': '#springMessageText("lang")',
'lang.short': '#springMessageText("lang.short")',
'serverError.message': '#springMessageText("serverError.message")',
'entities.displayName': '#springMessageText("entities.displayName")',
...rest of translations...
};
Finally you need to do that that spring web render this view with Velocity so you need to add to a controller one mapping like this:
#RequestMapping("/translations.js")
public String getTranslationsJs(HttpServletRequest request, Locale locale) {
return "/translations";
}
This way, when making a reference to this js file on your html:
<script type="text/javascript" src="/translations.js"></script>
Spring web renders the file using velocity returning a content like this:
var _i18n = {
'lang': 'en-US',
'lang.short': 'en',
'serverError.message': 'Server error.',
'entities.displayName': 'Company name'
...
};
I have written an html file using jQuery to read a JSON file. It works fine by itself; I tested it using Safari. However, when I try to use the exact same code in WebMatrix, it gives me an error, saying the JSON file cannot be found. I checked and the file is there.
Here is a simple version of the offending code. (The same comments apply: it works by itself in Safari but says "file not found" when used in WebMatrix.)
Can someone help me?
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
<script>
var Email=new Array();
var i=0;
var email;
$.getJSON('MoodMinder.json', function(data) {
$.each(data.User, function(i, f) {
Email[i]=f.Email;
i++;
})
email="<p>" + Email[0] + "</p>";
$(email).appendTo("#email");
});
</script>
</head>
<body>
<div id="email"></div>
</body>
</html>
Here is the JSON:
{
"User":[
{"Email":"cklann999#gmail.com"}
]
}
And here is the Web.config file (added section recommended by Nidzix):
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<customErrors mode="Off"></customErrors>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SqlServerCe.4.0" />
<add invariant="System.Data.SqlServerCe.4.0" name="Microsoft® SQL Server® Compact 4.0" description=".NET Framework Data Provider for Microsoft SQL Server Compact" type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
</DbProviderFactories>
</system.data>
<system.webServer>
<staticContent>
<mimeMap fileExtension=".json" mimeType="application/json"></mimeMap>
</staticContent>
</system.webServer>
</configuration>
You have to have configuration file called Web.config in the root folder, containing this piece fo code:
<?xml version="1.0"?>
<configuration>
<system.webServer>
<staticContent>
<mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>
</system.webServer>
</configuration>