如何与JSP Servlet一起使用

时间:2022-09-06 16:36:00

I'm studying JSP and Servlets by reading a book and following some online tutorials. I'm totally new with web programming using JSP and Servlets.

我正在通过阅读一本书和一些在线教程来学习JSP和Servlets。我是使用JSP和Servlets进行Web编程的新手。

I came across an example which I am trying to understand.

我遇到了一个我想要了解的例子。

index.html

<form action="emailList" method="post">

    <input type="hidden" name="action" value="add" />

    <label>Email: </label>
    <input type="email" name="email" required /> <br />
    <label>First Name:</label>
    <input type="text" name="firstName" required /> <br/>
    <label>Last Name:</label>
    <input type="text" name="lastName" required /> <br />

    <label>&nbsp;</label>
    <input type="submit" value="Join Now" id="submit" />

</form>

EmailServlet.java

public class EmailListServlet extends HttpServlet{

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String url = "/index.html";

        //get the current action
        String action = req.getParameter("action");

        if(action == null){
            action = "join"; //default action
        }

        //perform action and set URL to appropriate page
        if(action.equals("join")){
            url = "/index.html"; //the join page
        }
        else if(action.equals("add")){
            //get parameters from the request
            String firstName = req.getParameter("firstName");
            String lastName = req.getParameter("lastName");
            String email = req.getParameter("email");

            //store data in User object and save User object in database
            User user = new User(firstName, lastName, email);
            UserDB.insert(user);

            //set User object in request object and set URL
            req.setAttribute("user", user);
            url = "/thanks.jsp"; //the thanks page
        }

        //forward request and response objects to specified url
        getServletContext().getRequestDispatcher(url).forward(req, resp);
    }

The thing I don't understand is the IF-ELSE part.

我不明白的是IF-ELSE部分。

I read somewhere that the main purpose of using hidden <input> is to determine the state of a form. The way I understand it is that of, a way to check if form fields (or parameters) are null or not.

我在某处读到使用隐藏的主要目的是确定表单的状态。我理解它的方式是,检查表单字段(或参数)是否为空的方法。

If that's the case, then what is the purpose of the value="add" attribute?

如果是这种情况,那么value =“add”属性的目的是什么?

Because on else if(action.equals("add")) , add was used.

因为在else if(action.equals(“add”)),使用了add。

What could the req.getParameter() return ?

req.getParameter()可以返回什么?

//get the current action
    String action = req.getParameter("action");

I'm asking because in the past I did some CRUD project on PHP where it used the ff to check if form has no null parameters.

我问,因为在过去我在PHP上做了一些CRUD项目,它使用ff检查表单是否没有空参数。

if(isset($_POST['btnSave'])){

}

<form method ="POST" action="index.php">
        <label>First Name<input type="text" name="firstname" required></label>
        <br /><br />
        <label>Last  Name<input type="text" name="lastname" required></label>
        <br /><br />
        <input type = "submit" name="btnSave" value="Save" />
        <input type = "submit" name="btnSearch" value="Search" />
    </form>

Instead, in the last form example it used the btnSave (form button) instead of a hidden input.

相反,在最后一个表单示例中,它使用btnSave(表单按钮)而不是隐藏输入。

I just don't see the point of using a value="add" and what req.getParameter("action") could return. Because it was used on the IF-ELSE

我只是没有看到使用value =“add”以及req.getParameter(“action”)可以返回的内容。因为它被用在IF-ELSE上

I'd appreciate any explanation.

我很感激任何解释。

Thank you.

2 个解决方案

#1


1  

Covering your questions in reverse order:

以相反的顺序覆盖您的问题:

What could the req.getParameter() return ?

req.getParameter()可以返回什么?

It could return anything. The <form> you posted will generate a request to the server that looks like this:

它可以返回任何东西。您发布的

将生成对服务器的请求,如下所示:

POST /emailList HTTP/1.1
Host: example.com
Cache-Control: no-cache

action=add&email=MyEmail&firstName=MyFirstName&lastName=MyLastName&submit=Join Now

Now, consider the case where someone submits the following request instead:

现在,考虑有人提交以下请求的情况:

POST /emailList HTTP/1.1
Host: example.com
Cache-Control: no-cache

action=edit&id=1&email=NewEmail&firstName=TypoFreeName&lastName=TypoFreeLastName&submit=Update Details

Since you don't have an "edit" case in your servlet, but you do have that if check, your servlet will just redirect to /index.html instead of changing a user's details or inserting a new user.

由于您的servlet中没有“编辑”案例,但是如果检查了,那么您的servlet只会重定向到/index.html,而不是更改用户的详细信息或插入新用户。

A logical next step for code like this would be to add new sections to your servlet:

像这样的代码的逻辑下一步是向servlet添加新的部分:

