how to load js and css file from web content spring mvc - javascript

I am unable to load JS and CSS file from webcontent folder.My login page goes without formatting please suggest me how to load this I am not using maven.
Plz find the image.

1) Create "resources" folder.
2) Add this in your xml file:
<mvc:resources mapping="/resources/**" location="/resources/" />
3)"Use" it in your page:
<link href="<c:url value="/resources/name_of_file.css" />" rel="stylesheet">
If you use Java Config, something like this will do the job:
#Configuration
#EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}
}

Related

Blazor WebAssembly load different scripts for specific Environment

I'm currently working on a .NET Standard 2.1 Blazor WebAssembly application. I try to include or exclude JavaScript files in my index.html according to an environment variable.
The Blazor WebAssembly App is NOT Asp.NET Core hosted.
In .NET Core there are usually Environment Tag Helpers like in the following example:
<environment include="Development">
<script src="js/app.js"></script>
<script src="js/helpers.js"></script>
</environment>
<environment exclude="Development">
<script src="js/site.min.js"></script>
</environment>
As already discussed in this question Blazor WebAssembly Environment Variables, the Environment Tag Helpers are server side code and thus don't work in Blazor WASm.
Now I try to find a good solution to include/exclude JavaScript files according to the Environment variable in Blazor WebAssembly.
The first idea was, similar like for CSS, to create a component called <Scripts> to load the different script files on the index.html like this:
#using Microsoft.AspNetCore.Components.WebAssembly.Hosting
#inject IWebAssemblyHostEnvironment hostEnv
#*Check the environment value*#
#if (hostEnv.IsDevelopment())
{
<script src="js/app.js"></script>
<script src="js/helpers.js"></script>
}
else
{
<script src="js/site.min.js"></script>
}
#code {}
Unfortunately this doesn't work, because the <script> Element is not allowed to be used in a Blazor component (.razor file).
The following error occurs: The script element allows authors to include dynamic script and data blocks in their documents. The element does not represent content for the user. ... Script tags should not be placed inside components because they cannot be updated dynamically. To fix this, move the script tag to the 'index.html' file or another static location. ... https://go.microsoft.com/fwlink/?linkid=872131
How do you load different scripts according to the Environment Variable i.e. Development, Production or Staging in Blazor Webassembly?
Do you know how to solve this problem?
I wanted to add Tailwind CDN script tag just during development. I ended up using the solution below:
index.html
<script src="_framework/blazor.webassembly.js"></script>
<script>
// If localhost, add tailwind CDN (or any other script that you want)
if (window.location.hostname == 'localhost') {
var customScript = document.createElement('script');
customScript.setAttribute('src', 'https://cdn.tailwindcss.com');
document.head.appendChild(customScript);
}
</script>
Simply copy your index.html code in a .cshtml (named BlazorApp.cshtml in the following sample) in your server project and fallback to this page.
public void Configure(IApplicationBuilder app)
{
...
app.UseEndpoints(endpoints =>
{
...
endpoints.MapFallbackToPage("/BlazorApp");
}
}
And update the code with <environment> tags for your conveniance.
Please check the solution in this answer (same question as you linked above) and that seems to work.
Basically the workaround is to use this in a new component called Head.razor as per the solution:
#inject IWebAssemblyHostEnvironment hostEnv
#if (hostEnv.IsDevelopment())
{
<title>BlazorWasmApp - In Debug</title>
<link href="css/debug.css" rel="stylesheet" />
}
else
{
<title>BlazorWasmApp - Not Debug</title>
<link href="css/live.css" rel="stylesheet" />
}
New Head.razor component:
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("app");
//Add the Head to root components
builder.RootComponents.Add<Head>("head");
builder.Services.AddTransient(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
await builder.Build().RunAsync();
}

Include static files in a reusable Razor Class Library

I am trying to make a reusable class library (RCL) that I can use in several ASP.NET Core MVC projects. So far so good… until I try to include the required JavaScript in the RCL. There is little-to-no documentation about this topic. My best shot was to try this example.
But when I do, I get the following error when I build the library:
This is the project file and the structure of the library:
Any help is appreciated.
Now that I have some spare time I will answer my own question. Maybe it will useful for someone.
Finally I solved this problem using EmmbededResources without the EmbeddedFilesManifest as ianbusko pointed out in Github.
First I created an extension for the IApplicationBuilder class:
namespace Dashboard.Lib.Extensions
{
public static class IApplicationBuilderExtension
{
public static void UseDashboardScripts(this IApplicationBuilder builder)
{
var embeddedProvider = new EmbeddedFileProvider(typeof(Areas.Dashboard.ViewComponents.DashboardViewComponent)
.GetTypeInfo().Assembly, "Dashboard.Lib.Scripts");
builder.UseStaticFiles(new StaticFileOptions()
{
FileProvider = embeddedProvider,
RequestPath = new PathString("/Scripts")
});
}
}
}
Then I added the javascript files to the project file:
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
<GenerateEmbeddedFilesManifest>false</GenerateEmbeddedFilesManifest>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.1.3" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.1.1" />
<PackageReference Include="Microsoft.Extensions.FileProviders.Embedded" Version="2.1.1" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Scripts/**/**/**/*" Pack="true" />
</ItemGroup>
In the RCL view the javascript is included as follows:
#section Scripts{
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript" src="~/Scripts/pagination.js"></script>
<script type="text/javascript" src="~/Scripts/checkdigit-validator.js"></script>
<script type="text/javascript" src="~/Scripts/rut-validation.js"></script>
}
Finally in the Statup.cs in the main MVC project you just have to include the following:
app.UseStaticFiles();
app.UseDashboardScripts();

