Java Spring从html表单

时间:2015-09-24 01:09:38

标签: java spring jsp spring-mvc

我正在尝试创建一个简单的应用程序,它涉及一个jsp页面(它只是一个输入查询和提交按钮的文本区域)一个Query类(下面显示的非常简单的类)和一个与两者交互的QueryController。我试图让QueryController打印到控制台来测试它,但没有输出打印到Standard.out。单击“提交”按钮会将我带到http://localhost:8080/<PROJECT_NAME>/?queryField=<QUERY_TEXT>,这会导致404错误,因为它不是有效的网页。三个[简单]类如下所示。感谢帮助。

查询类:

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>

和我简单的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";
}
}

3 个答案:

答案 0 :(得分:3)

我们需要对Spring模块进行更多配置才能实现这一目标。您可以使用Option 1 - with web.xmlOption 2 - without web.xml

选项1(web.xml)

1。web.xml修改为:

<?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。使用路径创建文件 - WEB-INF/config/SimpleProjectServlet-servlet.xml

3. 将以下内容添加到步骤2中创建的文件中。您需要编辑Spring版本引用:

<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. context:component-scan

的上述配置中设置正确的包名称

选项2(非web.xml)

1。删除web.xml

2。为基于Java Config的注释添加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。使用SpringWebConfig处的正确包修改@ComponentScan

4. Java Config添加WebApplication。使用所需的配置创建一个扩展WebApplicationInitializer的类:

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("/");
        }
    }

更新

这里我们有很少的配置部分导致了这个错误:

  1. DispatcherServlet已配置为接受views/*
  2. 的网址
  3. 部署描述符没有src\main\javaWEB-INF\classes
  4. 用户Spring 3正在Tomcat 8上运行,默认为JDK-8ASM Loader无法加载文件。不得不转移到Spring版本4.0.1-RELEASE

答案 1 :(得分:2)

你的query.jsp文件需要一些改动。从:

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

要:

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

您需要指定path属性才能使用Spring表单处理。需要路径属性:它将表单元素(本例中为文本区域)映射到POJO类的变量(查询类的私有字符串查询)。

答案 2 :(得分:0)

我认为你需要添加一个配置文件,在你的web.xml中你应该为它添加声明,如:  的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>
...
在appServlet-servlet.xml中,您应该声明注释扫描,如:

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

希望这有帮助!