Handle two URL pattern form one controller in Spring MVC

873 views Asked by At

I'm learning spring mvc using spring tool suite in eclipse IDE.My base package is org.springTest.test and I've create two jsp pages under view folder index.jsp and home.jsp. I'm trying to use home.jsp as my welcome page. When I'm trying to access http://localhost:8081/test/ and http://localhost:8081/test/index.jsp it always gives index.jsp page.I also tried to add home page in to welcome file-list.But same result.Please look into web.xml and controller class.How can I fix this?.

HomeController.java

package org.springTest.test;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


 @Controller
 public class HomeController {


private static final Logger logger = LoggerFactory
        .getLogger(HomeController.class);


@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
    logger.info("Welcome home! The client locale is {}.", locale);

    Date date = new Date();
    DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG,
            DateFormat.LONG, locale);

    String formattedDate = dateFormat.format(date);

    model.addAttribute("serverTime", formattedDate);

    return "home";
}

@RequestMapping(value = "index", method = RequestMethod.GET)
public String home1(Locale locale, Model model) {
    logger.info("Welcome index! The client locale is {}.", locale);

    Date date = new Date();
    DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG,
            DateFormat.LONG, locale);

    String formattedDate = dateFormat.format(date);

    model.addAttribute("serverTime", formattedDate);

    return "index";
}
}

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">

<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>
    <url-pattern>/index.jsp</url-pattern>
</servlet-mapping>

</web-app>
1

There are 1 answers

3
NeoP5 On

for spring-webmvc you will need to register a "InternalResourceViewresolver" bean if not yet done. If this is already done can you please attache the configuration?

The internalResourceViewResolver is used to match your return-code "home" and "index" from your controller-methods to a cetrain view (jsp).

a resource view resolver can be configured like this:

@Bean
public InternalResourceViewResolver jspViewResolver() {
  InternalResourceViewResolver bean = new InternalResourceViewResolver();
  bean.setPrefix("/WEB-INF/views/");
  bean.setSuffix(".jsp");
  return bean;
}

It will take the string-name returned by your controller; e.g. "home" and append ".jsp" to it and look for "/WEB.INF/views/home.jsp". If it can not be found an error is thrown or the welcome-jsp is delvivered.

I've attached servlet-context.xml and console out put also.

servlet-context.xml

  <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="org.springTest.test" />

Last lines of console out put

INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - 
    Mapped "{[/],methods=[GET],params=[],headers=[],consumes=[],produces=           [],custom=[]}" 
    onto public java.lang.String org.springTest.test.HomeController.home
    (java.util.Locale,org.springframework.ui.Model)
INFO :        org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/index],methods=[GET],params=[],headers=[],consumes= [],produces=[],custom=[]}"onto public java.lang.String     org.springTest.test.HomeController.home1(java.util.Locale,org.springframework.ui.Model)
INFO : org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - 
    Mapped URL path [/resources/**] onto handler 
    'org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0'
INFO : org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'appServlet': 
    initialization completed in 544 ms
INFO : org.springTest.test.HomeController - Welcome index! The client     locale is en_US.