javaweb用户密码的封装

问题?在我们用表单的时候时常会遇到封装一些用户密码之类的数据这一个问题。
           这里就交给大家几个便捷方法。有常用的封装方法,也有利用开源框架BeanUtilse框架来封装方法的。

说明:

常用表单数据的获取
1.表单输入域类型:
radio checkbox,即使表单中有对应名称输入域,如果一个不选择,则什么数据不会带给服务器。(注 意空指针异常)
如果选择了其中的一个或多个,则把他们的value的取值提交给服务器。
如果选择了其中的一个或多个,他们又没有value取值,则提交给服务器的值是on.


2.请求参数的编码:
浏览器当前使用什么编码,就以什么编码提交请求参数。<meta http-equiv="content-type" content="text/html; charset=UTF-8">

request.setCharacterEncoding(编码):通知程序,客户端提交的数据使用的编码。但是只对POST请 求方式有效

3.如果是get请求提交数据,编码就是ISO-8859-1

4.Tips:目前采用POST提交方式。


举个例子:

再举封装方法之前,我们先看看HttpServletRequest中的request对象有哪些方法

package com.dp.java.Rquest;

import java.io.IOException;
import java.io.PrintWriter;

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

/**
 * HttpRequest的常用方法的使用
 *
 */
public class RequestDom1 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		PrintWriter pr=response.getWriter();
		String url=request.getRequestURL().toString();
		//协议:主机和端口 http://localhost:8080/day7/servlet/RequestDom1
		
		String uri=request.getRequestURI();
		//得到请求资源地址/day7/servlet/RequestDom1
		
		String queryString =request.getQueryString();//get请求的参数字符串:如;表单中的username、password
		String remoteAddr =request.getRemoteAddr();
		int remotePort= request.getRemotePort();//得到客户端的端口号,注:不是服务器端口号8080
		String method =request.getMethod();//请求方式走的是什么方法:如get或者post
		
		pr.println("URL:"+url);
		pr.println("uri:"+uri);
		pr.println("queryString:"+queryString);
		pr.println("remoteAddr:"+remoteAddr);
		pr.println("remotePort:"+remotePort);
		pr.println("method:"+method);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}
首先是jsp或者html文件。


 
<%@ page language="java" import="java.util.*" pageEncoding="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 'index.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">
	-->
  </head>
  
  <body>
  <form action="/day7/servlet/RequestDom2" method="post">     <br>
  		用  户 名:<input type="text" name="username">     <br>
  		密      码:<input type="password" name="password">     <br>
  		确认密码:<input type="password" name="password">     <br>
  		性      别:<input type="text" name="gen">     <br>
  		<input type="submit"  value="提交">
  </form>

  </body>
</html>



然后是映射文件xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>day7</display-name>

  <servlet>
    <servlet-name>RequestDom2</servlet-name>
    <servlet-class>com.dp.java.Rquest.RequestDom2</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>RequestDom2</servlet-name>
    <url-pattern>/servlet/RequestDom2</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>  
  </welcome-file-list>
</web-app>

最后是我们的HttpServlet中的service请求处理servlet类
第一种方法(只需要得到客户端的值,但不需要封装):
1.最常用的获取用户名及密码的


import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;

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

import org.apache.commons.beanutils.BeanUtils;

import com.dp.java.Bean.User;

public class RequestDom2 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		test1(request, response);
	}
         //获取指定单一参数的值
	private void test1(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter pri=response.getWriter();
		String name=request.getParameter("username");
		String password=request.getParameter("password");
		pri.write("用户名:"+name+"  密码:"+password);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}



2.种方法(加入碰到需要再次输入密码呢,也就是重复参数的时候):


package com.dp.java.Rquest;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;

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

import org.apache.commons.beanutils.BeanUtils;

import com.dp.java.Bean.User;

public class RequestDom2 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		test1(request, response);

	}
	//获取指定重名参数的值
		private void test1(HttpServletRequest request, HttpServletResponse response)
				throws ServletException, IOException {
			response.setHeader("Content-Type", "text/html;charset=UTF-8");
			response.setCharacterEncoding("UTF-8");
			PrintWriter pri=response.getWriter();
			String name[]=request.getParameterValues("username");
			String password[]=request.getParameterValues("password");
			for(String s:name){
				pri.write("用户名:"+s);
			}
			for(String s1:password){
				pri.write("  密   码:"+s1);
			}
		}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}



3.方法(得到客户端所有参数及值):

package com.dp.java.Rquest;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;

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

import org.apache.commons.beanutils.BeanUtils;

import com.dp.java.Bean.User;

