GregH
GregH

Reputation: 5459

Java Spring get data from html form

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

Upvotes: 0

Views: 9934

Answers (3)

James Jithin
James Jithin

Reputation: 10565

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

Upvotes: 3

rojaranivutukuri
rojaranivutukuri

Reputation: 21

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).

Upvotes: 2

Kenny Tai Huynh
Kenny Tai Huynh

Reputation: 1599

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!

Upvotes: 0

Related Questions