首页 > 代码库 > JSP简单练习-用Servlet获取表单数据

JSP简单练习-用Servlet获取表单数据

// javaBean代码
package servlet;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class AcceptUserRegist extends HttpServlet {
	public String codeToString(String str)  // 处理中文字符串的函数
	{
		String s=str;
		try
		{
			byte tempB[]=s.getBytes("ISO-8859-1");
			s=new String(tempB);
			return s;
		}catch(Exception e)
		{
			return s;
		}
	}
	
	public void init(ServletConfig config) throws ServletException
	{
		super.init(config);
	}
	
	public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
		// 设置mime
		response.setContentType("text/html;charset=GB2312");
		PrintWriter out=response.getWriter();
		out.println("<html><head><title>接收新用户注册</title></head> <body>");
		out.println("这是新用户注册所提交的数据:<br>");
		out.println("用户名是:"+codeToString(request.getParameter("username"))+"<br>");
		out.println("密码是:"+codeToString(request.getParameter("userpassword"))+"<br>");
		out.println("性别是:"+codeToString(request.getParameter("sex"))+"<br>");
		out.println("出生年月是:"+request.getParameter("year")+request.getParameter("month")+request.getParameter("day")+"<br>");
		out.println("电子邮箱是:"+request.getParameter("E-mail")+"<br>");
		out.println("家庭住址是:"+codeToString(request.getParameter("address"))+"<br>");
		out.print("</body> </html>");
	}

}

<!-- servletform.jsp -->
<%@ page contentType="text/html;charset=gb2312" %>
<script language="javascript">
   function on_submit()  // 验证数据的合法性
   {
      if(form1.username.value=http://www.mamicode.com/="")>另外,在web.xml文件的<web-app>与</web-app>中加入如下配置:

  <servlet>
     <servlet-name>acceptUserRegist</servlet-name>
     <servlet-class>servlet.AcceptUserRegist</servlet-class>
  </servlet>
  <servlet-mapping>
     <servlet-name>acceptUserRegist</servlet-name>
     <url-pattern>/acceptUserRegist</url-pattern>
  </servlet-mapping>
输入网址:localhost:8080/jspdemo/servletform.jsp

填写信息~ 如下:

提交后,显示页面如下: