I have created a mapping in web.xml something like this:
<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>/about/*</url-pattern>
</servlet-mapping>
In my controller I have something like this:
import org.springframework.stereotype.Controller;
@Controller
public class MyController{
@RequestMapping(value="/about/us", method=RequestMethod.GET)
public ModelAndView myMethod1(ModelMap model){
//some code
return new ModelAndView("aboutus1.jsp",model);
}
@RequestMapping(value="/about", method=RequestMethod.GET)
public ModelAndView myMethod2(ModelMap model){
//some code
return new ModelAndView("aboutus2.jsp",model);
}
}
And my dispatcher-servlet.xml has view resolver like:
<mvc:annotation-driven/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:viewClass="org.springframework.web.servlet.view.JstlView"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp"/>
To my surprise: request .../about/us
is not reaching to myMethod1 in the controller. The browser shows 404 error. I put a logger inside the method but it isn't printing anything, meaning, its not being executed..../about
works fine! What can be the done to make .../about/us
request work? Any suggestions?
Make sure you create your package and classes in src/main/java NOT in src/main/resources. If maven doesn't create the src/main/java folder, just create the folder and move the package folders/classes there. Doing this resolved the no mapping error for me. Hope this information will be useful to someone.
@RequestMapping is used at the class level while @GetMapping is used to connect the methods. This is also an important Spring MVC interview question to knowing how and when to use both RequestMapping and GetMapping is crucial for Java developers.
The @RequestMapping annotation can be applied to class-level and/or method-level in a controller. The class-level annotation maps a specific request path or pattern onto a controller. You can then apply additional method-level annotations to make mappings more specific to handler methods.
We went through the two most common reasons for receiving a 404 response from our Spring application. The first was using an incorrect URI while making the request. The second was mapping the DispatcherServlet to the wrong url-pattern in web. xml.
You need to use @RequestMapping(value="/us", method=RequestMethod.GET)
or you need to request about/about/us
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With