Servlet基础(3)

Servlet获取表单数据
首先有两个静态页面,reg.jsp和userinfo.jsp,分别是注册页面和注册成功之后显示注册信息的页面。

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'reg.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <style type="text/css">
     .label{
          width: 20%    
     }
     .controler{
          width: 80%    
     }
   </style>  
   <script type="text/javascript" src="js/Calendar3.js"></script>
  </head>

  <body>
    <h1>用户注册</h1>
    <hr>
    <form name="regForm" action="servlet/RegServlet" method="post" >
              <table border="0" width="800" cellspacing="0" cellpadding="0">
                <tr>
                    <td class="lalel">用户名:</td>
                    <td class="controler"><input type="text" name="username" /></td>
                </tr>
                <tr>
                    <td class="label">密码:</td>
                    <td class="controler"><input type="password" name="mypassword" ></td>

                </tr>
                <tr>
                    <td class="label">确认密码:</td>
                    <td class="controler"><input type="password" name="confirmpass" ></td>

                </tr>
                <tr>
                    <td class="label">电子邮箱:</td>
                    <td class="controler"><input type="text" name="email" ></td>

                </tr>
                <tr>
                    <td class="label">性别:</td>
                    <td class="controler"><input type="radio" name="gender" checked="checked" value="Male"><input type="radio" name="gender" value="Female"></td>

                </tr>

                <tr>
                    <td class="label">出生日期:</td>
                    <td class="controler">
                      <input name="birthday" type="text" id="control_date" size="10"
                      maxlength="10" onclick="new Calendar().show(this);" readonly="readonly" />
                    </td>
                </tr>
                <tr>
                    <td class="label">爱好:</td>
                    <td class="controler">
                    <input type="checkbox" name="favorite" value="nba"> NBA &nbsp;
                      <input type="checkbox" name="favorite" value="music"> 音乐 &nbsp;
                      <input type="checkbox" name="favorite" value="movie"> 电影 &nbsp;
                      <input type="checkbox" name="favorite" value="internet"> 上网 &nbsp;
                    </td>
                </tr>
                <tr>
                    <td class="label">自我介绍:</td>
                    <td class="controler">
                        <textarea name="introduce" rows="10" cols="40"></textarea>
                    </td>
                </tr>
                <tr>
                    <td class="label">接受协议:</td>
                    <td class="controler">
                        <input type="checkbox" name="isAccept" value="true">是否接受霸王条款
                    </td>
                </tr>
                <tr>
                    <td colspan="2" align="center">
                        <input type="submit" value="注册"/>&nbsp;&nbsp;
                        <input type="reset" value="取消"/>&nbsp;&nbsp;
                    </td>
                </tr>
              </table>
            </form>
  </body>
</html>
<%@ page language="java" import="java.util.*,java.text.*" contentType="text/html; charset=utf-8"%>

<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'userinfo.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <style type="text/css">
     .title{
         width: 30%;    
         background-color: #CCC;
         font-weight: bold;
     }
     .content{
         width:70%;
         background-color: #CBCFE5;
     }

   </style>  
  </head>

  <body>
    <h1>用户信息</h1>
    <hr>
    <center>
     <jsp:useBean  id="regUser" class="entity.Users" scope="session"/>   
     <table width="600" cellpadding="0" cellspacing="0" border="1">
        <tr>
          <td class="title">用户名:</td>
          <td class="content">&nbsp;<jsp:getProperty name="regUser" property="username"/></td>
        </tr>
        <tr>
          <td class="title">密码:</td>
          <td class="content">&nbsp;<jsp:getProperty name="regUser" property="mypassword"/></td>
        </tr>
        <tr>
          <td class="title">性别:</td>
          <td class="content">&nbsp;<jsp:getProperty name="regUser" property="gender"/></td>
        </tr>
        <tr>
          <td class="title">E-mail:</td>
          <td class="content">&nbsp;<jsp:getProperty name="regUser" property="email"/></td>
        </tr>
        <tr>
          <td class="title">出生日期:</td>
          <td class="content">&nbsp;
            <% 
               SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
               String date = sdf.format(regUser.getBirthday());

            %>
             <%=date%>
          </td>
        </tr>
        <tr>
          <td class="title">爱好:</td>
          <td class="content">&nbsp;
            <% 
               String[] favorites = regUser.getFavorites();
               for(String f:favorites)
               {
            %>
                <%=f%> &nbsp;&nbsp;
            <% 
               }
            %>
          </td>
        </tr>
        <tr>
          <td class="title">自我介绍:</td>
          <td class="content">&nbsp;<jsp:getProperty name="regUser" property="introduce"/></td>
        </tr>
        <tr>
          <td class="title">是否介绍协议:</td>
          <td class="content">&nbsp;<jsp:getProperty name="regUser" property="flag"/></td>
        </tr>
     </table>
    </center>
  </body>
