使用servlet从我的JSP页面获取值

时间:2013-09-10 06:57:52

标签: jsp servlets

我正在尝试从我的注册表单中获取详细信息,使用servlet然后显示所有现有用户。 我知道我在servlet中出错了。无法真正找到答案。

这是我的reg.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Registration</title>
    </head>
    <body>
        <form method="post" action="UserController.java">
            <center>
            <table border="1" width="30%" cellpadding="5">
                <thead>
                    <tr>
                        <th colspan="2">Enter Information Here</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>First Name</td>
                        <td><input type="text" name="fname" value="" /></td>
                    </tr>
                    <tr>
                        <td>Last Name</td>
                        <td><input type="text" name="lname" value="" /></td>
                    </tr>
                    <tr>
                        <td>Email</td>
                        <td><input type="text" name="email" value="" /></td>
                    </tr>
                    <tr>
                        <td>User Name</td>
                        <td><input type="text" name="uname" value="" /></td>
                    </tr>
                    <tr>
                        <td>Password</td>
                        <td><input type="password" name="pass" value="" /></td>
                    </tr>
                    <tr>
                        <td><input type="submit" value="Submit" /></td>
                        <td><input type="reset" value="Reset" /></td>
                    </tr>
                    <tr>
                        <td colspan="2">Already registered!! <a href="index.jsp">Login Here</a></td>
                    </tr>
                </tbody>
            </table>
            </center>
        </form>
    </body>
</html>

这是我的servlet代码

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.SwingUtilities;
import com.shreya.dao.UserDao;
import com.shreya.model.Details;
import com.shreya.model.User;

public class UserController extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static String INSERT_OR_EDIT = "/user.jsp";
    private static String LIST_USER = "/listUser.jsp";
    private UserDao dao;

    public UserController() {
        super();
        dao = new UserDao();
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        String forward="";
String act = request.getParameter("act");
         if (act != null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("login")) {
            forward= "/Login.jsp";
            }

         else if (act != null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("delete"))
        {
            int userId = Integer.parseInt(request.getParameter("userId"));
            dao.deleteUser(userId);
            forward = LIST_USER;
            request.setAttribute("users", dao.getAllUsers());    
        } else if (act!=null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("edit")){
            forward = INSERT_OR_EDIT;
            int userId = Integer.parseInt(request.getParameter("userId"));
            User user1 = dao.getUserById(userId);
            request.setAttribute("user", user1);
        } else if (act!=null && !act.equalsIgnoreCase("null") && act.equalsIgnoreCase("listUser")){
            forward = LIST_USER;
            request.setAttribute("users", dao.getAllUsers());
        } else 
            forward = "/Login.jsp";

                RequestDispatcher view = request.getRequestDispatcher(forward);
        view.forward(request, response);

    }


        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = new User();
        Details details = new Details();
        user.setFirstName(request.getParameter("firstName"));
        user.setLastName(request.getParameter("lastName"));
        details.setUsername(request.getParameter("username"));
        details.setPassword(request.getParameter("password"));
      //  details.setId(request.getParameter("id"));
        String str=request.getParameter("username");
        String str1=request.getParameter("password");



if(str.equalsIgnoreCase("shreya")&&str1.equalsIgnoreCase("singh"))
         System.out.println("Login!");
     else
     {
      System.out.println("Login failed!");


      request.setAttribute("users",dao.getAllUsers());

            request.getRequestDispatcher("/listUser.jsp").forward(request, response); 

        }
     }
}

编辑1:

else if (act!=null && !act.equalsIgnoreCase("null") &&    act.equalsIgnoreCase("register")){
        forward = LIST_USER;
        request.setAttribute("users", dao.getAllUsers());

传递了一个动作寄存器来保存doGet方法中的值。 我如何在dopost中进行相应的修改?

1 个答案:

答案 0 :(得分:0)

改变这个:

details.setUsername(request.getParameter("username"));
details.setPassword(request.getParameter("password"));

到此:

details.setUsername(request.getParameter("uname"));
details.setPassword(request.getParameter("pass"));

输入的名称必须与您获得的请求参数的名称相匹配。

编辑:一些基本建议:

不直接访问请求参数进行存储,准备一个简单的实用函数来处理空值。请求参数在未发出时将为null,但如果为空,则为“”。

枚举请求参数名称的公共静态字符串常量,代码中包含魔术字符串可能会导致对其失去控制:

public static String PARAM_USERNAME = "uname";
public static String PARAM_PASSWORD = "pass";

如果参数是必需的,只需检查它是否具有实际值并处理错误/情况,在servlet中具有原始异常可能是以后调试的痛苦。

预见请求转储方法(保留在Utility类中)只是为了注销所有请求参数,属性和HTTP头,在调试时会为您节省大量的这些情况。

EDIT2:尝试调用此doPost方法并查看会发生什么(将参数的名称更改为正确的名称):

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    PrintWriter out = response.getWriter();
    try {
        out.println("Dumping Request");
        Enumeration<?> paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String paramName = (String)paramNames.nextElement();
            String paramValue = request.getParameter(paramName);
            out.println("   " + paramName + ": " + paramValue);
        }

        // User user = new User();
        // Details details = new Details();
        // user.setFirstName(request.getParameter("firstName"));
        // user.setLastName(request.getParameter("lastName"));
        // details.setUsername(request.getParameter("username"));
        // details.setPassword(request.getParameter("password"));
        //  details.setId(request.getParameter("id"));
        // String str = request.getParameter("username");
        // String str1 = request.getParameter("password");

        // if (str.equalsIgnoreCase("shreya") && str1.equalsIgnoreCase("singh"))
        //     System.out.println("Login!");
        // else
        // {
        //     System.out.println("Login failed!");    
        //     request.setAttribute("users", dao.getAllUsers());    
        //     request.getRequestDispatcher("/listUser.jsp").forward(request, response);    
        // }
    } catch (Throwable t) {
        out.println("Exception in servlet");
        t.printStackTrace(out);
    }
}