Not being able to find my mapping anymore (spring - controller) - spring

I am not being able to find my mapping anymore (I made it work. But then, I made changes, but probably due to cache, I didn't realize when it stopped working :-( ). It gives 404 error now when I click on submit on the form. Any help would be appreciated. Thank you in advance!
web.xml:
<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>/app/*</url-pattern>
</servlet-mapping>
JSP:
<form:form method="POST" action="/app/app/studentSearchById" commandName="student">
Controller:
#Controller
// #RequestMapping("/studentSearch")
public class StudentSearchController {
// #Autowired
//StudentService userService = new StudentService();
// #RequestMapping(value="/StudentSearchById", method = RequestMethod.GET)
// public ModelAndView searchById(#PathVariable Long studentId) {
#RequestMapping(value = "/studentSearchById", method = RequestMethod.POST)
public ModelAndView searchById(#ModelAttribute("student") Student student, Map<String, Object> map,
HttpServletRequest request) {
StudentService userService = new StudentService();
Student studentFound = userService.findStudent(student.getStudentId());
ModelAndView modelAndView = new ModelAndView();
// modelAndView.addObject("students", studentFound);
return modelAndView;
}
Thank you a lot in advance!

When you are using stereotype annotation (#Controller , #Service, #Repository) then its better to use context: component-scan tag to say that Spring has to scan packages searching the annotation and register beans within the application context.

I spent hours on this... just after posting, I figured out...
I had changed the line on my spring-servlet.xml. Putting the line as before, it worked:
<context:component-scan base-package="my.controller.package" />

Related

How to allow GET method for endpoint programmatically?

I am loading a .war file and add it as web app to the embedded Tomcat server.
#Bean
public EmbeddedServletContainerFactory servletContainerFactory() {
LOGGER.info("Adding web app");
return new TomcatEmbeddedServletContainerFactory() {
#Override
protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(Tomcat tomcat) {
String appHome = System.getProperty(Environment.APP_HOME);
String targetFileName = "web-0.0.1-SNAPSHOT.war";
InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(targetFileName);
LOGGER.info(System.getProperty("user.name"));
LOGGER.debug("Loading WAR from " + appHome);
File target = new File(Paths.get(appHome, targetFileName).toString());
try {
LOGGER.info(String.format("Copy %s to %s", targetFileName, target.getAbsoluteFile().toPath()));
java.nio.file.Files.copy(resourceAsStream, target.getAbsoluteFile().toPath(), StandardCopyOption.REPLACE_EXISTING);
Context context = tomcat.addWebapp("/", target.getAbsolutePath());
context.setParentClassLoader(getClass().getClassLoader());
} catch (ServletException ex) {
throw new IllegalStateException("Failed to add webapp.", ex);
} catch (Exception e) {
throw new IllegalStateException("Unknown error while trying to load webapp.", e);
}
return super.getTomcatEmbeddedServletContainer(tomcat);
}
};
}
This is working so far but if I access http://localhost:8080/web I am getting
2017-03-04 11:18:59.588 WARN 29234 --- [nio-8080-exec-2] o.s.web.servlet.PageNotFound : Request method 'GET' not supported
and the response
Allow: POST
Content-Length: 0
Date: Sat, 04 Mar 2017 10:26:16 GMT
I am sure all I have to do is to allow the GET method on /web and hopefully the static web content provided from the loaded war file will be accessible via web browser.
How/where can I configure the endpoint such that it allows GET requests?
I tried to introduce a WebController as described in this tutorial.
#Controller
public class WebController {
private final static Logger LOGGER = Logger.getLogger(WebController.class);
#RequestMapping(value = "/web", method = RequestMethod.GET)
public String index() {
LOGGER.info("INDEX !");
return "index";
}
}
In the log output I can see that this is getting mapped correctly:
RequestMappingHandlerMapping : Mapped "{[/web],methods=[GET]}" onto public java.lang.String org.ema.server.spring.controller.dl4j.WebController.index()
but it does not change the fact that I cannot visit the website.
I've also configured a InternalResourceViewResolver:
#Configuration
#EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter {
private final static Logger LOGGER = Logger.getLogger(MvcConfiguration.class);
#Override
public void configureViewResolvers(ViewResolverRegistry registry) {
LOGGER.info("configureViewResolvers()");
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setSuffix(".html");
registry.viewResolver(resolver);
}
#Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
web.xml
Since I configure everything in pure Java, this file does not define a lot:
<?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"
version="3.0">
<display-name>Easy Model Access Server</display-name>
<listener>
<listener-class>org.ema.server.ServerEntryPoint</listener-class>
</listener>
<context-param>
<param-name>log4j-config-location</param-name>
<param-value>WEB-INF/classes/log4j.properties</param-value>
</context-param>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/web/*.html</url-pattern>
</servlet-mapping>
</web-app>
Reproduce
If you want to reproduce this you can simply checkout the entire code from github. All you need to do this:
mkdir ~/.ema
git clone https://github.com/silentsnooc/easy-model-access
cd easy-model-access/ema-server
mvn clean install
java -jar server/target/server-*.jar
This will clone, build and run the server.
The directory ~/.ema directory is required at the moment. It is where the WAR is being copied as the server starts.
My guess is that your web.xml maps any path to the Spring DispatcherServlet, something like:
<servlet>
<servlet-name>app</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Because of <url-pattern>/</url-pattern> any request must be handled by a Spring controller, for this reason your static files are not served by Tomcat. Also a pattern like /*.html would have same effect.
If you have only a few pages you might add one or more mapping to the predefined default servlet for them, before the mapping of Spring (and also before Spring Security if you use it):
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>index.html</url-pattern>
</servlet-mapping>
You may also use <url-pattern>*.html</url-pattern> or, if your resources are under the web path and there are only static resources there: <url-pattern>/web/*</url-pattern>
Maybe all this is done instead in Java code in the org.ema.server.ServerEntryPoint that you have as a listener in web.xml
I think the mapping I wrote up in web.xml is done in your case in method getServletMappings of class org.ema.server.spring.config.AppInitializer, I changed it to use a more strict pattern /rest-api/* instead than /, not sure pattern is correct and everything else works, but now http://127.0.0.1:8080/index.html works
#Override
protected String[] getServletMappings() {
return new String[] { "/rest-api/*" };
}
as I see the url: http://localhost:8080/web is wrong.
You can try: http://localhost:8080/[name-of-war-file]/web

Spring MVC configuration and mapping

Hate to ask a simple config question but I'm new to the spring mvc framework and for some reason struggling a little bit. I am working on this just to learn it as I have used MVC in ruby and wanted to try it in java.
I have a sample app that talks to a DB and returns a full table from my controller out to a JSP it all works my table is displaying from the DB Correctly. I still think I have my configs wrong though as my app only works if my web.xml is setup like so
<servlet-mapping>
<servlet-name>foo</servlet-name>
<url-pattern>/RunList.jsp</url-pattern>
</servlet-mapping>
I don't think I should have to use the full name of the JSP in my pattern. if I just use / I get
<servlet-mapping>
<servlet-name>foo</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Sep 01, 2015 10:53:02 AM org.springframework.web.servlet.PageNotFound noHandlerFound
WARNING: No mapping found for HTTP request with URI [/dyn-qa-qeb/] in DispatcherServlet with name 'foo'
Here is my controller
#RequestMapping(value="/RunList")
public ModelAndView listRun(ModelAndView model) throws IOException{
//#ModelAttribute
System.out.println("**** Controller ******");
List<QAModel> listRun = runDao.list();
model.addObject("RunList", listRun);
model.setViewName("RunList");
return model;
}
I also have an MVC Configuration file that I setup based on a tutorial but I am not sure if that just overrides the web.xml
#Configuration
#ComponentScan(basePackages="com.foo")
#EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter{
#Bean
public ViewResolver getViewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
This was a config issue long ago solved just cleaning up my questions

How to globally handle 404 exception by returning a customized error page in Spring MVC?

I need to return a customized error page for HTTP 404, but the code does not work. I already read the stackflow 1,2, 3 and different online + articles but my case is quite different with those or at least I can not figure out the issue.
HTTP Status 404 -
type Status report
message
description The requested resource is not available.
For example, it is suggested to use an action name in web.xml to handle the exception, it might work but I think is not a good method of doing it.
I used following combinations:
1)
#Controller //for class
#ResponseStatus(value = HttpStatus.NOT_FOUND) //for method
2)
#Controller //for class
#ResponseStatus(value = HttpStatus.NOT_FOUND) //for method
#ExceptionHandler(ResourceNotFoundException.class) //for method
3)
#ControllerAdvice //for class
#ResponseStatus(value = HttpStatus.NOT_FOUND) //for method
3)
#ControllerAdvice //for class
#ResponseStatus(HttpStatus.NOT_FOUND) //for method
4)
#ControllerAdvice //for class
#ResponseStatus(value = HttpStatus.NOT_FOUND) //for method
#ExceptionHandler(ResourceNotFoundException.class) //for method
Code
#ControllerAdvice
public class GlobalExceptionHandler {
#ResponseStatus(value = HttpStatus.NOT_FOUND)
public String handleBadRequest(Exception exception) {
return "error404";
}
}
DispatcherServlet does not throw an exception by default, if it does not find the handler to process the request. So you need to explicitly activate it as below:
In web.xml:
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>throwExceptionIfNoHandlerFound</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
If you are using annotation based configuration:
dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
In the controller advice class:
#ExceptionHandler
#ResponseStatus(HttpStatus.NOT_FOUND)
public String handleExceptiond(NoHandlerFoundException ex) {
return "errorPage";
}
You can use the #ResponseStatus annotation at the class level. At least it works for me.
#Controller
#ResponseStatus(value=HttpStatus.NOT_FOUND)
public class GlobalExceptionHandler {
....
}
You can add the following in your web.xml to display an error page on 404. It will display 404.jsp page in views folder inside WEB-INF folder.
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/views/404.jsp</location>
</error-page>

How to inject a Spring Data JPA Repository into a Servlet Filter?

I'm using the Tuckey UrlRewriteFilter. I want to use a rewrite rule from a database, so using the <class-rule class="com.example.Foo" /> configuration, which lets you get rules at runtime. I created a class extending RewriteRule:
public class Foo extends RewriteRule {
#Autowired
private MyRepository myRepository;
public boolean init(ServletContext servletContext) {
return true;
}
#Override
public RewriteMatch matches(HttpServletRequest request, HttpServletResponse response) {
//myRepository is null
return super.matches(request, response);
}
#Override
public void destroy() {
}
}
I'd like to use a Spring Data JPA Repository inside this Foo class, but it looks the repository is null.
How can I inject it correctly?
Declare your filter in web.xml as usual, except that you will need to provide org.springframework.web.filter.DelegatingFilterProxy as the filter class name instead of your actual class name.
<filter>
<filter-name>urlRewriteFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>urlRewriteFilter</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping>
Finally, in your ROOT application context, declare a bean pointing to your filter class and with the same name as the filter name provided in web.xml in the application context file loaded from web.xml:
<bean id="urlRewriteFilter" class="org.tuckey.web.filters.urlrewrite.UrlRewriteFilter"/>
Since your filter instance is now managed by Spring, you can inject any Spring managed bean into it.

Having issue with mapping in spring dispatcher servlet

I have a JSP page that contains a form and on submitting that form I need to call GET method. But with my current mapping, when I try to load my JSP page then instead of loading the JSP page it calls GET method.
Following are the mappings that I made.
web.xml:
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/test/*</url-pattern>
</servlet-mapping>
TestHarnessController :
#Controller
#RequestMapping("/testHarness")
public class TestHarnessController {
#RequestMapping(method = RequestMethod.GET)
public String handleGetRequest(HttpServletRequest request, HttpServletResponse response) {
return null;
}
#RequestMapping(method = RequestMethod.POST)
public String handlePostRequest(HttpServletRequest request, HttpServletResponse response) {
return null;
}
}
And my JSP page url is:
http://localhost.ms.com:8080/DataBox/test/testHarness.jsp
Please give me some suggestions as I am struggling with this since 2 -3 days.

Resources