web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
id="WebApp_ID" version="4.0">
<!-- xml=可扩展的标记语言 -->
<!-- ns=namespace命名空间 -->
<!-- xsd=xml schema definition文档结构描述 -->
<!-- <servlet> -->
<!-- <servlet-name>Test1Servlet</servlet-name> -->
<!-- <servlet-class>test211230.Test1Servlet</servlet-class> -->
<!-- </servlet> -->
<!-- <servlet-mapping> -->
<!-- <servlet-name>Test1Servlet</servlet-name> -->
<!-- <url-pattern>/Test1Servlet</url-pattern> -->
<!-- </servlet-mapping> -->
<!-- load-on-startup标签作用:tomcat启动时执行该servlet的初始化 -->
<!-- 当值为负整数或未指定值时,该servlet是在第一次被调用时加载并初始化 -->
<!-- 当值为0或正整数是,tomcat启动时会加载并初始化,值越小优先级越高 -->
<!-- 一般会设置上,空间换时间,避免用户在使用是加载等待 -->
<servlet>
<servlet-name>Test3Servlet</servlet-name>
<servlet-class>test211230.Test3Servlet</servlet-class>
<init-param>
<param-name>username</param-name>
<param-value>zhangsan</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>123456</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Test3Servlet</servlet-name>
<url-pattern>/Test3Servlet</url-pattern>
</servlet-mapping>
<display-name>demo211229</display-name>
<welcome-file-list>
<!-- 欢迎页 -->
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
Test1Servlet.java
package test211230;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Test1Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public Test1Servlet() {
super();
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.service(req, resp);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter wr=response.getWriter();
wr.append("asdasd");
wr.flush();
wr.close();
wr=null;
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
testa,jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- http://127.0.0.1:8080/demo211229/Test1Servlet -->
<!-- http://127.0.0.1:8080/demo211229/test/tes211230/testa.jsp 访问网页中的内容文件规则 -->
<!-- 协议://hostname:port/访问的工程名/(WebContent之下的目录结构) -->
<!-- 1-请求路径action="/demo211229/Test1Servlet" -->
<!-- 2-请求方式method="post" -->
<!-- 3-请求参数(参数名+参数值) -->
<form action="/demo211229/Test2Servlet" method="post">
账号<input type="text" name="code"><br>
密码<input type="password" name="pass"><br>
<input type="radio" name="sex" value="1">男
<input type="radio" name="sex" value="2">女<br>
<input type="checkbox" name="hobby" value="a">跑步
<input type="checkbox" name="hobby" value="b">游泳
<input type="checkbox" name="hobby" value="c">羽毛球<br>
<select name="addr">
<option value="bejing">北京</option>
<option value="shanghai">上海</option>
<option value="guangzhou">广州</option>
</select><br>
<input type="hidden" name="action" value="hide">
<input type="submit">
<input type="reset">
</form>
<!-- http://127.0.0.1:8080/demo211229/img/curry1.png -->
<img alt="" src="/demo211229/img/curry1.png">
<!-- http://127.0.0.1:8080/demo211229/test/js/jquery-3.6.0.min.js -->
<script src="/demo211229/test/js/jquery-3.6.0.min.js"></script>
<a href="http://www.baidu.com">AAA</a>
<!-- http://127.0.0.1:8080/demo211229/Test1Servlet -->
<a href="/demo211229/Test1Servlet">BBB</a>
<a href="/demo211229/test/tes211230/testa.jsp">CCC</a>
<!-- 请求方式get/post ----post一般在表单中遇到,其他大概率是get请求-->
<!-- 网络资源:以路径的形式写的东西都是,包括 js css png 网页 servlet -->
</body>
</html>
Test2Servlet,java
package test211230;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Map;
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("/Test2Servlet")
public class Test2Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public Test2Servlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String code = request.getParameter("code");
String pass = request.getParameter("pass");
System.out.println(code+"\t"+pass);
String sex = request.getParameter("sex");
System.out.println(sex);
String[] hobby = request.getParameterValues("hobby");
System.out.println(Arrays.toString(hobby));
Map<String, String[]> map = request.getParameterMap();
System.out.println(map);
response.sendRedirect("/demo211229/test/tes211230/testb.jsp");
}
}
Test3Servlet.java
package test211230;
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Test3Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public Test3Servlet() {
System.out.println("Test3Servlet--构造方法");
}
@Override
public void init(ServletConfig config) throws ServletException {
System.out.println("Test3Servlet-init");
String username = config.getInitParameter("username");
System.out.println("username="+username);
Enumeration<String> names = config.getInitParameterNames();
while(names.hasMoreElements()) {
String name = names.nextElement();
String value = config.getInitParameter(name);
System.out.println(name +" "+ value);
}
String servletName = config.getServletName();
System.out.println("servletName="+servletName);
}
@Override
public void destroy() {
super.destroy();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
authcode.jsp–验证码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
http://127.0.0.1:8080/demo211229/test/test211231/authcode.jsp
<form action="/demo211229/SubmitServlet" method="post">
<!-- 有密文method用dopost方法,更安全 -->
<table>
<tr>
<td>账号</td>
<td><input type="text" name="code"></td>
</tr>
<tr>
<td>密码</td>
<td><input type="password" name="pass"></td>
</tr>
</tr>
<tr>
<td><img src="/demo211229/AuthCodeServlet"
onclick="this.src='/demo211229/AuthCodeServlet?'+Math.random()"></td>
<!-- ?'+Math.random()-----?不能丢,后面跟的就是参数。/一直重复访问同一个路径会被网页拦截,加随机数使访问的路径不同 -->
<td><input type="text" name="authcode"></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" >
<input type="reset">
</td>
</tr>
</table>
</form>
</body>
</html>
```
# AuthCodeServlet,java
```java
package test122131;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
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("/AuthCodeServlet")
public class AuthCodeServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
private static char[] chs="1234567890abcdefghijklmnopqrstuiwxyz".toCharArray();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("获得验证码图片");
BufferedImage image=new BufferedImage(75,25,BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.setColor(new Color(200,200,255));
g.fillRect(0, 0, 75, 75);
g.setFont(new Font("隶书", Font.BOLD, 15));
StringBuffer str = new StringBuffer();
Random r = new Random();
for(int i=0;i<4;i++) {
int index=r.nextInt(36);
g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
g.drawString(chs[index]+"",15*i+3, 16+(r.nextInt(3)));
str.append(chs[index]);
}
req.getSession().setAttribute("auth_code", str.toString());
ImageIO.write(image, "jpg", resp.getOutputStream());
}
}
SubmitServlet.java
package test122131;
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("/SubmitServlet")
public class SubmitServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String authcode=req.getParameter("authcode");
Object auth_code=req.getSession().getAttribute("auth_code");
if(auth_code.toString().equals(authcode)){
System.out.println("验证成功");
}else {
System.out.println("验证失败");
}
String code = req.getParameter("code");
String pass = req.getParameter("pass");
}
}
testAjax.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ajax</title>
</head>
<body>
<script type="text/javascript" src="/demo211229/test/js/jquery-3.6.0.min.js"></script>
<form action="" method="post">
<!-- 有密文method用dopost方法,更安全 -->
<table>
<tr>
<td>账号</td>
<td><input type="text" name="code"></td>
</tr>
<tr>
<td>密码</td>
<td><input type="password" name="pass"></td>
</tr>
</tr>
<tr>
<td><img src="/demo211229/AuthCodeServlet"
onclick="this.src='/demo211229/AuthCodeServlet?'+Math.random()"></td>
<!-- ?'+Math.random()-----?不能丢,后面跟的就是参数。/一直重复访问同一个路径会被网页拦截,加随机数使访问的路径不同 -->
<td><input type="text" name="authcode"></td>
</tr>
<tr>
<td colspan="2">
<input type="button" value="确定">
<input type="reset">
</td>
</tr>
</table>
</form>
<div id="div_a">AAAAA</div>
<!-- http://127.0.0.1:8080/demo211229/test/test211231/testAjax.jsp -->
<!-- 表单提交submit请求 -->
<!-- ajax请求 =asynchronous(异步) JavaScript and xml-->
<!-- ajax请求=jQuery/js(知道) -->
<!-- 阻止表单提交=将type由submit改为button -->
<script type="text/javascript">
function ajaxButton() {
var code1=$("input[name='code']").val();
var pass1=$("input[name='pass']").val();
var authcode1=$("input[name='authcode']").val();
$.ajax({
url:"/demo211229/AjaxServlet",
type:"post",
data:{code:code1,pass:pass1,authcode:authcode1,action:"aaa"},
dataType:"json",
success:function(data){
console.log(data)
console.log(typeof data)
$("#div_a").html(data)
}
});
console.log(222)
}
$(function() {
$("input[type='button']").click(ajaxButton);
})
</script>
</body>
</html>
AjaxServlet.java
package test122131;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
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 org.json.JSONArray;
import org.json.JSONObject;
@WebServlet("/AjaxServlet")
public class AjaxServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String code = req.getParameter("code");
String pass = req.getParameter("pass");
String authcode = req.getParameter("authcode");
System.out.println(code+"\t"+pass+"\t"+authcode);
PrintWriter wr = resp.getWriter();
wr.write(getjson());
wr.flush();
wr.close();
wr=null;
}
private String getjson() {
PersonModel p2=new PersonModel();
p2.setAge(22);
p2.setCode("1002");
p2.setId(1);
p2.setName("lxf");
JSONObject obj2=new JSONObject(p2);
System.out.println(obj2);
return obj2.toString();
}
}
testa.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- http://127.0.0.1:8080/demo211229/Test1Servlet -->
<!-- http://127.0.0.1:8080/demo211229/test/tes211230/testa.jsp 访问网页中的内容文件规则 -->
<!-- 协议://hostname:port/访问的工程名/(WebContent之下的目录结构) -->
<!-- 1-请求路径action="/demo211229/Test1Servlet" -->
<!-- 2-请求方式method="post" -->
<!-- 3-请求参数(参数名+参数值) -->
<form action="/demo211229/Test2Servlet" method="post">
账号<input type="text" name="code"><br>
密码<input type="password" name="pass"><br>
<input type="radio" name="sex" value="1">男
<input type="radio" name="sex" value="2">女<br>
<input type="checkbox" name="hobby" value="a">跑步
<input type="checkbox" name="hobby" value="b">游泳
<input type="checkbox" name="hobby" value="c">羽毛球<br>
<select name="addr">
<option value="bejing">北京</option>
<option value="shanghai">上海</option>
<option value="guangzhou">广州</option>
</select><br>
<input type="hidden" name="action" value="hide">
<input type="submit">
<input type="reset">
</form>
<!-- http://127.0.0.1:8080/demo211229/img/curry1.png -->
<img alt="" src="/demo211229/img/curry1.png">
<!-- http://127.0.0.1:8080/demo211229/test/js/jquery-3.6.0.min.js -->
<script src="/demo211229/test/js/jquery-3.6.0.min.js"></script>
<a href="http://www.baidu.com">AAA</a>
<!-- http://127.0.0.1:8080/demo211229/Test1Servlet -->
<a href="/demo211229/Test1Servlet">BBB</a>
<a href="/demo211229/test/tes211230/testa.jsp">CCC</a>
<!-- 请求方式get/post ----post一般在表单中遇到,其他大概率是get请求-->
<!-- 网络资源:以路径的形式写的东西都是,包括 js css png 网页 servlet -->
</body>
</html>
TestJson.java
package test122131;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
public class TestJson {
public static void main(String[] args) {
JSONObject obj = new JSONObject();
obj.put("age", 22);
obj.put("name", "zhangsan");
obj.put("isStudent", true);
obj.put("hobby", new String[] { "swimming", "hiking" });
PersonModel p1=new PersonModel();
p1.setAge(20);
p1.setCode("1001");
obj.put("user", p1);
obj.put("key", (Object)null);
System.out.println(obj.toString());
Map<String, Object> map=new HashMap<String, Object>();
map.put("age", 22);
map.put("name", "zhangsan");
map.put("isStudent", true);
map.put("hobby", new String[] { "swimming", "hiking" });
JSONObject obj1 = new JSONObject(map);
System.out.println(obj1);
PersonModel p2=new PersonModel();
p2.setAge(22);
p2.setCode("1002");
p2.setId(1);
p2.setName("lxf");
JSONObject obj2=new JSONObject(p2);
System.out.println(obj2);
PersonModel p3=new PersonModel();
p3.setAge(22);
p3.setCode("1003");
p3.setId(3);
p3.setName("xiaoming");
PersonModel p4=new PersonModel();
p4.setAge(22);
p4.setCode("1004");
p4.setId(4);
p4.setName("xiaohong");
List<PersonModel> list = Arrays.asList(p3,p4);
JSONArray json3 = new JSONArray(list);
System.out.println(json3.toString());
}
}
PersonModel
package test122131;
public class PersonModel {
private int id;
private String code;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}