servlet课堂代码笔记

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;
    
    /**
     * Servlet implementation class Test1Servlet
     * @WebServlet servlet3.0--url mapping class--映射
     * 协议://hostname:port/访问的工程名/(url mapping)
     *  http://127.0.0.1:8080/demo211229/Test1Servlet <!-- 映射路径 -->
     */
    //@WebServlet servlet3.0--url mapping class--映射
    //协议://hostname:port/访问的工程名/(url mapping)
    //http://127.0.0.1:8080/demo211229/Test1Servlet <!-- 路径 -->
    //所有的servlet-url mapping不能重复
    //@WebServlet和servlet-web.xml同时使用也不可以重名
    
    //1-servlet文件--extends HttpServlet
    //2-servlet配置--注解@WebServlet或web.xml
    //3-servlet使用--生命周期(init(初始化)/service/destroy(销毁))
    
    //@WebServlet("/Test1Servlet")
    public class Test1Servlet extends HttpServlet {//继承了HttpServlet
    	private static final long serialVersionUID = 1L;//序列号
           
        /**
         * @see HttpServlet#HttpServlet()
         */
        public Test1Servlet() {//构造方法,不用可以不写
            super();
            // TODO Auto-generated constructor stub
        }
        @Override
        	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        		// TODO Auto-generated method stub
        		super.service(req, resp);	
        	}
    	/**       
    	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    	 */
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
    			throws ServletException, IOException { //request请求。response回复/响应
    		// TODO Auto-generated method stub
    //		response.getWriter().append("Served at: ").append(request.getContextPath());//写出流.拼接"Served at: "。拼接 访问的工程名
            PrintWriter wr=response.getWriter();//字符流
    //        ServletOutputStream os=response.getOutputStream();//字节流
            wr.append("asdasd");
    //        wr.write("c");
    //        wr.print("a");
    //        wr.println("a");
            wr.flush();//强制清除缓冲区
            wr.close();//关闭流
            wr=null;//置空
    	}
    	/**
    	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    	 */
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
    			throws ServletException, IOException {
    		// TODO Auto-generated method stub
    //		System.out.println("==========");
    		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;
    
    /**
     * Servlet implementation class Test2Servlet
     */
    @WebServlet("/Test2Servlet")
    public class Test2Servlet extends HttpServlet {
    	//MVC=model(模型层) view(视图层) controller(控制层)
    	//控制层-servlet
    	//1-接收请求
    	//2-获得参数(封装)
    	//3-调用方法
    	//4-返回结果/页面跳转。二者不能同时存在
    	private static final long serialVersionUID = 1L;
           
        /**
         * @see HttpServlet#HttpServlet()
         */
        public Test2Servlet() {
            super();
            // TODO Auto-generated constructor stub
        }
    
    	/**
    	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    	 */
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		// TODO Auto-generated method stub
    		response.getWriter().append("Served at: ").append(request.getContextPath());
    	}
    
    	/**
    	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    	 */
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		// TODO Auto-generated method stub
    //		doGet(request, response);
    		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.setCharacterEncoding("UTF-8");//显示中文
    //		 response.setContentType("text/html; charset=UTF-8");//回复的是html时加
    //		 PrintWriter wr = response.getWriter();
    //		 String html="<html><head></head><body>账号"+code+"<br>密码"+pass+"</body>";
    //		 wr.append(html);
    //		 wr.flush();
    //		 wr.close();
    //		 wr=null;
    		 //页面跳转
    		 //1-请求转发
    		 //请求转发的路径=要跳转的路径中,从/开始,不带有工程名的路径
    		 //路径就是网络资源,js,css,png,网页文件,servlet文件...
    //		 request.getRequestDispatcher("/test/tes211230/testb.jsp").forward(request, response);
    		 //request.getRequestDispatcher("/Test1Servlet").forward(request, response);
    		 //web->servlet2->servlet1->...->web
    		 //2-请求重定向
    		//请求重定向的路径=要跳转的路径中,从/开始,带有工程名的路径
    		 response.sendRedirect("/demo211229/test/tes211230/testb.jsp");
    		 //response.sendRedirect("/demo211229/Test1Servlet");
    		 //请求=web->java
    		 //回复=java->web
    		 //请求回路=web->java->web=一次请求
    		 //区别
    		 //1-转发是在服务器端完成的,重定向是在客户端发生的
    		 //2-转发的速度快一些,重定向速度慢
    		 //3-转发是同一个请求(web-servlet-web),重定向是两次不同的请求(web-servlet-web)(web-web)
    		 //4-转发的地址栏没有变化,重定向地址栏有变化
    		 //5-转发必须是在同一个服务器下完成,重定向可以在不同的服务器下完成
    		 
    	}
    
    }

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;
    
    /**
     * Servlet implementation class Test3Servlet
     */
    //http://127.0.0.1:8080/demo211229/Test3Servlet
    //@WebServlet(urlPatterns = {"/Test3Servlet"},loadOnStartup = 0,initParams = {
    //		@WebInitParam(name = "username",value = "lisi"),
    //		@WebInitParam(name = "password",value = "asdasd")})
    public class Test3Servlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
           
    	//servlet生命周期=可以被定义为从创建到销毁的整个过程
    	//1-init用于初始化
    	//2-servlet方法用来处理请求的--间接调用doget/dopost
    	//3-destroy方法用于结束销毁
    	//最后servlet由JVM垃圾回收器进行垃圾回收
    	
        /**
         * @see HttpServlet#HttpServlet()
         */
        public Test3Servlet() {//构造方法
    //        super();
        	System.out.println("Test3Servlet--构造方法");
        }
    
        //init方法只会调用执行一次,是在第一次访问(或创建)时
        //之后每次请求都不会再调用执行init,用于servlet的初始化
        //线程:
        //当请求访问一个servlet时,会创建并得到同一个servlet实例(单例)
        //每次请求都会产生一个新的线程----线程并发问题
        
        @Override
        public void init(ServletConfig config) throws ServletException {//初始化
    //    	super.init(config);
        	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);
        }
        
        //只会调用执行一次,表示servlet生命周期结束,调用后,该servlet对象被标记为垃圾,被回收
        @Override
        public void destroy() {
        	super.destroy();
        }
        
    	/**
    	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    	 */
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		// TODO Auto-generated method stub
    		response.getWriter().append("Served at: ").append(request.getContextPath());
    	}
    
    	/**
    	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    	 */
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		// TODO Auto-generated method stub
    		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;
    //awt swing java可视化界面的工具
    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());//用Session可以在多变量的情况下使用
    		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();
    // 	$("form").serialize();//a=b&c=d
    	$.ajax({//   异步请求,局部刷新
    		url:"/demo211229/AjaxServlet",//请求路径,跟action一样
    // 		访问网页端:/工程名+webcontent目录下的结构
    // 		访问java端:工程名+servlet上的urlmapping
    		type:"post",//请求方式,跟method一样
    // 		data:"a=b&c=d",//请求参数,url?a=b&c=d
    // 		data:"$("form").serialize()"
    // 		data:"code="+code1+"&pass="+pass1+"&authcode="+authcode1+",
    		data:{code:code1,pass:pass1,authcode:authcode1,action:"aaa"},
    		dataType:"json",//请求返回的数据类型,text/json/xml
    		success:function(data){//请求成功返回时的回调方法--核心
    			console.log(data)//请求成功返回回来的数据
    			console.log(typeof data)
    // 			var json = JSON.parse(data);//将json格式的字符串转换成json格式的对象
    // 			var str = JSON.stringify(json);//json格式的对象转换成json格式的字符串
    // 			$.each(data,function(){	
    	
    // 			})
    			$("#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);
    //		ajax请求中必须用返回结果的回复,不能用页面跳转的回复
    		PrintWriter wr = resp.getWriter();
    		wr.write(getjson());//标准json格式的字符串返回给网页
    		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) {
    		//把其他形式转换为json格式
    		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集合对应的key、value转换为json格式
    		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);
    		
    		//把实体类转换成json格式
    		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);
    		
    		//将集合转换为json格式
    		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);//将对象p3,p4构成集合list
    		JSONArray json3 = new JSONArray(list);
    		System.out.println(json3.toString());//得到的是json格式对象构成的数组
    	}
    	
    	//json=javascript object notation
    	//number
    	//string
    	//boolean
    	//array
    	//object
    	//null
    	
    	//1-json中不区分整数、小数等数字类型,统一使用number
    	//2-array数据,以[]形式定义,元素间用逗号分隔,元素可以是任意类型
    	//[1,2,3,4,5,6]
    	//3-object对象,用{}形式定义,元素以键值形式书写,key必须是字符串类型,
    	//value可以是任意类型,key和value之间用:分隔映射,元素之间用逗号分隔
    	//{"a":"b","c":"1"}
    }

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;
    	}
    
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个简单的示例代码,演示如何在两个Servlet之间进行通信: Servlet1.java: ```java import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Servlet1 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取请求参数 String message = request.getParameter("message"); // 创建一个跳转链接 String url = "Servlet2?message=" + message; // 重定向到Servlet2 response.sendRedirect(url); } } ``` Servlet2.java: ```java import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Servlet2 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取请求参数 String message = request.getParameter("message"); // 在控制台输出消息 System.out.println("接收到的消息:" + message); } } ``` 在上述示例中,Servlet1接收到一个名为"message"的请求参数,并将其作为查询字符串传递给Servlet2。然后,Servlet2接收到这个参数并在控制台输出。 请注意,这只是一个简单的示例,实际应用中可能会有更多的逻辑和错误处理。此外,还可以使用其他方法进行Servlet之间的通信,例如使用请求转发而不是重定向。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值