Servlet中接收和返回数据


public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } @Override public void init() throws ServletException { System.out.println("进入 服务器..."); } }

  

我们可以看到HttpServletRequest, HttpServletResponse这两个对象。可以说,这是JavaWeb中至关重要的两个对象。接下来,我们来做一个简短的说明:

1、HttpServletRequest

request对象(HttpServletRequest)代表客户端的请求,当客户端通过HTTP协议访问服务器
时,HTTP请求头中的所有信息都封装在这个对象中,通过这个对象提供的方法,可以获得客户端请求的所有信息。

其中,请求头就是Request Headers. 我们还可以看到请求的方式是Get方式,通过浏览器地址栏的方式就是GET方式。现在,我们改变在请求的同时加入一点信息:

http://localhost/wzry/login.do?username=admin&password=123&type=weixin


在请求地址后面加一个 ?,开始拼接数据,每一个数据都是key=value 的形式,不同数据之间用 & 连接。再次回车。我们可以看到信息发生了变化:

不论你是什么请求,你往服务器传递的数据只能是 字符串!

现在,我们可以在Servlet中接收这些参数!

@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String username=req.getParameter("username");
		String password=req.getParameter("password");
		String type=req.getParameter("type");
		System.out.println("用户登录...");
		System.out.println(username);
		System.out.println(password);
		System.out.println(type);
		
	}

  

运行结果:

正常情况下,为了保存这些数据,我们都会各自建立一个Java类,比如用户类。我们为了方便起见,可以采用一种公用的数据结构来保存,那就是Map。从道理上也能明白吧,客户端传递数据到我们的服务器,我们是不是首先得想办法把它存起来?好像给你一筐鸡蛋,然后他说,鸡蛋给你,框子我得拿走,那么你是不是得找一个容器,把鸡蛋装起来呢?不就是这个道理嘛。

Map就是这么一个容器。
修改后的代码:

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		String type = req.getParameter("type");
		System.out.println("用户登录...");
		
		System.out.println(username);
		System.out.println(password);
		System.out.println(type);
		
		System.out.println("开始存入map...");
		Map<String,Object> map=new HashMap<>();
		map.put("username", username);
		map.put("password", password);
		map.put("type", type);
		System.out.println("存入map成功!");
		System.out.println(map);
	}

  

在实际的开发中,传进来的数据肯定是不一样的,如果我们太依赖于getParameter这个方法,就无法做到灵活变通。那么有没有一种通用的方法,让request对象中附带的数据自动转换为Map呢?

我已经封装好了一个工具类,里面就有这样的方法。

public static Map<String,Object> getParameters(HttpServletRequest req){
		Map<String,Object> map=new HashMap<>();
		Enumeration<String> names = req.getParameterNames();
		while (names.hasMoreElements()) {
			String key=names.nextElement();	//获取key值
			map.put(key, req.getParameter(key));	//获取value值
		}
		return map;
	}

  

于是请求参数的获取就变得很简单了

@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("用户登录...");
		System.out.println("开始存入map...");
		Map<String,Object> map=StringUtils.getParameters(req);
		System.out.println("存入map成功!");
		System.out.println(map);
	}

  

2、HttpServletResponse

Web服务器收到客户端的http请求,会针对每一次请求,分别创建一个用于代表请求的request对象(HttpServletRequest)、和代表响应的response对象(HttpServletResponse)。
request和response对象即代表请求和响应,那我们要获取客户机提交过来的数据,只需要找request对象就行了。要向客户机输出数据,只需要找response对象就行了。

在刚才的例子中,我们添加以下代码:

		resp.setContentType("text/html;charset=utf-8");
		PrintWriter writer = resp.getWriter();
		writer.println("登录成功!");

  页面效果:

我们通过这种方式,就可以往客户端发送一个数据。

刚才讲了GET方式提交可以直接在浏览器地址栏操作,GET方式提交的缺点就是会暴露自己的数据信息,还有一种POST提交的方式。相比GET方式要安全一点,它不会直接暴露数据。现在我们通过form表单来做一个讲解。
在WebContent目录下新建一个index.jsp。

编写form表单:

	<!-- post提交表单 -->
	<form action="login.do" name="myform" method="post" onsubmit="check();">
		<table>
			<tr>
				<td>用户名:</td>
				<td><input type="text" name="username" id="username" /></td>
			</tr>
			<tr>
				<td>密码:</td>
				<td><input type="password" name="password" id="password" /></td>
			</tr>
		</table>
		<input type="submit" value="提交"/>
		<input type="hidden" name="type" value="weixin" />
	</form>

  

我们一般还需要在后台进行一个验证。

我们故意不填写用户名和密码,点击登录按钮,结果并没有什么卵用。因为其实传递到后台是有值的,只是为””,这一点和js不同,在Java中,””不等于假,它只是代表一个空字符串。所以我们需要修改一下验证条件。还有,为了不让代码继续往下执行,我们需要及时return。

 为了给用户返回错误信息,我们得把信息抛到页面上。

 

关注一下,这里有两个重复点,于是考虑封装。

/**
 * 工具类
 * @author Administrator
 *
 */
public class StringUtils {
	/**
	 * 是否为空
	 * @param o
	 * @return
	 */
	public static boolean isEmpty(Object o){
		if(o==null)return true;
		if("".equals(o))return true;
		return false;
	}
	
	/**
	 * 不为空
	 * @param o
	 * @return
	 */
	public static boolean isNotEmpty(Object o){
		return !isEmpty(o);
	}
	
	/**
	 * 输出信息到页面
	 * @param resp
	 * @param o
	 */
	public static void writeObject(HttpServletResponse resp,Object o){
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter writer=null;
		try {
			writer= resp.getWriter();
			writer.println(o);
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			writer.flush();
			writer.close();
		}
	}
	
	/**
	 * 获取请求参数
	 * @param req
	 * @return
	 */
	public static Map<String,Object> getParameters(HttpServletRequest req){
		Map<String,Object> map=new HashMap<>();
		Enumeration<String> names = req.getParameterNames();
		while (names.hasMoreElements()) {
			String key=names.nextElement();	//获取key值
			map.put(key, req.getParameter(key));	//获取value值
		}
		return map;
	}
}

  

封装之后代码简洁很多了

@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("用户登录...");
		System.out.println("开始存入map...");
		Map<String,Object> map=StringUtils.getParameters(req);
		System.out.println("存入map成功!");
		System.out.println(map);
		
		if(StringUtils.isEmpty(map.get("username"))){
			StringUtils.writeObject(resp,"用户名不能为空!");
			System.out.println("用户名不能为空!");
			return;
		}
		if(StringUtils.isEmpty(map.get("password"))){
			StringUtils.writeObject(resp,"密码不能为空!");
			System.out.println("密码不能为空!");
			return;
		}
		StringUtils.writeObject(resp,"登录成功!");
	}

  

 参考:https://www.cnblogs.com/skyblue-li/p/8251225.html

原文地址:https://www.cnblogs.com/1906859953Lucas/p/10828316.html