if(action.equals("join")){
    url = "/index.html"; //the join page
}
else if (action.equals("delete") {
    //Call UserDB.delete()
}
else if (action.equals("edit") {
    //Call UserDB.update()
}
else if(action.equals("add")){
    ...
}

what is the purpose of the value="add" attribute?

value =“add”属性的目的是什么?

It's partly to control the flow of your servlet and partly to act as an error prevention measure; if the request includes action=add, you proceed with the assumption that you'll have the other form elements (better practice would be to check to make sure that firstName, lastName, and email are set in the request before calling UserDB).

它部分用于控制servlet的流量,部分用于防止错误措施;如果请求包含action = add,则继续假设您将拥有其他表单元素(更好的做法是检查以确保在调用UserDB之前在请求中设置firstName,lastName和email)。

#2


1  

The code is frankly a bit odd. It appears to be designed to handle the case where a different form (without an action field) is POSTed to the servlet, and to handle it by presenting the index.html page. Perhaps there's another form somewhere else in the chapter that does that?

代码坦率地说有点奇怪。它似乎旨在处理将不同形式(没有操作字段)POST到servlet并通过呈现index.html页面来处理它的情况。或许在本章的其他地方有另一种形式可以做到这一点?

If the form in the question is posted to the server, the servlet will receive an action parameter. (Well, unless JavaScript code actively removes the input from the form first.) So getParameter("action") will not return null. It might (if JavaScript code changed the input's value) get a different string, even a "" string, but not null.

如果问题中的表单发布到服务器,则servlet将接收操作参数。 (好吧,除非JavaScript代码首先主动从表单中删除输入。)因此getParameter(“action”)不会返回null。它可能(如果JavaScript代码更改了输入的值)获得了不同的字符串,甚至是“”字符串,但不是null。

It's probably worth noting that it doesn't handle the possibility that a different form with an action=add field is posted to the server, and happily uses the other parameters without checking them server-side, which is poor practice. Validation must be done server-side.

值得注意的是,它没有处理将具有action = add字段的不同表单发布到服务器的可能性,并且愉快地使用其他参数而不检查它们的服务器端,这是不好的做法。验证必须在服务器端完成。

#1


1  

Covering your questions in reverse order:

以相反的顺序覆盖您的问题:

What could the req.getParameter() return ?

req.getParameter()可以返回什么?

It could return anything. The <form> you posted will generate a request to the server that looks like this:

它可以返回任何东西。您发布的

将生成对服务器的请求,如下所示:

POST /emailList HTTP/1.1
Host: example.com
Cache-Control: no-cache

action=add&email=MyEmail&firstName=MyFirstName&lastName=MyLastName&submit=Join Now

Now, consider the case where someone submits the following request instead:

现在,考虑有人提交以下请求的情况:

POST /emailList HTTP/1.1
Host: example.com
Cache-Control: no-cache

action=edit&id=1&email=NewEmail&firstName=TypoFreeName&lastName=TypoFreeLastName&submit=Update Details

Since you don't have an "edit" case in your servlet, but you do have that if check, your servlet will just redirect to /index.html instead of changing a user's details or inserting a new user.

由于您的servlet中没有“编辑”案例,但是如果检查了,那么您的servlet只会重定向到/index.html,而不是更改用户的详细信息或插入新用户。

A logical next step for code like this would be to add new sections to your servlet:

像这样的代码的逻辑下一步是向servlet添加新的部分:

if(action.equals("join")){
    url = "/index.html"; //the join page
}
else if (action.equals("delete") {
    //Call UserDB.delete()
}
else if (action.equals("edit") {
    //Call UserDB.update()
}
else if(action.equals("add")){
    ...
}

what is the purpose of the value="add" attribute?

value =“add”属性的目的是什么?

It's partly to control the flow of your servlet and partly to act as an error prevention measure; if the request includes action=add, you proceed with the assumption that you'll have the other form elements (better practice would be to check to make sure that firstName, lastName, and email are set in the request before calling UserDB).

它部分用于控制servlet的流量,部分用于防止错误措施;如果请求包含action = add,则继续假设您将拥有其他表单元素(更好的做法是检查以确保在调用UserDB之前在请求中设置firstName,lastName和email)。

#2


1  

The code is frankly a bit odd. It appears to be designed to handle the case where a different form (without an action field) is POSTed to the servlet, and to handle it by presenting the index.html page. Perhaps there's another form somewhere else in the chapter that does that?

代码坦率地说有点奇怪。它似乎旨在处理将不同形式(没有操作字段)POST到servlet并通过呈现index.html页面来处理它的情况。或许在本章的其他地方有另一种形式可以做到这一点?

If the form in the question is posted to the server, the servlet will receive an action parameter. (Well, unless JavaScript code actively removes the input from the form first.) So getParameter("action") will not return null. It might (if JavaScript code changed the input's value) get a different string, even a "" string, but not null.

如果问题中的表单发布到服务器,则servlet将接收操作参数。 (好吧,除非JavaScript代码首先主动从表单中删除输入。)因此getParameter(“action”)不会返回null。它可能(如果JavaScript代码更改了输入的值)获得了不同的字符串,甚至是“”字符串,但不是null。

It's probably worth noting that it doesn't handle the possibility that a different form with an action=add field is posted to the server, and happily uses the other parameters without checking them server-side, which is poor practice. Validation must be done server-side.

值得注意的是,它没有处理将具有action = add字段的不同表单发布到服务器的可能性,并且愉快地使用其他参数而不检查它们的服务器端,这是不好的做法。验证必须在服务器端完成。