I am trying to make an ajax call from a jsp page using the spring MVC framework to fetch some data from the server but I am getting the following error.
10-Dec-2015 11:53:05.349 WARNING [http-nio-8084-exec-14] org.springframework.web.servlet.PageNotFound.noHandlerFound No mapping found for HTTP request with URI [/EIMEnterprise/[object%20Object]] in DispatcherServlet with name 'spring-dispatcher'
No matter what I have as my URL parameter for my $.get call, it seems to attach an [object%20Object]] value at the end. Here is my Ajax Controller Class
#Controller
public class AjaxController {
#RequestMapping(value="/viewhiers.html", method=RequestMethod.GET)
public #ResponseBody ArrayList<HierarchyBean> getHiersViaAjax(#RequestParam("versionID") int versionID) {
//return an arraylist of HierarchyBean
}
}
Below is my web.xml file
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>EIMEnterprise</display-name>
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
And below is my jsp page with the following code
<script type="text/javascript">
$(document).ready(function() {
$('#versiontab tr td').click(function() {
//alert("Hello");
//highlight the current row and disable highlight on the other rows
$(this).closest("tr").addClass('highlightblue').siblings().removeClass('highlightblue');
//make an ajax call to populate the hierarchies
$.get({
url: '/EIMEnterprise/viewhiers.html?versionID=1',
type: 'GET',
success: function(data) {
alert("success");
/*
$.each(data, function (index, value) {
alert(index + " " + value);
});*/
}
});
});
});
</script>
And here is my spring-dispatcher-servlet.xml file
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!--Scan this package for any controller annotations-->
<context:component-scan base-package="com.eimenterprise.controllers" />
<!--Used for using pathvariable with map-->
<mvc:annotation-driven />
<mvc:resources location="/resources/" mapping="/resources/**" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
Please let me know what I am doing wrong as it seems to append an object value at the end of the urL instead of sending it to the correct controller and thus cannot find the mapping.
I was passing the parameters wrong in $.get. This is resolved.
Should use $.get in the following way.
$.get( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
alert( "Load was performed." );
});
Related
My ajax is performing successfully because it deletes the row from database :
#Controller
...
#ResponseBody
#RequestMapping(value = "/ajaxDeleteUser", method = RequestMethod.POST)
public ModelAndView ajaxDelUser(HttpServletRequest request) {
int userId = Integer.parseInt(request.getParameter("id"));
userDao.delete(userId);
return new ModelAndView("redirect:/");
}
...
At the view :
<c:url value="/" var="home" scope="request" />
$.ajax({
data: {"id":data},
type: "POST",
url: "${home}"+"ajaxDeleteUser",
async: false
});
The problem is that after the ajax is complete then I saw the row on the list ! So how to redirect to the list actual page after ajax complete ?
UPDATE :
Here is servlet-context.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
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">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.ambre.hib" />
</beans:beans>
And here is web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 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>
</web-app>
Consider using "success" event: http://api.jquery.com/Ajax_Events/
$.ajax({
data: {"id":data},
type: "POST",
url: "${home}"+"ajaxDeleteUser",
async: false,
success: function(result) {
location.href = "your_location"
}
});
You've got two options here. First, you can redirect on the front end after the ajax completes using the ajax success function like below:
success: function(result) {
location.href = "your_location"
}
Or preferably you can do it on the backend using spring mvc do the job. For this purpose remove the #Responsebody cuz you don't need it (you are not returning anything) and also change the return type to a String like below.
#RequestMapping(value = "/ajaxDeleteUser", method = RequestMethod.POST)
public String ajaxDelUser(HttpServletRequest request) {
//your stuff goes here
....
//important line
return "redirect:/index.html";
}
Here I am using index.html but change the name to your preferred page. As long as you've configured the Spring view resolver properly then it should work by itself. If you've put a suffix in the view resolver (for example .jsp) then you should return just the name of the page without the suffix and spring will figure out the page automatically like below
return "redirect:/index"; //equals index.jsp
You can Use this.This will redirect after response has arrived.
$.ajax({
data:{"id":data},
type: "POST",
url: "${home}"+"ajaxDeleteUser",
async: false,
success: function(result) {
var link = "http://www.sample.com";
$(location).attr('href',link);
});
Here's the story, I have a single page application, where I want to call a servlet from an ajax object, and have the text returned from the servlet be displayed on my webpage.
Here's an example of how I could do it:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src="jquery.js" type="text/javascript" ></script>
<script type="text/javascript">
function submittext() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "submit", true);
xmlhttp.send();
document.getElementById("myTextField").innerHTML = xmlhttp.responseText;
}
</script>
</head>
<body>
<input type="text" name="mytext" />
<br>
<button onClick="submittext()">Submit</button>
<br>
<div id="myTextField"></div>
</body>
</html>
web.xml
<servlet>
<servlet-name>testdogservlet</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>testdogservlet</servlet-name>
<url-pattern>/submit</url-pattern>
</servlet-mapping>
testdogservlet-servlet
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="world.hello.mytest" />
<bean id="viewResolver"
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>
</beans>
MyServlet.java
package world.hello.mytest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class MyServlet {
private String savedText;
#RequestMapping("/submit")
public ModelAndView submitText()
{
return new ModelAndView("text", "barModelName", "submission successful ModelObject");
}
}
text.jsp
${barModelName};
This solution works fine. You click the submit button, and it changes the div contents to text contained in text.jsp.
The question is, it seems redundant to have an entire page dedicated as just the container for holding this text. Is there a tidier solution for doing this?
A spring controller can pass in the HttpServletRequest and HttpServletReponse into the mapped methods.
Modify your method to accept these two arguments, and then you can directly modify the HttpServletResponse.
#RequestMapping("/submit")
private void submit(HttpServletRequest request, HttpServletResponse response) throws IOException
{
OutputStream os = response.getOutputStream();
os.write("submission successful ModelObject".getBytes());
os.close();
os.flush();
}
Just replace the return object to something like this:
private String savedText;
#RequestMapping("/submit")
public String submitText()
{
return "submission successful ModelObject";
}
My advice is convert it to JSON object using either #RestController or Jackson JSON converter.
#RequestMapping("/submit")
#ResponseBody
public String submitText()
{
return "submission successful ModelObject";
}
For Last couple of days i have been trying spring 4 websocket . But There is a problem
I am using apache-tomcat-8 and this is not a maven project.
Here are my snippets
index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Hello WebSocket</title>
<script type="text/javascript" src="./js/sockjs-0.3.4.js"></script>
<script type="text/javascript" src="./js/stomp.js"></script>
<script type="text/javascript">
var stompClient = null;
function setConnected(connected) {
document.getElementById('connect').disabled = connected;
document.getElementById('disconnect').disabled = !connected;
document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
document.getElementById('response').innerHTML = '';
}
function connect() {
var socket = new SockJS("<c:url value='/hello'/>");
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
setConnected(true);
console.log('Connected: ' + frame);
window.alert('Connected: ' + frame);
stompClient.subscribe('/topic/greetings', function(greeting){
showGreeting(JSON.parse(greeting.body).content);
});
});
}
function disconnect() {
if (stompClient != null) {
stompClient.disconnect();
}
setConnected(false);
console.log("Disconnected");
}
function sendName() {
var name = document.getElementById('name').value;
stompClient.send("/app/hello", {}, JSON.stringify({ 'name': name }));
}
function showGreeting(message) {
var response = document.getElementById('response');
var p = document.createElement('p');
p.style.wordWrap = 'break-word';
p.appendChild(document.createTextNode(message));
response.appendChild(p);
}
</script>
</head>
<body>
<noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websocket relies on Javascript being enabled. Please enable
Javascript and reload this page!</h2></noscript>
<div>
<div>
<button id="connect" onclick='connect();'>Connect</button>
<button id="disconnect" disabled="disabled" onclick="disconnect();">Disconnect</button>
</div>
<div id="conversationDiv">
<label>What is your name?</label><input type="text" id="name" />
<button id="sendName" onclick="sendName();">Send</button>
<p id="response"></p>
</div>
</div>
</body>
</html>
WebSocketConfig.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:websocket="http://www.springframework.org/schema/websocket"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/websocket
http://www.springframework.org/schema/websocket/spring-websocket.xsd">
<websocket:message-broker application-destination-prefix="/app">
<websocket:stomp-endpoint path="/hello">
<websocket:sockjs/>
</websocket:stomp-endpoint>
<websocket:simple-broker prefix="/topic"/>
</websocket:message-broker>
</beans>
HelloMessage.java
package com.springws.test;
public class HelloMessage {
private String name;
public String getName() {
return name;
}
}
Greeting.java
package com.springws.test;
public class Greeting {
private String content;
public Greeting(String content) {
this.content = content;
}
public String getContent() {
return content;
}
}
GreetingController.java
package com.springws.test;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
#Controller
public class GreetingController {
#MessageMapping("/hello")
#SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception {
System.out.println(message.getName());
return new Greeting("Hello, " + message.getName() + "!");
}
}
web.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID"
version="3.0">
<display-name>CRUDWebAppMavenized</display-name>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value> /WEB-INF/WebSocketConfig.xml</param-value>
</context-param>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
spring-servlet.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:p="http://www.springframework.org/schema/p"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
<context:annotation-config />
<context:component-scan base-package="com.springws.test" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
<tx:annotation-driven />
</beans>
WebSocketConfig.java
package com.springws.test;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
#Configuration
#ComponentScan(basePackages = {"com.springws.test"})
#EnableWebSocketMessageBroker
#EnableWebMvc
#Controller
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
#Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
#Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/hello").withSockJS();
}
}
Libraries
But in browser console
its giving the following output
Opening Web Socket...
stomp.js:145 Web Socket Opened...
stomp.js:145 >>> CONNECT
accept-version:1.1,1.0
heart-beat:10000,10000
Whoops! Lost connection to undefined
why its losing connection ?
I Found the Answer. I missed three libraries.
jackson-annotations-2.5.1.jar ,
jackson-core-2.5.1.jar ,
jackson-databind-2.5.1.jar
and i removed the old library jackson-annotations-2.1.2.jar and added these three libraries . And Now its workig like a deram
I have a view 'hi.jsp' with user name and password text fields. I need to submit 'hi.jsp' to 'LoginController.java'. If there is any error in the data submitted then 'LoginController.java' must redirect the request back to 'hi.jsp' (with text fields retaning the entered data) with respective error messages. After changing data and re-submitting 'hi.jsp' I get 404 error.
So the first submission is successful however problem occurs during second submission.
The source code of files is mentioned below:
hi.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="s" %>
<%# page session="false" %>
<html>
<body>
<s:form method="POST" modelAttribute="loginObj" action="login/validatelogin">
<label for="userName">UserName</label>
<s:input path="userName" id="userName" size="15"/><br>
<div style="{color:red}"> <s:errors path="userName"></s:errors></div>
<label for="password">Password</label>
<s:input path="password" id="password" size="15" /><br>
<s:errors path="password"></s:errors>
<input name="submit" type="submit" value="login"/>
</s:form>
</body>
</html>
LoginController.java
package rajeev.spring.spitter.mvc.controller;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#RequestMapping("/login")
public class LoginController {
#RequestMapping(value="/validatelogin", method=RequestMethod.POST)
public String validateLogin(#Valid #ModelAttribute("loginObj") LoginBean loginObj, BindingResult bindingResult)
{
System.out.println(bindingResult.hasErrors());
if(bindingResult.hasErrors())
{
return "hi";
}
return "home";
}
}
spitter-servlet.xml (spring configuration)
<?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"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.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.0.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="rajeev.spring.spitter.mvc.controller"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
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 Hello World</display-name>
<welcome-file-list>
<welcome-file>/</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>springDispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spitter-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springDispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
During the second submission of 'hi.jsp' tomcat log also displays a warning:
WARNING: No mapping found for HTTP request with URI [/SpringMVC/login/login/validatelogin] in DispatcherServlet with name 'springDispatcher'
It seems that during second submission of 'hi.jsp' an extra '/login' is getting appended to the submission path of the form.
Kindly suggest if something is wrong with above code or do I need to modify it to make it working.
Thanks for your help.
This is because the relative form post URL changed when you map your handler method into a different URL
<s:form method="POST" modelAttribute="loginObj" action="login/validatelogin">
Common solution to this problem is to use absolute path, but instead of hardcoding, lookup your context-path using
<c:set var="root" value="${pageContext.request.contextPath}"/>
Then on your form
<s:form method="POST" modelAttribute="loginObj" action="${root}/login/validatelogin">
Other option you might consider is to use Post-Redirect pattern in your controller handler method to avoid switching the URL
public String validateLogin(#Valid #ModelAttribute("loginObj") LoginBean loginObj, BindingResult bindingResult) {
....
return "redirect:/login";
}
Try this:
<c:url var="myAction" value="/login/validatelogin"/>
<s:form method="POST" modelAttribute="loginObj" action="${myAction}">
I'm trying to get a correct current URL in JSP in Spring webapp. I'm trying to use the following fragment in the JSP file:
${pageContext.request.requestURL}
The issue is that the returned URL contains prefix and suffix defined by UrlBasedViewResolver. For example the correct URL is:
http://localhost:8080/page
But the returned one is:
http://localhost:8080/WEB-INF/jsp/page.jsp
The best way would be to use EL like this:
${requestScope['javax.servlet.forward.request_uri']}
In a jsp file:
request.getAttribute("javax.servlet.forward.request_uri")
Maybe you are looking for something like:
<%= new UrlPathHelper().getOriginatingRequestUri(request) %>
This is not that elegant but solved my problem.
You can make Interceptor and set request attribute e.g.
request.setAttribute("__SELF",request.getRequestURI);
and in jsp
<form action="${__SELF}" ></form>
Anyone who wants to know about other than the reuqest URI, for example a query string, you can check all the names of the variables in the code of RequestDispatcher(of Servlet API 3.1+) interface.
You can get the query string like this:
${requestScope['javax.servlet.forward.query_string']}
I just found the right answer for your question. The key is using Spring Tags.
<spring:url value="" />
If you put the value attribute empty, Spring will display the mapping URL set in your #RequestMapping.
Try this:
<%# page import="javax.servlet.http.HttpUtils.*" %>
<%= javax.servlet.http.HttpUtils.getRequestURL(request) %>
Which Spring version are you using? I have tested this with Spring 3.1.1.RELEASE, using the following simple application:
Folder structure
-----------------------------------------------------------------------------------
spring-web
|
--- src
|
--- main
|
--- webapp
|
--- page
| |
| --- home.jsp
|
--- WEB-INF
|
--- web.xml
|
--- applicationContext.xml
home.jsp
-----------------------------------------------------------------------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html dir="ltr" lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Welcome to Spring Web!</title>
</head>
<body>
Page URL: ${pageContext.request.requestURL}
</body>
</html>
web.xml
-----------------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" metadata-complete="true" version="2.5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<display-name>org.example.web</display-name>
<servlet>
<servlet-name>spring-mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/webContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-mvc-dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
</web-app>
applicationContext.xml
-----------------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:util="http://www.springframework.org/schema/util" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd">
<context:annotation-config />
<context:component-scan base-package="org.example" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/page/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:annotation-driven />
On accessing http://localhost:8080/spring-web/page/home.jsp, the URL is correctly displayed as http://localhost:8080/spring-web/page/home.jsp.
Here's an approached I've had success with to build an internal link (not absolute):
Path: ${requestScope['javax.servlet.forward.servlet_path']}
Params: ${requestScope['javax.servlet.forward.query_string']}
Putting those together joined by ? to construct the current url:
<c:set var="currentUrl" value="${requestScope['javax.servlet.forward.servlet_path']}?${requestScope['javax.servlet.forward.query_string']}"/>
Add additional url parameters as needed like:
<c:url value="${currentUrl}" var="enUrl"><c:param name="lang" value="en"/></c:url>
<c:url value="${currentUrl}" var="esUrl"><c:param name="lang" value="es"/></c:url>
I used the following in a similar situation. ${currentUrl} can then be Used where needed. Needs core tag library
<c:url value = "" var = "currentUrl" ></c:url>
*<% String myURI = request.getAttribute("javax.servlet.forward.request_uri").toString(); %>
<% String[] split = myURI.split("/"); %>
<% System.out.println("My url is-->"+ myURI
+ " My url splitter length --->"+split.length
+"last value"+split[4]);%>
<%-- <jsp:param name="split[4]" value="split[4]" /> --%>
<c:set var="orgIdForController" value="<%= split[4] %>" />
<a type="button" class="btn btn-default btn-xs"
href="${pageContext.request.contextPath}/supplier/add/${orgIdForController}">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
Add
</a>
- List item*