0

I am trying to create a simple application which involves a jsp page (which is just a textarea to enter a query and a submit button) a Query class (very simple class shown below) and a QueryController to interact with the two. I am trying to have the QueryController print to console to test it but no output is being printed to Standard.out . Clicking the submit button takes me to http://localhost:8080/<PROJECT_NAME>/?queryField=<QUERY_TEXT> which results in a 404 error since it is not a valid webpage. The three [simple] classes are shown below. Help is appreciated.

Query class:

public class Query {

    private String query;
    public String getQuery() {
         return query;
    }
    public void setQuery(String query) {
         this.query = query;
    }
}

query.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"   "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>

<form action="query" method="post" commandName="queryForm">
<textarea name="queryField" cols="55" rows="1"></textarea><br>
<input type="submit" value="submit">
</form>

</body>
</html>

and my simple QueryController.java:

@Controller
@RequestMapping(value = "/query")
public class QueryController {

@RequestMapping(method = RequestMethod.POST)
public String processRegistration(@ModelAttribute("queryForm") Query query,
        Map<String, Object> model) {

    // for testing purpose:
    System.out.println("query (from controller): " + query.getQuery());

    return "someNextPageHere";
}
}
9
  • 2
    Why are you using a GET on a form post? Commented Sep 24, 2015 at 1:12
  • Can you post your web.xml and the context file in your code?! 404 means it does not regconize the mapping page?! Have you declared the annotation scan?! Commented Sep 24, 2015 at 1:38
  • @Kenny Tai Huynh web.xml is added and ChiefTwoPencils I'm not sure what you are suggesting to do differently. Commented Sep 24, 2015 at 1:53
  • The controller expects post request and your form method is get w3schools.com/tags/ref_httpmethods.asp Commented Sep 24, 2015 at 1:56
  • Do you have a welcome page defined? If yes, is that being shown when you access http://localhost:8080/<PROJECT_NAME>? Commented Sep 24, 2015 at 2:04

3 Answers 3

3
+100

We would need more configuration to Spring modules to get this working. You may go with Option 1 - with web.xml or Option 2 - without web.xml:

Option 1 (web.xml)

1. Modify your web.xml to:

<?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>SimpleProject</display-name>

    <servlet>
        <servlet-name>SimpleProjectServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                 /WEB-INF/config/SimpleProjectServlet-servlet.xml
            </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>SimpleProjectServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>query.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
</web-app>

2. Create file with path - WEB-INF/config/SimpleProjectServlet-servlet.xml

3. Add following contents to the file created in Step 2. You would need to edit the Spring version references:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.2.xsd">
    <context:component-scan base-package="com.mycompany.myproject" />
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/views/jsp/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
    <mvc:resources mapping="/resources/**" location="/resources/" />
    <mvc:annotation-driven />
</beans>

4. Set right package name as you have in the above configuration at context:component-scan

Option 2 (non-web.xml)

1. Delete your web.xml

2. Add Java Config for annotation based Spring MVC

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@EnableWebMvc
@Configuration
@ComponentScan({ "com.mycompany.myproject" })
public class SpringWebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations(
                "/resources/");
    }

    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/views/jsp/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }

}

3. Modify SpringWebConfig with the right package at @ComponentScan

4. Add Java Config for WebApplication. Create a class extending WebApplicationInitializer with required configurations:

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

    import org.springframework.web.servlet.DispatcherServlet;

    public class MyWebAppInitializer implements WebApplicationInitializer {

        public void onStartup(ServletContext container) throws ServletException {
            AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
            ctx.register(SpringWebConfig.class);
            ctx.setServletContext(container);

            ServletRegistration.Dynamic servlet = container.addServlet(
                    "dispatcher", new DispatcherServlet(ctx));
            servlet.setLoadOnStartup(1);
            servlet.addMapping("/");
        }
    }

Update

Here we had few configuration part that was resulting in this error:

  1. DispatcherServlet was configured to accept url with views/*
  2. Deployment Descriptor did not have src\main\java to WEB-INF\classes
  3. User had Spring 3 running on Tomcat 8 which defaults to JDK-8 and ASM Loader could not load files. Had to move to Spring version 4.0.1-RELEASE
Sign up to request clarification or add additional context in comments.

13 Comments

I tried your option #1 and have updated my post with your suggestions. The same issue is persisting though- nothing printing in console
Could you name your textarea to query instead of queryField? If that doesn't work, for debugging purpose, set your model attribute to required=false. Also, when the app starts, do you the mapping /query being displayed?
tried renaming the textarea with no luck. and no the url that shows at launch is localhost:8080/GCImage
For debugging, rename processRegistration(@ModelAttribute("queryForm") Query query, Map<String, Object> model) to processRegistration() and check if method gets called.
after doing so, the same result is happening, 404 at localhost:8080/GCImage and localhost:8080/GCImage/query. and no stacktrace errors
|
2

You query.jsp file need some change. From:

<textarea name="queryField" cols="55" rows="1"></textarea>

To:

<textarea name="queryField" path="query" cols="55" rows="1"></textarea>

You need to specify path attribute in order to use Spring form handling. Need of path attribute: it maps the form element (text area in this case) to a variable of POJO class (private String query of Query class).

1 Comment

Oh. My. God. Thanks a lot, I could kiss you right now. You solved my problem with that path,
0

I think you need to add a config file and in your web.xml you should add the declaration for it like: web.xml

...
<!-- Processes application requests -->
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>


    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
...

in your appServlet-servlet.xml, you should declare the annotation scan like:

 <tx:annotation-driven />
    <mvc:annotation-driven />
    <context:annotation-config />
    <context:component-scan base-package="abc.xyz"/>

Hope this help!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.