简体   繁体   中英

JSP form bean with Servlet action

File Test.jsp :

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

File person.java :

    private String fname;
    private String lname;

File TestServlets.java :

    doPost() {
        ...
    }

How to make the form fields in jsp map to pojo and use in servlets?

Here is the way to go about this with Servlet s, which ruled before Struts and Spring :

webapp/Test.jsp or 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;
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM