servlet(二)HttpServletRequest和HttpServletResponse参数的接收和响应

一、请求头信息:

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form method="get" action="demo">
		用户名:<input type="text" name="username"/>
		密码:<input type="password" name="pwd"/>
		<input type="checkbox" name="hob" value="打球">打球
		<input type="checkbox" name="hob" value="唱歌">唱歌
		<input type="checkbox" name="hob" value="跳舞">跳舞
		<input type="submit" value="提交" />
	</form>
</body>
</html>

 

 

package com.requstdemo;

import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name="MyDemo",urlPatterns="/demo")
public class MyDemo extends HttpServlet{
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");//设置请求字符集
		resp.setContentType("text/html;charset=utf-8");//设置响应字符集
		System.out.println("get方法");
		Enumeration<String> headNames=req.getHeaderNames();
		String str="<table border='1'>";
		while(headNames.hasMoreElements()){
			str+="<tr>";
			String name=headNames.nextElement();
			String value=req.getHeader(name);
			str+="<td>"+name+"</td>";
			str+="<td>"+value+"</td>";
			str+="</tr>";
		}
		str+="</table>";
		resp.getWriter().write(str);
	}
}


 

 

二、获取前台传值:

 

 

1、表单的action请求(id用于js,class用于css,name用于后台):

(1、)req.getParameter(arg)方法,参数为name值。例:

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="demo">
		用户名:<input type="text" name="username"/>
		密码:<input type="password" name="pwd"/>
		<input type="submit" value="提交" />
	</form>
</body>
</html>

 

package com.requstdemo;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name="MyDemo",urlPatterns="/demo")
public class MyDemo extends HttpServlet{

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");//设置请求字符集
		resp.setContentType("text/html;charset=utf-8");//设置响应字符集
		String username=req.getParameter("username");
		String pwd=req.getParameter("pwd");
		resp.getWriter().write(username+" "+pwd);
	}

}


(2、)req.getParameterNames()获取所有的name值,然后再利用上面(1、)中的方法获取value值。例:

 

 

package com.requstdemo;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name="MyDemo",urlPatterns="/demo")
public class MyDemo extends HttpServlet{

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");//设置请求字符集
		resp.setContentType("text/html;charset=utf-8");//设置响应字符集
		/*方法一
		String username=req.getParameter("username");
		String pwd=req.getParameter("pwd");
		resp.getWriter().write(username+" "+pwd);*/
		Enumeration<String> names=req.getParameterNames();
		while(names.hasMoreElements()){
			String name=names.nextElement();
			String value=req.getParameter(name);
			resp.getWriter().write(name+"  "+value);
		}
		
	}

}

(3、)req.getParameterValues(arg);用于获取一个name对应多个值的情况,如多选框:

 

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="demo">
		用户名:<input type="text" name="username"/>
		密码:<input type="password" name="pwd"/>
		<input type="checkbox" name="hob" value="打球">打球
		<input type="checkbox" name="hob" value="唱歌">唱歌
		<input type="checkbox" name="hob" value="跳舞">跳舞
		<input type="submit" value="提交" />
	</form>
</body>
</html>

 

 

package com.requstdemo;

import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name="MyDemo",urlPatterns="/demo")
public class MyDemo extends HttpServlet{

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");//设置请求字符集
		resp.setContentType("text/html;charset=utf-8");//设置响应字符集
		/*方法一
		String username=req.getParameter("username");
		String pwd=req.getParameter("pwd");
		resp.getWriter().write(username+" "+pwd);*/
		/*方法二
		Enumeration<String> names=req.getParameterNames();
		while(names.hasMoreElements()){
			String name=names.nextElement();
			String value=req.getParameter(name);
			resp.getWriter().write(name+"  "+value);
		}*/
		String[] hobs=req.getParameterValues("hob");
		resp.getWriter().write(Arrays.toString(hobs));
	}

}

(4、)前台传json数组给后台:

