JSP表单bean与Servlet操作

时间:2015-10-10 17:35:44

标签: java jsp servlets

档案Test.jsp

    <form action="servlet.action">
    <input type="text" name="fname">
    <input type="text" name="lname">
    </form>

档案person.java

    private String fname;
    private String lname;

档案TestServlets.java

    doPost() {
        ...
    }

如何将jsp中的表单字段映射到pojo并在servlet中使用?

1 个答案:

答案 0 :(得分:0)

以下是使用Servlet进行此操作的方法,该方法在StrutsSpring之前统治:

webapp / Test.jsp或WebContent / Test.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>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <form action="servlet.action">
        <input type="text" name="fname" placeholder="First"> <input
            type="text" name="lname" placeholder="Last"> <input type="submit" />
    </form>
</body>
</html>

的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>TestServlets</servlet-name>
        <servlet-class>TestServlets</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>TestServlets</servlet-name>
        <url-pattern>/servlet.action</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>Test.jsp</welcome-file>
    </welcome-file-list>
</web-app>

TestServlets.java

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TestServlets extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        Person person = new Person();
        person.setFname(req.getParameter("fname")); //Populate fields from request parameter
        person.setLname(req.getParameter("lname"));

    }
}

Person.java

public class Person {

    private String fname;
    private String lname;

    public String getFname() {
        return fname;
    }

    public void setFname(String fname) {
        this.fname = fname;
    }

    public String getLname() {
        return lname;
    }

    public void setLname(String lname) {
        this.lname = lname;
    }

}