public class RequestDom2 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		test1(request, response);

	}
	private void test1(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter pri=response.getWriter();
		Enumeration e=request.getParameterNames();//得到所有参数的对象树
		while(e.hasMoreElements()){
			String username=e.nextElement().toString();
			String[] password=request.getParameterValues(username);
//			String password=request.getParameter(username);
			pri.write("用户名:"+username+"  密码:"+Arrays.asList(password));
		}
			
		
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}



第二种方法(实际开发中将得到的参数值,封装到javaBean的类中):
引入bean类
注:表单域总的名称必须和javaBean中的属性名相同(很重要)


package com.dp.java.Bean;

import java.util.Arrays;

public class User {
	String username;
	String password[];
	String gen;
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String[] getPassword() {
		return password;
	}
	public void setPassword(String[] password) {
		this.password = password;
	}
	public String getGen() {
		return gen;
	}
	public void setGen(String gen) {
		this.gen = gen;
	}
	@Override
	public String toString() {
		return "User [username=" + username + ", password="
				+ Arrays.toString(password) + ", gen=" + gen + "]";
	}

	
	

}

如何将数据封装到bean类中呢?也有几个方法(下面所有方法均封装到bean类中)
1.实际开发汇中将得到的参数值,封装到javaBean中


package com.dp.java.Rquest;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;

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

import org.apache.commons.beanutils.BeanUtils;

import com.dp.java.Bean.User;

public class RequestDom2 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		test1(request, response);

	}

//实际开发汇中将得到的参数值,封装到javaBean中
	private void test1(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");//设置响应编码为中文编码
		request.setCharacterEncoding("UTF-8");//设置请求编码为中文编码
		User us=new User();
		System.out.println("封装前:"+us);
		
		 Enumeration e=request.getParameterNames();
		 //这个方法用来封装,显然不好,得根据参数才能封装。
//		 while(e.hasMoreElements()){
//			 String username=(String)e.nextElement();
//			 String pass[]=request.getParameterValues(username);
//			 if("username".equals(username)){
//				 us.setUsername(pass[0]);
//			 }
//			 if("password".equals(username)){
//				 us.setPassword(pass);
//			 }
//			 	 
//		 }
		 //更加有效率容易维护的方法。表单域总的名称必须和javaBean中的属性名相同。
		 while(e.hasMoreElements()){
			 String parname=(String)e.nextElement();
			 String value[]=request.getParameterValues(parname);
			 try {
				 //将javaBean类与得到的参数名称产生一个映射
				 //PropertyDescriptor 描述 Java Bean 通过一对存储器方法导出的一个属性。
				PropertyDescriptor pro=new PropertyDescriptor(parname, User.class);
				Method m=pro.getWriteMethod();//获得应该用于写入属性值的setter方法
				if(!(value.length>1)){
					m.invoke(us, value);//这里写成value[0]或者value都可以,因为就一个值
				}else{
					//invoke指带有指定参数的指定对象调用由此 Method 对象表示的底层方法。
					//个别参数被自动解包,以便与基本形参相"匹配",基本参数和引用参数都随需服从方法调用转换。 
					m.invoke(us, (Object)value);
				}
				
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		 }
		 System.out.println("封装后:"+us);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}

2.运用getParameterMap()方法封装到javaBean中

package com.dp.java.Rquest;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;

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

import org.apache.commons.beanutils.BeanUtils;

import com.dp.java.Bean.User;

public class RequestDom2 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		test1(request, response);

	}

//实际开发汇中将得到的参数值,运用getParameterMap()方法封装到javaBean中
		private void test1(HttpServletRequest request, HttpServletResponse response)
				throws ServletException, IOException {
			response.setContentType("text/html;charset=UTF-8");//设置响应编码为中文编码
			request.setCharacterEncoding("UTF-8");//设置请求编码为中文编码
			User us=new User();
			System.out.println("封装前:"+us);
			
			Map<String, String[]> map=request.getParameterMap();
			for(Map.Entry<String, String[]> m:map.entrySet()){
				String parname=m.getKey();
				String value[]=m.getValue();
				
				try {
					PropertyDescriptor pr=new PropertyDescriptor(parname, User.class);
					Method method=pr.getWriteMethod();
					if(!(value.length>1)){
						method.invoke(us, value);
					}
					else{
						method.invoke(us, (Object)value);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				
				
			}
			System.out.println("封装后:"+us);
			
		}
		
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}




3.利用BeanUtils框架(需要导入BeanUtils的jar包)来封装,这种方法最简单,但是却需要用到开源框架,
我们需要导入两个必须的BeanUtils包(第一个:commons-beanutils-1.8.3.jar。第二个:commons-logging-1.1.1.jar)这两个包在我上传的资源中有供下载。也可以去BeanUtils官网下载(解压后就有这两个包)


package com.dp.java.Rquest;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;

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

import org.apache.commons.beanutils.BeanUtils;

import com.dp.java.Bean.User;

public class RequestDom2 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		test1(request, response);

	}