$.ajax({
               url:'./service/iposremoteapprove/caseToUser.do',
               data:{
                ds:JSON.stringify(data)   /* 特别需要注意这里,需要现将json数组通过JSON.stringify()处理一下之后,才能作为我们需要的参数传过去
               },
               type:'post',
               dataType:"json",
               success:function(json){
                $.messager.alert("提示","成功","info");
               }
  });
java接收参数
String ds = request.getParameter("ds");
JSONArray json=JSONArray.fromObject(ds);
JSONObject jsonOne;
 Map<String,String> map=null;
for(int i=0;i<json.size();i++){
          updataMap = new HashMap<String,String>();
          jsonOne = json.getJSONObject(i);
          map.put("name", (String) jsonOne.get("name"));
          map.put("age", (String) jsonOne.get("age"));
 }

 

2、异步获取(ajax)。

 

例一、现在做一个异步登录的例子:

(1、)前台

register.html:

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>

<script type="text/javascript">
function fun(){
	
	var pwd=document.getElementById("pwd").value;
	
	var rpwd=document.getElementById("rpwd").value;
	if(pwd==rpwd){
		return true;
	}else{
		alert("密码不一样");
		return false;
	}
	 
}
</script>
</head>
<body>
<form method="post" action="register" onsubmit="return fun()">
		用户名:<input type="text" name="username"/>
		密码:<input type="password" name="pwd" id="pwd"/>
		确认密码:<input type="password" name="rpwd" id="rpwd"/>
		<input type="submit" value="注册" />
	</form>
	<div></div>
	
</body>
</html>


login.html:

 

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="assets/js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function(){
	$("form").submit(function(){
		var dt=$("form").serialize();
		$.post("login",dt,function(data){
			$("div").html(data);
			 if(data=="登录成功"){
				window.location.href="main.html";
			}else{
				alert(data);
			}  
			//alert(data);
		});
		
		return false;
	}); 
	 
})
</script>
</head>
<body>
<form method="post">
		用户名:<input type="text" name="username"/>
		密码:<input type="password" name="pwd"/>
		<input type="submit" value="登录" />
	</form>
	<a href="register.html">还没有账号,去注册</a>
	<div></div>
</body>
</html>

 

这里重点是这个submit事件,return false阻止表单自己提交(这句话要写在后面,不然它后面的ajax不执行了)。在ajax中,利用serialize方法把表单序列化,得到一组key-value值请求后台,后台接收并处理后response响应这个请求,返回data给这个函数,然后这个function(data)函数再对请求成功得到的data进行分析决定下一步。


(2、)Dao层:

 

package com.login.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import com.login.util.DbUtil;

public class UserDao {
//查询用户名是否存在
public int userByName(String username){
	int a=1;
	DbUtil dbUtil=new DbUtil();
	String sql="select * from login where name=?";
	ResultSet s=dbUtil.executeQuery(sql, username);
	try {
		if(s.next()){
			a=-1;
		}
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
    dbUtil.close();
	return a;
}

public int register(String name, String pwd) {
	DbUtil dbUtil=new DbUtil();
	int b=0;
	String sql="insert into login(name,pwd) values(?,?)";
	b=dbUtil.executeUpdate(sql, name,pwd);
	dbUtil.close();
	return b;
}

public int login(String username, String pwd) {
	int a=-1;
	DbUtil dbUtil=new DbUtil();
	String sql="select * from login where name=? and pwd=?";
	ResultSet resultSet=dbUtil.executeQuery(sql, username,pwd);
	try {
		if(resultSet.next()){
			a=1;
		}
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	dbUtil.close();
	return a;
}
}

(3、)servlet层:

 

 

package com.login.servlet;

import java.io.IOException;

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

import com.login.dao.UserDao;
@WebServlet(name="RegisterServlet",urlPatterns="/register")
public class RegisterServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	System.out.println("rigtser post");
	req.setCharacterEncoding("utf-8");
	resp.setContentType("text/html;charset=utf-8");
	String name=req.getParameter("username");
	String pwd=req.getParameter("pwd");
	UserDao dao=new UserDao();
	int a=dao.userByName(name);
	if(a>0){
		int b=dao.register(name,pwd);
		if(b>0){
			resp.sendRedirect("login.html");
		}else{
			resp.getWriter().write("<h1>服务器繁忙</h1>");
		}
	}else{
		resp.getWriter().write("<h1>该用户名已存在</h1>");
	}
}
}

 

 

package com.login.servlet;

import java.io.IOException;

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

import com.login.dao.UserDao;

@WebServlet(name = "LoginServlet", urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("post");
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		//resp.setContentType("application/json;charset=utf-8");
		String username = req.getParameter("username");
		String pwd = req.getParameter("pwd");
		// System.out.println(username+pwd);
		UserDao dao = new UserDao();
		int a = dao.login(username, pwd);
		if (a > 0) {
			String str = "\"code\":" + "\"" + "登录成功" + "\"";
			System.out.println(str);
			resp.getWriter().write("登录成功");

		} else {
			String str = "\"code\":" + "\"" + "登录失败" + "\"";
			System.out.println(str);
			resp.getWriter().write("登录失败");
		}
	}
}

 

例二、时钟:

 

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="assets/js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function(){
	function getTime(){
		$.get("time",function(data){
			$("div").html(data);
		});
	}
	setInterval(getTime,1000);
});
</script>
</head>
<body>
<div></div>
</body>
</html>

 

package ajaxtest;

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

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name="MyTime",urlPatterns="/time")
public class MyTime extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	req.setCharacterEncoding("utf-8");
	resp.setContentType("text/html;charset=utf-8");
	//resp.setIntHeader("Refresh", 1);//请求后每一秒钟响应一次
	Date date=new Date();
	SimpleDateFormat f=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
	String str=f.format(date);
	System.out.println(str);
	resp.getWriter().write(str);
}
@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
}


本人一开始没有用setInterval定时,而是在后台用

resp.setIntHeader("Refresh", 1);

 

定时,后来发现只有在浏览器中http://localhost:8080/ajaxtest/time请求这个servlet时间才会变,而直接访问这个网页http://localhost:8080/ajaxtest/time.html时间并没有变,原因是因为time.html里面这个ajax请求只运行一次(代码从上往下解析,解析到这里运行),虽然发送了请求后response多次响应,但是前台并没有再去接收了(ajax请求解析过了,不会再解析一次),所以我最后用的是setInterval来定时,每一秒钟请求一次。

 

例三、计算器:

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="assets/js/jquery-3.2.1.min.js" ></script>
<script>
	$(function(){
		var a;
		$("form").submit(function(){
			
			var dt=$("form").serialize();
			$.get("cal",dt,function(data){
				
				$(".num3").val(data);
				//$("div").html(data);
			});
			return false;
		})
		
	})
</script>
</head>
<body>
	<form method="post">
<input type="text" name="num1" />+
<input type="text" name="num2" />
<input type="submit" value="="/>
<input type="text" name="num3" class="num3" id="num3"/>

</form>
<div></div>
</body>
</html>

 

package calculator;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name="Cal",urlPatterns="/cal")
public class Cal extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	req.setCharacterEncoding("utf-8");
	resp.setContentType("text/html;charset=utf-8");
	
	String num1=req.getParameter("num1");
	String num2=req.getParameter("num2");
	int num11=Integer.parseInt(num1.trim());
	int num21=Integer.parseInt(num2.trim());
	Integer a=num11+num21;
	System.out.println(a);
	resp.getWriter().write(a.toString());//只能返回text/html类型的文本
}
@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
}

 

完整的计算器:

 

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="assets/js/jquery-3.2.1.min.js" ></script>
<script>
	$(function(){
		var option="i";
	    $("select").change(function(){
	    	option=$(this).val();
	    	if(option=="+"){
	    		option="i";
	    	}
	    	//alert(option);
	    });
		$("form").submit(function(){
			var dt=$("form").serialize();
			dt+="&option="+option;
			console.info(dt);
			$.get("cal",dt,function(data){
				
				$(".num3").val(data);
				//$("div").html(data);
			});
			return false;
		})
		
	})
</script>
</head>
<body>
	<form method="post">
<input type="text" name="num1" />
<select>
  <option value="+">+
  <option value="-">-
  <option value="*">*
  <option value="/">/
</select>
<input type="text" name="num2" />
<input type="submit" value="="/>
<input type="text" name="num3" class="num3" id="num3"/>

</form>
<div></div>
</body>
</html>

 

package calculator;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name="Cal",urlPatterns="/cal")
public class Cal extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	req.setCharacterEncoding("utf-8");
	resp.setContentType("text/html;charset=utf-8");
	Integer a = null;
	String num1=req.getParameter("num1");
	String num2=req.getParameter("num2");
	String option=req.getParameter("option");
	int num11=Integer.parseInt(num1.trim());
	int num21=Integer.parseInt(num2.trim());
	if(option.equals("i")){
		 a=num11+num21;
	}
	if(option.equals("-")){
		 a=num11-num21;
	}
	if(option.equals("*")){
		 a=num11*num21;
	}
	if(option.equals("/")){
		 a=num11/num21;
	}
	System.out.println(option);
	resp.getWriter().write(a==null? "null":a.toString());//只能返回text/html类型的文本
}
@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
}


这里我也不清楚为什么不可以直接传一个加号过去,传加号req获取到的为空,只好以一个i代替加号。效果如下:

 

 

三、重定向和请求转发:

1、重定向:

resp.sendRedirect(arg);让浏览器再发送一次请求,所以总共发送了两次请求,后面一次是浏览器自己发送的。产生两个request对象,之前请求的参数Parameter不存在了,且地址栏地址发送改变;

2、请求转发:

 

req.getRequestDispatcher(arg).forward(req, resp);

arg为另一个url。请求总共只发送了一次,之前的请求参数还在,且地址栏地址没有改变,相当于把请求转给另一个servlet。
 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

w_t_y_y

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值