First Servlet - Java
2017-08-12 本文已影响13人
Java酸不酸
此文只是用了GET方法请求,所有POST方法没有贴出来了,下次使用另外更新。
对应接口是本人的本地服务器,所以别人无法访问,此文主要记录接口的写法以及细节。
字符编码
//设置UTF-8编码
response.setContentType("text/html; charset=UTF-8");
//中文字符转译
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("uth-8");
登录
login1:http://192.168.1.101:8080/myweb/servlet/myservlet?name=rr&password=123
login2:http://192.168.2.100:8080/myweb/servlet/myservlet?name=rr&password=123
//登录接口实现方法
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
//字符转译
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("uth-8");
//获取name参数的值
String name = request.getParameter("name").toString();
//获取password参数的值
String password = request.getParameter("password").toString();
//判断
if (name.equals("rr") && password.equals("123")) {
returnmsg(out, 1, "登录成功!");
} else {
System.out.println(name + password);
returnmsg(out, 2, "登录失败,用户名或密码错误!");
}
}
/**
* 返回参数
* @param out
* @param code
* @param message
* @throws UnsupportedEncodingException
*/
public void returnmsg(PrintWriter out, int code, String message) {
Map<String, Object> msg = new HashMap<String, Object>();
msg.put("code", code);
msg.put("msg", message);
//转为json格式,先要导入gson包
out.print(new Gson().toJson(msg));
}
返回结果:
{
"code":1,
"msg":"登录成功"
}
用户列表
adminList1:http://192.168.1.101:8080/myweb/servlet/adminlist
adminList2:http://192.168.2.100:8080/myweb/servlet/adminlist
public class adminlist extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//UTF-8
response.setContentType("text/html; charset=UTF-8");
//字符转译
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("uth-8");
PrintWriter out = response.getWriter();
out.print(returnAdminlist());
}
/**
* 将生成的数据抽成一个方法,并返回生成的数据
*/
public List<String> returnAdminlist() {
List<String> mapList = new ArrayList<String>();
List<String> address = new ArrayList<String>();
address.add("杭州");
address.add("北京");
address.add("深圳");
address.add("上海");
address.add("耒阳");
for (int i = 0; i < 10; i++) {
Map< String, String> adminlist = new HashMap<String, String>();
adminlist.put("admin", "小荣儿" + (i + 1));
adminlist.put("address", address.get(new Random().nextInt(5)));
adminlist.put("tel", randomNum());
mapList.add(new Gson().toJson(adminlist));
}
return mapList;
}
/**
* 随机生成一个9以内的数字,并拼凑成10位数字
*/
public String randomNum() {
String randString = "";
for (int i = 0; i < 10; i++) {
Random random = new Random();
randString += random.nextInt(9);
}
return "1" + randString;
}
}
返回结果:
[
{
"address":"深圳",
"admin":"小荣儿1",
"tel":"14178070375"
},
{
"address":"北京",
"admin":"小荣儿2",
"tel":"18828271185"
}
.....
]