</html>

为了提交用户注册表单,我们建一个实体类(entity.Users),里边的属性应该为私有并且与表单里的一一对应。之后要将这些字段封装一下,右键->source->Generate Getters and Setters,全部都封装一下。之后最好再写一下不带参数的构造函数。字段的代码如下

private String username; //用户名
    private String mypassword; //密码
    private String email; //电子邮箱
    private String gender; //性别
    private Date birthday; //出生日期
    private String[] favorites; //爱好
    private String introduce; //自我介绍
    private boolean flag; //是否接受协议

然后要做一个处理用户注册的Servlet类,这里包名为servlet,类名为RegServlet,所以reg.jsp中的表单的action也对应为servlet/RegServlet。
由于表单是post方式请求,所以在doPost方法里处理。首先为了保证可以注册中文的信息,我们指定用utf-8。request.setCharacterEncoding("utf-8");然后既然是用户注册所以要先创建用户的实体类。Users u = new Users();再接收每个传过来的变量,如何接收?
以username为例,先设置一个变量String username;然后username=request.getParameter("username");,其他的变量都使用同样的方法。
不过Date类型的比较特殊,要首先进行转换,SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");,之后birthday = sdf.parse(request.getParameter("birthday"));
而对于字符串数组,使用的就不是request.getParameter而是request.getParameterValues。
然后我们将这些获取到的值传入到生成的用户对象当中,还是以username为例,u.setUsername(username);,这里的set方法就是之前封装字段时候的set方法。这里要注意,Boolean类型的变量最好不要用is开头,可以就用Flag,这样可以避免一些问题。
赋值完之后就是跳转,我们可以使用服务器内部跳转的方式跳转到注册成功页面request.getRequestDispatcher("../userinfo.jsp").forward(request,response);。这里..表示要跳转到外边一层的目录下,之后就可以在跳转到的页面来获取信息。在跳转之前要把注册成功的用户对象保存在session中request.getSession().setAttribute("regUser", u);这里的regUser是起的名字,把对象u给传进去。
整个完整的代码如下

package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

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

import entity.Users;

public class RegServlet extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public RegServlet() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doPost(request,response);
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");

        Users u = new Users();
        String username,mypassword,gender,email,introduce,isAccept;
        Date birthday;
        String[] favorites;


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try
        {
            username = request.getParameter("username");
            mypassword = request.getParameter("mypassword");
            gender = request.getParameter("gender");
            email = request.getParameter("email");
            introduce = request.getParameter("introduce");
            birthday = sdf.parse(request.getParameter("birthday"));
            if(request.getParameterValues("isAccpet")!=null)
            {
              isAccept = request.getParameter("isAccept");
            }
            else
            {
              isAccept = "false";
            }
            //用来获取多个复选按钮的值
            favorites = request.getParameterValues("favorite");
            u.setUsername(username);
            u.setMypassword(mypassword);
            u.setGender(gender);
            u.setEmail(email);
            u.setFavorites(favorites);
            u.setIntroduce(introduce);
            if(isAccept.equals("true"))
            {
                u.setFlag(true);
            }
            else
            {
                u.setFlag(false);
            }
            u.setBirthday(birthday);

            //把注册成功的用户对象保存在session中
            request.getSession().setAttribute("regUser", u);
            //跳转到注册成功页面
            request.getRequestDispatcher("../userinfo.jsp").forward(request,response);
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }


    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}

之后就是在userinfo.jsp中来获取信息。使用javaBean,javaBean使用jsp的useBean来获取,指定范围scope是session,id是regUser,还要指明是哪个类,class为entity.Users。<jsp:useBean id="regUser" class="entity.Users" scope="session"/>
然后以usernam为例显示用户名,<jsp:getProperty name="regUser" property="username"/>,name表示是哪个javaBean。
爱好是一个数组,需要遍历,这里代码如下

<% 
               String[] favorites = regUser.getFavorites();
               for(String f:favorites)
               {
            %>
                <%=f%> &nbsp;&nbsp;
            <% 
               }
            %>

然后是出生日期这一项也要进行转换,提前要把java.text.*导入进来。然后就可以使用SimpleDateFormat,代码如下

<% 
               SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
               String date = sdf.format(regUser.getBirthday());

            %>
             <%=date%>

如此,便完成了工作

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值