How do I map this URL to a Spring controller method? - spring

I'm using Spring 3.1.1.RELEASE. I'm having fits mapping URLs to controller methods. I would like to map the URL "/my-context-path/organizations/add" to the controller method below. In my controller, I have
#Controller
#RequestMapping("/organizations")
public class OrganizationController
{
…
#RequestMapping(value = "/add", method = RequestMethod.GET)
public ModelAndView doGetadd()
{
… do some stuff …
return new ModelAndView("organizations/add");
} // doGetadd
In my web.xml I have
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
version="2.5">
<display-name>SB Admin</display-name>
<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>/organizations/*</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</context-param>
and in my dispathcer-servlet.xml I have
...
<!-- Enable annotation driven controllers, validation etc... -->
<mvc:annotation-driven />
<context:component-scan base-package="org.myco.subco" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
but requests for my desired context-path result in "No mapping found for HTTP request with URI [/myproject-1.0-SNAPSHOT/organizations/add] in DispatcherServlet with name 'dispatcher" errors (using JBoss 7). How do I map this thing properly? Note that I have multiple methods in my controller that I want to different URLs within the "/organizations" space.

Try this.
Change the dispatcher servlet mapping to :
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
And for the OrganizationController the mapping would be
#Controller
#RequestMapping("/organizations")
public class OrganizationController
And for the ContractsController the mapping would be
#Controller
#RequestMapping("/contracts")
public class OrganizationController

According to the Spring Doc the ModelAndView constructor parameter is the name of the view file.
So that file could be addView.jsp .
As well as the fact that you're (as far as my Spring knowledge goes) actually mapping it to /Application-Name/organizations/organizations/add due to :
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/organizations/</url-pattern>
</servlet-mapping>
And
#Controller
#RequestMapping("/organizations")
public class OrganizationController
I'd recommend changing the requestmapping from the controller to
#Controller
#RequestMapping("/")
public class OrganizationController
The <url-pattern>/organizations/</url-pattern> basiccally defines the 'virtual path' on which your site will be accessible.
Al mappings you do on controllers will append to it, makeing it /organizations/whateverpagecomeshere.jsp
And make sure that View file exists !

Related

http status 500-Error instantiating servlet class org.springframework.web.servlet.DispatcherServlet

Above is the directory hierarchy of my program
I am new to spring and learning MVC concepts I have written a program which takes input(Name) into a text box and prints Hello...'name'. Tha following is my directory structure and the various files I have created.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" 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>MVC_HelloWorld</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- default configuration -->
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>*.ap</url-pattern> <!-- this same extension should bbe used in form action -->
</servlet-mapping>
</web-app>
HelloWorld-servlet.xml
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<!-- default handler mapping -->
<!-- file should be created under web inf annd it's view resolver file -->
<!-- handler(Not rqd in case of default handler) -->
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
<!-- controller configuration -->
<bean name="/HelloWorld.ap" class="controller.HelloController"> <!-- mapping url pattern to controller class using 'name' -->
<!-- view resolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" vlaue="/"/> <!-- default location (prefix used foor rqd page locations) -->
|<property name="sufix" value=".jsp"/> <!-- sufix used forr rqd page extensions -->
</bean>
</bean>
</beans>
HelloController.java
package controller;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import com.sun.javafx.collections.MappingChange.Map;
public class HelloController implements Controller {
#Override
public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse res) throws Exception {
String name=req.getParameter("name");
Map m= new HashMap(); // creating output object
m.put("msg","Hello..."+name);
ModelAndView mav=new ModelAndView("success"+m);
return mav;
}
}
index.jsp
<h1> Hello World</h1>
<form action="./hello.ap">
NAME: <input type="text" name="name">
<input type="Submit" value="Say Hello">
</form>
success.jsp
${msg}
when I am running this code the index.jsp page is running properly bur upon further execution It shows Error 500. what's wrong with the code..?? I am using Eclipse oxygen in that apache 8.5
You configuration in web.xml are wrong.
You are trying to map the dispatch servlet as the controller.
In spring mvc like in other mvc frameworks (struts etc.) there is one major servlet that use to dispatch all requests.
org.springframework.web.servlet.DispatcherServlet is usually named “dispatcher” and should be mapped to a top level url usually “\”
e.g.
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
...
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
And the controller is mapped under this url e.g. HelloWorld
#Controller
#RequestMapping("/HelloWorld");"
public class HelloController implements Controller {}
As your initial project is far from the classic vanilla starter Spring MVC project and it looks like you are using a very old Spring version (or spring tutorial). I suggest to start fresh from some online tutorial.
E.g.
http://www.journaldev.com/2433/spring-mvc-tutorial
http://www.mkyong.com/spring-mvc/gradle-spring-mvc-web-project-example/
Try below edit to web.xml.
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>*.ap</url-pattern> <!-- this same extension should bbe used in form action -->
</servlet-mapping>

Spring mvc #RequestMapping on class level and method level 404 Status

I know that there are lot of posts here with the same problem, but none of them seem to help me, so this will probably be a duplicate.
Im creating a spring mvc application using Maven, i have only one controller with one method. When i put the request mapping annotation only on the class level the application works fine but when i put it on the class level and the method level and i send a request like this:
localhost:8080/myapplication/planification/projet
i get 404 error: HTTP Status 404 - /myapplication/planification/WEB-INF/pages/test.jsp
here is my controller
#Controller
#RequestMapping("/planification")
public class PlanificationController {
#RequestMapping("/projet")
public ModelAndView projets (ModelAndView m){
m.addObject("projets", "All projects");
m.setViewName("test");
return m;
}
}
mvc-dispatcher-servlet.xml
<beans>
<context:component-scan base-package="com.smit"/>
<mvc:annotation-driven/>
<!-- **** VIEW RESOLVER BEAN **** -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
web.xml
<web-app>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet- class>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/mvc-dispatcher-servlet.xml
</param-value>
</context-param>
</web-app>
Hold on, you are using / in front of RequestMapping value, which means from the root. You should removed it like this
#RequestMapping("projet")
Then go to localhost:8080/myapplication/planification/projet
Edit:
WEB-INF should have / in front!

The requested resource is not available error in spring mvc project

I got an error as follows :
Status report
message: /SBC/loginform.html
description :The requested resource is not available.
dispatcher-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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/Views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</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" 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>OpticareVisionHouse</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/forms/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/resources/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</context-param>
</web-app>
-------------------------------------------------
LoginController.java
#Controller
#RequestMapping("loginform.html")
public class LoginController {
#Autowired
public LoginService loginService;
#RequestMapping(method = RequestMethod.GET)
public String showForm(Map model) {
LoginForm loginForm = new LoginForm();
model.put("loginForm", loginForm);
System.out.print("controller calls1");
return "loginform";
}
#RequestMapping(method = RequestMethod.POST)
public String processForm(#Valid LoginForm loginForm, BindingResult result,
Map model) {
System.out.print("controller calls2");
if (result.hasErrors()) {
return "loginform";
}
/*
String userName = "UserName";
String password = "password";
loginForm = (LoginForm) model.get("loginForm");
if (!loginForm.getUserName().equals(userName)
|| !loginForm.getPassword().equals(password)) {
return "loginform";
}
*/
boolean userExists = loginService.checkLogin(loginForm.getUserName(),
loginForm.getPassword());
if(userExists){
model.put("loginForm", loginForm);
return "loginsuccess";
}else{
result.rejectValue("userName","invaliduser");
return "loginform";
}
}
------------------------------------------------
index.jsp
<% response.sendRedirect("loginform.html"); %>
------------------------------------------------
index.jsp is there at webContent.
loginform.jsp is at webContent->web-Inf ->Views
Your dispatcherServlet is mapping urls like: /forms/* to the spring servlet.
You are requesting a url like: /SBC/loginform.html
This request will never go to the spring servlet. You have to access: /{your app context}/forms/loginform.html in order to go to the spring url mapped. Your app context seems to be "SBC", so it will be something like: /SBC/forms/loginform.html
Another way is change the Servlet mapping to:
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
This way, every request on your app context /SBC/* will be routed to the spring servlet.
With this configuration, you should be able to access your controller with: /SBC/loginform.html

How to load the data in index page using spring mvc?

I tried couple of Tutorial in Spring-MVC to load the data in index page without using ajax call means before loading the index page I want to get the data from server and load the data into the index page.but did not get proper answer.
Finally after couple of try i got the answer.here is my code.
web.xml
<display-name>SpringTest</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<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>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
My Controller
#Controller
public class WebController {
#Autowired
private EmployeeService empService;
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView index() {
List<Employee> empList = empService.getAllEmployee();
Collections.sort(empList, new EmployeeSortById());
ModelAndView modelMap = new ModelAndView("index","employeeList", empList);
System.out.println("Calling controller");
return modelMap;
}
}
spring-context.xml
<context:component-scan base-package="com.app.controller,com.app.dao.impl,com.app.service.impl" />
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp" />
</bean>

How to map dynamic url /prj/noticeOpen/2 in Spring MVC controller

Hi I am having hard time with following url:
dynamicLink
to map with following controller method:
#RequestMapping(value="/noticeOpen/{quesId}")
public ModelAndView noticeOpen(#ModelAttribute("NoticeForm") NoticeForm noticeForm,
ModelMap model,
#PathVariable("quesId") Integer quesId){
System.out.println(quesId);
return new ModelAndView("/noticeOpen","noticeForm",noticeForm);
}
Problem starts when i click on the anchor dynamicLink and it does not transfers control to my controller, instead it shows following in browser's address bar:
http://127.0.0.1:8080/prj/noticeOpen/2/WEB-INF/pages/noticeOpen.jsp
Moreover I have following mapping in applicationContext.xml
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
This all works fine if I remove {quesId} from controller's #RequestMapping and #PathParam from method signature(also remove questionId from anchor )
http://127.0.0.1:8080/prj/noticeOpen
But that does not sound dynamic and fulfill my requirement.
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:jsp="http://java.sun.com/xml/ns/javaee/jsp" 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" version="2.5">
<display-name>Spring Web MVC Application</display-name>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<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>
</web-app>
Update
I created new Controller for /noticeOpen/{quesId} and its now getting the control, But I am not able to understand the behavior of the following methods.
Please take a look below on NoticeController and then result under that:
#Controller
public class NoticeController {
#RequestMapping(value="/noticeOpen/{quesId}")
public ModelAndView noticeOpen(#ModelAttribute("NoticeForm") NoticeForm noticeForm,ModelMap model,#PathVariable("quesId") Integer quesId){
return new ModelAndView("noticeOpen","noticeForm",noticeForm);
}
#RequestMapping(value="/noticeOpen")
public ModelAndView noticeOpen(#ModelAttribute("NoticeForm") NoticeForm noticeForm,ModelMap model){
return new ModelAndView("noticeOpen","noticeForm",noticeForm);
}
#RequestMapping(value="/noticeOpen") it redirects me to correct noticeOpen.jsp
#RequestMapping(value="/noticeOpen/{quesId}") it redirects me to following error Page
HTTP Status 404 - /prj/noticeOpen/WEB-INF/pages/noticeOpen.jsp
type Status report
message /prj/noticeOpen/WEB-INF/pages/noticeOpen.jsp
description The requested resource is not available.
Apache Tomcat/6.0.36
Change your prefix value in applicationContext.xml as follows
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
A slash before WEB-INF.It will work.

Resources