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

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.

Related

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 do I map this URL to a Spring controller method?

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 !

Spring MVC: how to create a default controller for index page?

I'm trying to do one of those standard spring mvc hello world applications but with the twist that I'd like to map the controller to the root. (for example: http://numberformat.wordpress.com/2009/09/02/hello-world-spring-mvc-with-annotations/ )
So the only real difference is that they map it to host\appname\something and I'd like to map it to host\appname.
I placed my index.jsp in src\main\webapp\jsp and mapped it in the web.xml as the welcome file.
I tried:
#Controller("loginController")
public class LoginController{
#RequestMapping("/")
public String homepage2(ModelMap model, HttpServletRequest request, HttpServletResponse response){
System.out.println("blablabla2");
model.addAttribute("sigh", "lesigh");
return "index";
}
As my controller but I see nothing appear in the console of my tomcat.
Does anyone know where I'm messing up?
My web.xml:
<?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">
<!-- Index -->
<welcome-file-list>
<welcome-file>/jsp/index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>
<servlet>
<servlet-name>springweb</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springweb</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
The mvc-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"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="de.claude.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="/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
I'm using Spring 3.0.5.release
Or is this not possible and do I need to put my index.jsp back in the root of the web-inf and put a redirect to somewhere inside my jsp so the controller picks it up?
I had the same problem, even after following Sinhue's setup, but I solved it.
The problem was that that something (Tomcat?) was forwarding from "/" to "/index.jsp" when I had the file index.jsp in my WebContent directory. When I removed that, the request did not get forwarded anymore.
What I did to diagnose the problem was to make a catch-all request handler and printed the servlet path to the console. This showed me that even though the request I was making was for http://localhost/myapp/, the servlet path was being changed to "/index.html". I was expecting it to be "/".
#RequestMapping("*")
public String hello(HttpServletRequest request) {
System.out.println(request.getServletPath());
return "hello";
}
So in summary, the steps you need to follow are:
In your servlet-mapping use <url-pattern>/</url-pattern>
In your controller use RequestMapping("/")
Get rid of welcome-file-list in web.xml
Don't have any files sitting in WebContent that would be considered default pages (index.html, index.jsp, default.html, etc)
Hope this helps.
The redirect is one option. One thing you can try is to create a very simple index page that you place at the root of the WAR which does nothing else but redirecting to your controller like
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:redirect url="/welcome.html"/>
Then you map your controller with that URL with something like
#Controller("loginController")
#RequestMapping(value = "/welcome.html")
public class LoginController{
...
}
Finally, in web.xml, to have your (new) index JSP accessible, declare
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
We can simply map a Controller method for the default view. For eg, we have a index.html as the default page.
#RequestMapping(value = "/", method = GET)
public String index() {
return "index";
}
once done we can access the page with default application context.
E.g http://localhost:8080/myapp
It works for me, but some differences:
I have no welcome-file-list in web.xml
I have no #RequestMapping at class level.
And at method level, just #RequestMapping("/")
I know these are no great differences, but I'm pretty sure (I'm not at work now) this is my configuration and it works with Spring MVC 3.0.5.
One more thing. You don't show your dispatcher configuration in web.xml, but maybe you have some preffix. It has to be something like this:
<servlet-mapping>
<servlet-name>myServletName</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
If this is not your case, you'll need an url-rewrite filter or try the redirect solution.
EDIT: Answering your question, my view resolver configuration is a little different too:
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
It can be solved in more simple way:
in web.xml
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.htm</welcome-file>
</welcome-file-list>
After that use any controllers that your want to process index.htm with #RequestMapping("index.htm"). Or just use index controller
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index.htm">indexController</prop>
</props>
</property>
<bean name="indexController" class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
</bean>
Just put one more entry in your spring xml file i.e.mvc-dispatcher-servlet.xml
<mvc:view-controller path="/" view-name="index"/>
After putting this to your xml put your default view or jsp file in your custom JSP folder as you have mentioned in mvc-dispatcher-servlet.xml file.
change index with your jsp name.
One way to achieve it, is by map your welcome-file to your controller request path in the web.xml file:
[web.xml]
<web-app ...
<!-- Index -->
<welcome-file-list>
<welcome-file>home</welcome-file>
</welcome-file-list>
</web-app>
[LoginController.java]
#Controller("loginController")
public class LoginController{
#RequestMapping("/home")
public String homepage2(ModelMap model, HttpServletRequest request, HttpServletResponse response){
System.out.println("blablabla2");
model.addAttribute("sigh", "lesigh");
return "index";
}
The solution I use in my SpringMVC webapps is to create a simple DefaultController class like the following: -
#Controller
public class DefaultController {
private final String redirect;
public DefaultController(String redirect) {
this.redirect = redirect;
}
#RequestMapping(value = "/")
public ModelAndView redirectToMainPage() {
return new ModelAndView("redirect:/" + redirect);
}
}
The redirect can be injected in using the following spring configuration: -
<bean class="com.adoreboard.farfisa.controller.DefaultController">
<constructor-arg name="redirect" value="${default.redirect:loginController}"/>
</bean>
The ${default.redirect:loginController} will default to loginController but can be changed by inserting default.redirect=something_else into a spring properties file / setting an environment variable etc.
As #Mike has mentioned above I have also: -
Got rid of <welcome-file-list> ... </welcome-file-list> section in the web.xml file.
Don't have any files sitting in WebContent that would be considered default pages (index.html, index.jsp, default.html, etc)
This solution lets Spring worry more about redirects which may or may not be what you like.

Resources