How to include external JS file in JSP file in Spring WebMVC framework?

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

How to include js files in the view. ASP.NET MVC 4

I wonder why my js file work when I call it in the view:
#section Scripts {
<script>
function myFunction() {
alert("Hello1");
}
</script>
}
but does not work when I call it:
#section Scripts {
<script type="text/javascript" src="~/Views/Home/script.js"></script>
<script>
myFunction();
</script>
}
It's because .js files are not accessible in the ~/Views/ folder. You have to enable it.
To enable access to .js files in the Views folder, you can add the following to your Views' folder's web.config directly under the handlers tag:
<add name="JavaScriptHandler"
path="*.js"
verb="*"
preCondition="integratedMode"
type="System.Web.StaticFileHandler" />
Alternatively put your script into the ~/Scripts/ folder and reference it like such:
#Scripts.Render("~/Scripts/script.js")
Its better practice to place your Js file in Script folder and access it from there. You could write this code in view's head to use the js file
#Scripts.Render("~/Scripts/script.js")
you have to add your script in the Bundle config :
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js", "~/Views/Home/script.js"));
this worked for me
You should Add rendersection to your Layout Page which your view using.
#RenderSection("scripts", required: false)

Load HTML in WebView with local css and js

I am displaying a webview with a remote html content get as a string from a remote server.
I store the html locally for a no connection use of my application.
Moreover I also store a .js script and a .css style file locally. These files can be updated by the server.
I store all these files at the following paths :
context.getFilesDir()+"content.css"
context.getFilesDir()+"content.js"
In the html string, css and js are referenced like this :
<link rel="stylesheet" href="/content.css" type="text/css" media="screen">
<script src="/content.js"></script>
I load the html using
this.webView.loadDataWithBaseURL(getFilesDir().getAbsolutePath(), html, "text/html", "utf-8", "about:blank");
But the style and the js are not taken into account, so I think something is wrong with the path I use to reference them, or to load the webView. So what is the way to do this ? I found many answers that use the "assets" folder but I do not want to use it since I have to update the css and the js from the server.
Finally I have found the solution :
The css (or js) file is saved in local using this method :
public static void writeToFile(Context context, String content, String title) throws IOException
{
OutputStreamWriter osw = new OutputStreamWriter(context.openFileOutput(title,Context.MODE_WORLD_READABLE));
osw.write(content);
osw.close();
}
Then I refer it in the html file using
<link rel="stylesheet" href="content.css" type="text/css" media="screen">
<script src="content.js"></script>
And finally I have opened the webview using :
this.webView = (WebView) findViewById(R.id.webview);
this.webView.getSettings().setJavaScriptEnabled(true);
this.webView.getSettings().setPluginsEnabled(true);
this.webView.setHorizontalScrollBarEnabled(false);
this.webView.setVerticalScrollBarEnabled(true);
this.webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
this.webView.setWebViewClient(this.controller.getWebViewClient());
String basePath = "file://"+getFilesDir().getAbsolutePath()+"/";
this.webView.loadDataWithBaseURL(basePath, data, "text/html", "utf-8", "about:blank");

Categories

Resources