Spring MVC - include static files / javascript , css - spring

I have created MVC application.
I want to include js or css file into jsp.
My static files ar under:
- webapp
-js/jquery.js
-WEB-INF|
|
- jsp/*.jsp
My code to include jquery is:
<script type="text/javascript" src="<c:url value="js/jquery.js" />"></script>
and i cant load the js file into view.
I see the logs with info:
WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/pool/js/jquery.js] in DispatcherServlet with name 'appServlet'
what means, that MVC try to map url to js file.
I think that there is something with my configuration, but i don't know what.
my web.xml is:
<?xml version="1.0" encoding="UTF-8"?>
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

add this to you confing and modify the location according to your need.
<mvc:resources mapping="/static/**" location="/WEB-INF/static/"/>
see this How to handle static content in Spring MVC?

Change your DispatcherServlet mapping to e.g:
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>*.jsp</url-pattern>
</servlet-mapping>
Or some other not conflicting url-pattern like *.htm or /controllers/*. Remember that from now on all your controllers will be available only through this pattern.
Now it is intercepting everything in your web application, including .js files, images, etc.
The same thing with hibernateFilter - you don't really need an open Hibernate session when fetching .js files, don't you?

Why not use the simple jsp core ?
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<link rel="stylesheet" type="text/css" href="<c:url value='/resources/css/bootstrap.css'/>" />

Use spring JSTL tags to include external script files or style sheets.
First you should include the the taglib in JSP as follows.
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
Then you can include extenal script file using,
<script type="text/javascript" src="<spring:url value="/js/jquery.js"/>"></script>

I agree with your answer. But in the style.css file declare url that relate to path of image.
--style.css--
.cwt-object0
{
display: block;
left: 2.62%;
margin-left: -1px;
position: absolute;
top: 43px;
width: 64px;
height: 64px;
background-image: url('/resources/images/object0.png');
background-position: 0 0;
background-repeat: no-repeat;
z-index: 0;
}
How to use tag <spring:url></spring:url> in style.css file to see in browser IE/Firefox
--jsp file ---
<link href="<spring:url value="/resources/style.css"/>" rel="stylesheet" type="text/css" media="screen">

add mvc:resources in your config file(*-servlet.xml), you can find it works

I just followed Mkyong Tutorial to place css, js, jquery & image files. Its working for me.
In servlet-context.xml
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/assets/" />
In JSP , import tag library
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
and add like
<link rel="stylesheet" href="<c:url value='/resources/css/custom.css'/>">

Related

Spring Web MVC Application Cannot Find Resources

I am using netbeans as my IDE for developing basic web application. I successfully added external files as resources such as pictures and CSS files. They were working fine untill today, suddenly they are not being found by netbeans. Following is the error I am getting when debugging
Failed to load resource: the server responded with a status of 405 (Method not allowed).
Here is how I have initialized the MVC resources in XML config file.
<mvc:resources mapping="/resources/**" location="/resources/" cache-period="31556926"/>
<mvc:annotation-driven />
And here is how I am using it, in JSP file.
<link rel="stylesheet" href='<c:url value="/resources/css/bootstrap.min.css"/>'>
So what could be wrong. Why it has stopped suddenly ? Thanks for any pointer.
======== EDIT ===========
Here is my web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Following (already shown) two lines are in applicationContext.xml
<mvc:resources mapping="/resources/**" location="/resources/" cache-period="31556926"/>
<mvc:annotation-driven />
And here is my controller.
#RequestMapping(value = "/myURL", method=RequestMethod.GET)
public String MyControllerGET(HttpServletRequest request, Model model)
{
// some code here....nothing fancy, just harcoding some values
}

Simple Spring Web Project Not Working

I've been trying to learn how to develop a Spring Web application and can't seem to get it working. Using the Spring Tool Suite, I created a new Spring Project using the Simple Spring Web Maven template, which basically is comprised of four files:
index.jsp:
<!DOCTYPE html>
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html>
<head>
<meta charset="utf-8">
<title>Welcome</title>
</head>
<body>
<c:url value="/showMessage.html" var="messageUrl" />
Click to enter
</body>
</html>
/WEB-INF/web.xml:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>spring-web-test</display-name>
<!--
- Location of the XML file that defines the root application context.
- Applied by ContextLoaderListener.
-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/application-config.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--
- Servlet that dispatches request to registered handlers (Controller implementations).
-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
/WEB-INF/mvc-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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.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.xsd">
<!-- Uncomment and your base-package here:
<context:component-scan
base-package="org.springframework.samples.web"/> -->
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- Example: a logical view name of 'showMessage' is mapped to '/WEB-INF/jsp/showMessage.jsp' -->
<property name="prefix" value="/WEB-INF/view/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
/WEB-INF/view/showMessage.jsp:
<!DOCTYPE html>
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<meta charset="utf-8">
<title>Welcome</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
This all seemed simple and basic enough, so I built it using Maven and packaged it into a WAR file. I then deployed it to a local TomEE 7 server, went to http://localhost:8080/spring-web-test-0.0.1-SNAPSHOT, and got to the very simple index.jsp page:
However, when clicking the link, which sends me to http://localhost:8080/spring-web-test-0.0.1-SNAPSHOT/showMessage.html, I get a 404 error from Tomcat:
I suspected it was because of the .html ending - based off what I understand of the dispatcher and view resolver, it would be looking for /WEB-INF/view/showMessage.html.jsp. However, trying to access http://localhost:8080/spring-web-test-0.0.1-SNAPSHOT/showMessage returns the same error. Looking at the Tomcat logs, I see
Nov 11, 2015 9:46:53 AM org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping found for HTTP request with URI [/spring-web-test-0.0.1-SNAPSHOT/showMessage.html] in DispatcherServlet with name 'dispatcherServlet'
Nov 11, 2015 9:46:55 AM org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping found for HTTP request with URI [/spring-web-test-0.0.1-SNAPSHOT/showMessage] in DispatcherServlet with name 'dispatcherServlet'
What am I doing wrong? The whole thing seems pretty simple, and I haven't even modified anything from the template Spring Tool Suite provides, so I'd have assumed it would work right out of the box. Unfortunately there doesn't seem to be a whole lot of resources online on developing Spring web applications for use in servlet containers, and of the ones I've found, nothing seemed to suggest I'm doing anything wrong.
Thanks.
Change your index.jsp to something like this
<c:url value="/showMessage" var="messageUrl" />
You don't need file extensions, because you've set them up in your mvc-config.xml.
Then you need a basic controller to handle the mapping. Something like this:
#Controller
public class WebController{
#RequestMapping(value = "/")
public String showMessage(){
return "index";
}
#RequestMapping(value = "/showMessage")
public String showMessage(){
return "showMessage";
}
}

How to access css file with Tomcat 6 and Spring 3.0.4

I try to access css file by:
<link rel="stylesheet" href="META-INF/resources/css/style.css" />
Structure:
springhibernate
-META-INF
-recources
-css
-style.css
-img
-WEB-INF
-classes
-jsp
web.xml
application-context.xml
web.xml part:
<servlet>
<servlet-name>test</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>test</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
How can I refer to a css file?
The META-INF directory is not accessible using an URL according to the specification. It's purpose is to hold information useful to Java archive tools, xml descriptors, etc.
Create separate top-level directory in your .war file to serve CSS, Javascript, HTML, etc. files.
Note: you can access everything in META-INF in your Java code, using ServletContext's getResource and getResourceAsStream calls. The limititation is that it cannot be referenced with a URL.

FKeditor and Spring MVC Maven integration step by step

I want to use Fckeditor in my spring mvc. Could you provide instruction or link to set up step by step?
I did below steps but when I run, 404 not found [/springmvc/fckeditor/editor/fckeditor.html ]is showing.
Could you check me what I am wrong and guide me?
Firstly, as per documentation I added below code in pom.xml.
<dependency>
<groupId>net.fckeditor</groupId>
<artifactId>java-core</artifactId>
<version>2.6</version>
</dependency>
And in web.xml file, I added below code.
<servlet>
<servlet-name>ConnectorServlet</servlet-name>
<servlet-class>
net.fckeditor.connector.ConnectorServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ConnectorServlet</servlet-name>
<url-pattern>
/resources/fckeditor/editor/filemanager/connectors/*
</url-pattern>
</servlet-mapping>
After that I download FCKeditor_2.6.8.zip file and extract in the src/main/resources folder.
In the jsp page, I added taglib, javascript and tag.
<%# taglib uri="http://java.fckeditor.net" prefix="FCK" %>
function FCKeditor_OnComplete(editorInstance) {
window.status = editorInstance.Description;
}
<FCK:editor instanceName="EditorDefault">
<jsp:attribute name="value">This is some <strong>sample text
</strong>. You are using <a href="http://www.fckeditor.net">
FCKeditor</a>.
</jsp:attribute>
</FCK:editor>
But Fckeditor is still not working.
Could you guide me which is wrong?
Thank you,
i have used ckeditor, below are configrations
<dependency>
<groupId>com.ckeditor</groupId>
<artifactId>ckeditor-java-core</artifactId>
<version>3.5.3</version>
</dependency>
in jsp file
<%# taglib prefix="ckeditor" uri="http://ckeditor.com"%>
<script type="text/javascript" src="%=request.getContextPath()%>/common/script/ckeditor/ckeditor.js"></script>
<form:textarea path="body" maxlength="5000" /> <ckeditor:replace replace="body" basePath="../ckeditor/" />
make sure you copy js files also and copy it and specify it in jsp

ActiveMQ AJax Client

I try to write a simple Ajax client to send and receive messages. It's successfully deployed but I have never received msg from the client. I am beating myself to think out what I am missing, but still can't make it work.
Here is my code:
I creat a dynamic web application named: ActiveMQAjaxService and put activemq-web.jar and all neccessary dependencies in the WEB-INF/lib folder. In this way, AjaxServlet and MessageServlet will be deployed
I start activemq server in command line: ./activemq => activemq successfully created and display:
Listening for connections at: tcp://lilyubuntu:61616
INFO | Connector openwire Started
INFO | ActiveMQ JMS Message Broker (localhost, ID:lilyubuntu-56855-1272317001405-0:0) started
INFO | Logging to org.slf4j.impl.JCLLoggerAdapter(org.mortbay.log) via org.mortbay.log.Slf4jLog
INFO | jetty-6.1.9
INFO | ActiveMQ WebConsole initialized.
INFO | Initializing Spring FrameworkServlet 'dispatcher'
INFO | ActiveMQ Console at http://0.0.0.0:8161/admin
INFO | Initializing Spring root WebApplicationContext
INFO | Connector vm://localhost Started
INFO | Camel Console at http://0.0.0.0:8161/camel
INFO | ActiveMQ Web Demos at http://0.0.0.0:8161/demo
INFO | RESTful file access application at http://0.0.0.0:8161/fileserver
INFO | Started SelectChannelConnector#0.0.0.0:8161
3) index.xml, which is the html to test the client:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript" src="amq/amq.js"></script>
<script type="text/javascript">amq.uri='amq';</script>
<title>Hello Ajax ActiveMQ</title>
</head>
<body>
<p>Hello World!</p>
<script type="text/javascript">
amq.sendMessage("topic://myDetector", "message");
var myHandler =
{
rcvMessage: function(message)
{
alert("received "+message);
}
};
function myPoll(first)
{
if (first)
{
amq.addListener('myDetector', 'topic://myDetector', myHandler.rcvMessage);
}
}
amq.addPollHandler(myPoll);
4) Web.xml:
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<display-name>ActiveMQ Web Demos</display-name>
<description>
Apache ActiveMQ Web Demos
</description>
<!-- context config -->
<context-param>
<param-name>org.apache.activemq.brokerURL</param-name>
<param-value>vm://localhost</param-value> (I also tried tcp://localhost:61616)
<description>The URL of the Message Broker to connect to</description>
</context-param>
<context-param>
<param-name>org.apache.activemq.embeddedBroker</param-name>
<param-value>true</param-value>
<description>Whether we should include an embedded broker or not</description>
</context-param>
<!-- servlet mappings -->
<!-- the subscription REST servlet -->
<servlet>
<servlet-name>AjaxServlet</servlet-name>
<servlet-class>org.apache.activemq.web.AjaxServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>MessageServlet</servlet-name>
<servlet-class>org.apache.activemq.web.MessageServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<!--
Uncomment this parameter if you plan to use multiple consumers over REST
<init-param>
<param-name>destinationOptions</param-name>
<param-value>consumer.prefetchSize=1</param-value>
</init-param>
-->
</servlet>
<!-- the queue browse servlet -->
<filter>
<filter-name>session</filter-name>
<filter-class>org.apache.activemq.web.SessionFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>session</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
After all of these, I deploy the web-app, and it's successfully deployed, but when I try it out in http://localhost:8080/ActiveMQAjaxService/index.html , nothing happens.
I can run the demo portfolioPublisher demo successfully at http://localhost:8161/demo/portfolio/portfolio.html, and see the numbers updated all the time. But for my simple web-app, nothing really works.
Any suggestion/hint is welcomed. Thanks so much
Lily
Try going to the management web console; web-page, and seeing if you can send a message to your broker from that context, that might go along way towards directing you towards the problem.
I set up the web.xml in web application as following and it works.
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>msg_tomcat_activemq</display-name>
<context-param>
<param-name>org.apache.activemq.brokerURL</param-name>
<param-value>tcp://192.168.1.105:61616</param-value>
</context-param>
<context-param>
<param-name>org.apache.activemq.embeddedBroker</param-name>
<param-value>true</param-value>
</context-param>
<servlet>
<servlet-name>AjaxServlet</servlet-name>
<servlet-class>org.apache.activemq.web.AjaxServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>MessageServlet</servlet-name>
<servlet-class>org.apache.activemq.web.MessageServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>AjaxServlet</servlet-name>
<url-pattern>/amq/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>MessageServlet</servlet-name>
<url-pattern>/message/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>session</filter-name>
<filter-class>org.eclipse.jetty.continuation.ContinuationFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>session</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.apache.activemq.web.SessionListener</listener-class>
</listener>
</web-app>

Resources