//实际开发汇中将得到的参数值,封装到javaBean中,更加简单的方法,
	//利用BeanUtils框架(需要导入BeanUtils的jar包)来封装
			private void test1(HttpServletRequest request, HttpServletResponse response)
					throws ServletException, IOException {
				response.setContentType("text/html;charset=UTF-8");//设置响应编码为中文编码
				request.setCharacterEncoding("UTF-8");//设置请求编码为中文编码
				User us=new User();
				System.out.println("封装前:"+us);
				try {
					BeanUtils.populate(us, request.getParameterMap());
				} catch (Exception e){
					e.printStackTrace();
				}
				
				System.out.println("封装后:"+us);
				
			}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}

4.折是一个题外方法,一般我们不用它(以流的形式来得到客户端正文输入内容)


package com.dp.java.Rquest;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;

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

import org.apache.commons.beanutils.BeanUtils;

import com.dp.java.Bean.User;

public class RequestDom2 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		test1(request, response);

	}
	
	//以流的形式来得到正文输入内容
	private void test1(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");//设置响应编码为中文编码
		request.setCharacterEncoding("UTF-8");//设置请求编码为中文编码
		User us=new User();
		ServletInputStream in=request.getInputStream();
		int len=-1;
		byte b[]=new byte[1024];
		while((len=in.read(b))!=-1){
			System.out.println(new String(b, 0, len));
		}
		in.close();
		                  	                  
		                  
		
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}




                     javaweb用户密码的封装_第1张图片


最后我们一个总例子,这个例子主要讲表单元素中的数据提交,想要加多少表单元素都可以,我们都可以进行封装(注:表单域总的名称必须和javaBean中的属性名相同(很重要))每次加入表单元素时,只需要在javabean中相应添加相同名字的属性并get/set和tostring方法就可以了。4

这样的例子,有利于在开发过程中的维护和修改。

package com.dp.java.Bean;

import java.util.Arrays;

public class User1 {
	private int id;
	private String username;
	private String password;
	private String gen;
	private boolean marry=true;
	private String[] hobby;
	private String city;
	private String descript;
	
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getGen() {
		return gen;
	}
	public void setGen(String gen) {
		this.gen = gen;
	}
	
	public boolean isMarry() {
		return marry;
	}
	public void setMarry(boolean marry) {
		this.marry = marry;
	}
	public String[] getHobby() {
		return hobby;
	}
	public void setHobby(String[] hobby) {
		this.hobby = hobby;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public String getDescript() {
		return descript;
	}
	public void setDescript(String descript) {
		this.descript = descript;
	}
	
	
	@Override
	public String toString() {
		return "User1 [id=" + id + ", username=" + username + ", password="
				+ password + ", gen=" + gen + ", marry=" + marry + ", hobby="
				+ Arrays.toString(hobby) + ", city=" + city + ", descript="
				+ descript + "]";
	}
}


<%@ page language="java" import="java.util.*" pageEncoding="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 'MyJsp1.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">
	-->

  </head>
  
  <body>
    <form action="/day7/servlet/RequestDom3" method="post">
		用  户 名:<input type="text" name="username">     <br>
  		密      码:<input type="password" name="password">     <br>
  		性      别:<input type="radio" name="gen"  value="0">男   
  		                <input type="radio" name="gen"  value="1">女<br>
  		                <input type="checkbox"  value="marry">已婚<br>
  		                <input type="checkbox"  value="zq"  name="hobby">足球<br>
  		                <input type="checkbox"  value="lq" name="hobby">篮球<br>
  		                <input type="checkbox"  value="ppq" name="hobby">乒乓球<br>
  		                <select name="city">
  		                	<option value="BJ">北京</option>
  		                	<option value="SD">山东</option>
  		                	<option value="SH">上海</option>
  		                </select><br>
  		                <textarea rows="3" cols="20" name="descript"></textarea><br>
  		                <input type="hidden" name="id" value="看不见的"><br>
  		                <input type="image" src="1.jpg">
  		<input type="submit"  value="提交" width="50px" height="80px">
	</form>
  </body>
</html>



package com.dp.java.Rquest;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

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

import org.apache.commons.beanutils.BeanUtils;

import com.dp.java.Bean.User1;

public class RequestDom3 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
		User1 us=new User1();
		System.out.println("封装前:"+us);
		try {
			BeanUtils.populate(us, request.getParameterMap());
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("封装后:"+us);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}

结果显示:




你可能感兴趣的:(java,Web,表单数据的封装与得到)