Java Spring从html表单获取数据

标签 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;
    }
}

查询.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";
}
}

最佳答案

我们需要对 Spring 模块进行更多配置才能使其正常工作。您可以选择选项 1 - 使用 web.xml选项 2 - 不使用 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.为基于注释的Spring MVC添加Java Config

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.使用@ComponentScan处的正确包修改SpringWebConfig

4.WebApplication添加Java Config。使用所需的配置创建一个扩展 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/* 的 url
  2. 部署描述符没有 src\main\javaWEB-INF\classes
  3. 用户在默认为 JDK-8Tomcat 8 上运行 Spring 3,而 ASM Loader 无法运行加载文件。必须迁移到 Spring 版本 4.0.1-RELEASE

关于Java Spring从html表单获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32751840/

相关文章:

java - 一个 classe owl api 的父类(super class)

java - 从 iOS 到 Android : Some beginner's questions

spring - 从 H2 控制台连接到 H2 数据库

spring - 如何在 Spring AOP 中获取 HttpServletRequest 和 HttpServletResponse 对象

java - Servlet 在 Eclipse 中运行时显示 404 错误

java - Java 中下划线作为变量名。为什么?

spring - 意外的 token (START_OBJECT),应为 VALUE_STRING : need JSON String that contains type id (for subtype of java. lang.Object)

java - 处理多部分/表单数据

javascript - 如何使jsp页面键盘可访问以及如何更改弹出的jsp页面的位置?

java - 配置 Tomcat 以便我可以将 JSP 页面连接到 MySQL