文章目录
- 一,Request对象
- --1,概述
- --2,测试
- 二,练习Request解析请求参数
- --0,项目结构
- --1,创建HTML网页
- --2,创建Servlet程序
- 三,改造Servlet程序实现入库
- --1,导入jar包
- --2,修改Servlet程序
- --3,测试
- 四,请求转发
- --1,概述
- --2,测试
- 五,Response对象
- --1,概述
- --2,测试
一,Request对象
–1,概述
1,用来接受请求,并且能够解析 请求参数.
GET方式: http://localhost:8080/user/userServlet?id=10&name=jack
POST方式: 数据不会在地址栏拼接的
2,常用的有两种:
ServletRequest 父接口
HttpServletRequest 子接口
–2,测试
package cn.tedu.cgb2110boot03.request;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 java.io.IOException;
import java.util.Arrays;@WebServlet
public class RequestServlet01 extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request, response);//和doGet干一样的活}//http://localhost:8080/RequestServlet01?name=jack&pwd=123protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("恭喜您,请求成功~~");
// Servlet解析请求参数HttpServletRequest//1.getParameter()--根据参数名获取参数值String s = request.getParameter("name");String p = request.getParameter("pwd");System.out.println(s+p);//2.getParameterValues()--根据参数名获取参数值,可以获取多个值,存入数组String[] datas = request.getParameterValues("like");System.out.println( Arrays.toString(datas) );//[足球, 篮球]//3.HttpServletRequest的其他APISystem.out.println( request.getCharacterEncoding() );//获取请求使用的字符集UTF-8System.out.println( request.getMethod() );//获取请求方式GETSystem.out.println( request.getContextPath() );//获取项目名称(被缺省)System.out.println( request.getRequestURI() );//要访问的资源路径/RequestServlet01System.out.println( request.getRequestURL() );//包含着http://localhost:8080/RequestServlet01System.out.println( request.getRemotePort() );//发起请求时的端口号System.out.println( request.getQueryString() );//获取请求时携带的参数}
}
二,练习Request解析请求参数
–0,项目结构
–1,创建HTML网页
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>测试 Servlet解析请求参数</title></head><body><h1>1.以get方式提交的数据</h1><form action="http://localhost:8080/user/addServlet">部门编号:<input type="number" name="deptno" placeholder="在这里输入部门编号.."/> <br />部门名称:<input type="text" name="deptname" placeholder="在这里输入部门名称.."/> <br />部门地址:<input type="text" name="deptloc" placeholder="在这里输入部门地址.."/> <br /><button type="submit">提交</button><button type="reset">取消</button></form><h1>2.以post方式提交的数据</h1><form method="post" action="http://localhost:8080/user/addServlet">账号:<input type="text" name="user" placeholder="在这里输入用户名.."/> <br />密码:<input type="password" name="pwd" placeholder="在这里输入密码.."/> <br />年龄:<input type="number" name="age" placeholder="在这里输入年龄.."/> <br /><button type="submit">提交</button><button type="reset">取消</button></form></body>
</html>
–2,创建Servlet程序
package cn.tedu.cgb2110boot03.request;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 java.io.IOException;
@WebServlet("/user/addServlet")
public class RequestServlet02 extends HttpServlet {//处理那些post请求protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("恭喜您,成功的提交了用户的数据!");//TODO 解析请求参数//TODO jdbc入库}//处理那些get请求protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("恭喜您,成功的提交了部门的数据!");//TODO 解析请求参数//TODO jdbc入库}
}
三,改造Servlet程序实现入库
–1,导入jar包
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>cn.tedu</groupId><artifactId>cgb2110boot03</artifactId><version>0.0.1-SNAPSHOT</version><name>cgb2110boot03</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><spring-boot.version>2.3.7.RELEASE</spring-boot.version></properties><dependencies><!-- 。。。。。。。。。添加 jdbc的jar包,需要指定坐标 。。。。。。。。。--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.48</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope><exclusions><exclusion><groupId>org.junit.vintage</groupId><artifactId>junit-vintage-engine</artifactId></exclusion></exclusions></dependency></dependencies><dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>${spring-boot.version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.8.1</version><configuration><source>1.8</source><target>1.8</target><encoding>UTF-8</encoding></configuration></plugin><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>2.3.7.RELEASE</version><configuration><mainClass>cn.tedu.cgb2110boot03.Cgb2110boot03Application</mainClass></configuration><executions><execution><id>repackage</id><goals><goal>repackage</goal></goals></execution></executions></plugin></plugins></build></project>
–2,修改Servlet程序
package cn.tedu.cgb2110boot03.request;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 java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;@WebServlet("/user/addServlet")
public class RequestServlet02 extends HttpServlet {//处理那些post请求protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("恭喜您,成功的提交了用户的数据!");//TODO 解析请求参数String user = request.getParameter("user");String pwd = request.getParameter("pwd");String age = request.getParameter("age");System.out.println(user+pwd+age);//TODO jdbc入库try {//1,导入jar包(在pom.xml里添加jar包的坐标依赖)//注册驱动Class.forName("com.mysql.jdbc.Driver");//获取连接String url="jdbc:mysql:///cgb211001?characterEncoding=utf8";Connection c = DriverManager.getConnection(url, "root", "root");//获取传输器String sql = "insert into user values(null,?,?,?)" ;//sql骨架PreparedStatement ps = c.prepareStatement(sql);ps.setObject(1,user);ps.setObject(2,pwd);ps.setObject(3,age);//执行SQLps.executeUpdate();//执行增删改的SQL//释放资源ps.close();c.close();System.out.println("恭喜您,用户信息已经入库成功!");} catch (Exception e) {e.printStackTrace();}}//处理那些get请求protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("恭喜您,成功的提交了部门的数据!");//TODO 解析请求参数(部门编号,名称,地址)String deptno = request.getParameter("deptno");String deptname = request.getParameter("deptname");String deptloc = request.getParameter("deptloc");//TODO jdbc入库try {//1,导入jar包(在pom.xml里添加jar包的坐标依赖)//注册驱动Class.forName("com.mysql.jdbc.Driver");//获取连接String url="jdbc:mysql:///cgb211001?characterEncoding=utf8";Connection c = DriverManager.getConnection(url, "root", "root");//获取传输器String sql = "insert into dept values(?,?,?)" ;//sql骨架PreparedStatement ps = c.prepareStatement(sql);ps.setObject(1,deptno);ps.setObject(2,deptname);ps.setObject(3,deptloc);//执行SQLps.executeUpdate();//释放资源ps.close();c.close();System.out.println("恭喜您,部门信息已经入库成功!");} catch (Exception e) {e.printStackTrace();}}
}
–3,测试
四,请求转发
–1,概述
是服务器内部的过程,客户端感受不到.
过程: 浏览器 -> A----B
特点: 一次请求一次响应. 地址栏不会改变. 全程使用同一个Request对象.
实现: request.getRequestDispatcher(“B的访问规则”).forward(request,response);
–2,测试
ServletA
package cn.tedu.cgb2110boot03.request;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 java.io.IOException;@WebServlet("/testa")
public class ServletA extends HttpServlet {protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("ServletA...doGet()被触发!");//请求转发: 实现 访问A时,A背后调用B 的效果//特点: 地址栏不变 + 同一个request对象(在A里存,在B里取)request.setAttribute("name","jack");//参数是 目标资源的访问规则.目标资源必须是在同一个项目里才能请求转发request.getRequestDispatcher("/testb").forward(request,response);}
}
ServletB
package cn.tedu.cgb2110boot03.request;
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 java.io.IOException;
@WebServlet("/testb")
public class ServletB extends HttpServlet {protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("ServletB...doGet()被触发!");//获取A中存好的数据Object o = request.getAttribute("name");System.out.println(o);//jack}
}
五,Response对象
–1,概述
专门用来给浏览器做出响应.
本质上就是获取一个输出流,利用输出流写出数据
常用对象:
ServletResponse – 父接口
HttpServletResponse – 子接口
常用方法:
1, getWriter() – 获取字符流(只能写出字符数据)
2, getOutputStream() – 获取字节流(写出任意格式的数据)
3, setContentType() – 写出数据中,如果包含中文,解决中文乱码
4, sendRedirect() – 完成重定向
–2,测试
package cn.tedu.cgb2110boot03.response;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 java.io.IOException;
import java.io.PrintWriter;//Servlet充当服务器:接受请求Request + 做出响应Response
// http://localhost:8080/resp/servlet01?id=10&name=张三
@WebServlet("/resp/servlet01")
public class ResponseServlet01 extends HttpServlet {//如果是get请求,Servlet会自动调用doGet()protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//TODO 解析请求参数String id = request.getParameter("id");String name = request.getParameter("name");//响应时使用的默认的字符集iso-8859-1,为了防止响应时的中文乱码问题,加以下代码response.setContentType("text/html;charset=utf8");//响应解析到的数据PrintWriter out = response.getWriter();out.println(id);//提供了一个换行写出的功能out.write(name);}
}