先创建一个SpringBoot项目

创建过程:File--newProject-Spring Initializr

SpringBoot创建好以后 需要添加注解

@SpringBootApplication
@ServletComponentScan  //需要添加这个注解
public class Cgb2110boot03Application{}

选中request包或者response包,创建一个个Servlet。

Servlet创建后不写括号地址,则以类名访问,写地址,则以地址访问。

@WebServlet
public class RequestServlet01 extends HttpServlet
访问:http://localhost:8080/RequestServlet01
@WebServlet("/resp/servlet01")
public class ResponseServlet01 extends HttpServlet 
访问:http://localhost:8080/resp/servlet01

Request:请求,前端输入的数据连接到java写到SQL里面

Response:响应,前端写入的数据,通过JAVA解析,显示在WEB前端

网页进行响应:http://localhost:8080/resp/servlet01?id=10&name=张三
<dependencies>
    <!--给项目添加jdbc的jar包,需要指定坐标,右键generate—dependency-输入mysql-connector-java确认,点右上m下载,中间的mysql字不飘红代表已经下载好-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.25</version>
    </dependency>

请求转发:

resquest 请求A转发给B,然后返回数据,过程都在后端操作。用户感觉不到转发过程

Servlet A请求里面的内容:
System.out.println("ServletA...doGet()被触发");
//请求转发:实现 访问A时,A背后调用B的效果
//参数是 目标资源的访问规则,目标资源必须是在同一个项目里
//特点:地址栏不变  +同一个request对象(在A里存,在B里取)
request.setAttribute("name","jack");
request.getRequestDispatcher("/testb").forward(request,response); //请求转发语句

Servlet B请求里面的内容:
System.out.println("ServletB...doGet()被触发");
//获取A中存好的数据
Object o=request.getAttribute("name");
System.out.println(o);

五,Response对象
–1,概述
专门用来给浏览器做出响应.
本质上就是获取一个输出流,利用输出流写出数据
常用对象:
ServletResponse – 父接口
HttpServletResponse – 子接口
常用方法:
1, getWriter() – 获取字符流(只能写出字符数据)
2, getOutputStream() – 获取字节流(写出任意格式的数据)
3, setContentType() – 写出数据中,如果包含中文,解决中文乱码
4, sendRedirect() – 完成重定向
 

获取请求:

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);
    }
    //http://localhost:8080/RequestServlet01?name=jack&pwd=123
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("恭喜您,请求成功~~~");
    //Servlet解析请求参数
        String s=request.getParameter("name");
        System.out.println(s);
        String p=request.getParameter("pwd");
        System.out.println(p);
        String[] l=request.getParameterValues("like");
        System.out.println(Arrays.toString(l));
        //其他API
        String s2=request.getCharacterEncoding(); //获取请求使用的字符集 UTF-8
        String method=request.getMethod();//获取请求方式GET
        String path=request.getContextPath();//获取项目名称(被缺省)
        String uri=request.getRequestURI();//要访问的资源路径/RequestServlet
        StringBuffer url=request.getRequestURL();//包含着http://localhost:8080/R
        int remotePort=request.getRemotePort();//发起请求时的端口号
        String string=request.getQueryString(); //获取请求时携带的参数
        System.out.println(s2);
        System.out.println(method);
        System.out.println(path);
        System.out.println(uri);
        System.out.println(url);
        System.out.println(remotePort);
        System.out.println(string);
    }
}

前端提交数据用JDBC存入到SQL

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;

@WebServlet("/user/addServlet")
public class RequestServlet02 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("恭喜你通过doPost提交数据....");
        doGet(request,response);
        String user=request.getParameter("user");
        String pwd=request.getParameter("pwd");
        String age=request.getParameter("age");
        System.out.println(request.getParameter("user"));
        System.out.println(request.getParameter("pwd"));
        System.out.println(request.getParameter("age"));

        try {
            //导入jar包(在pom.xml里添加jar包的坐标依赖)
            Class.forName("com.mysql.cj.jdbc.Driver");//第一步:注册驱动
            String url="jdbc:mysql:///cgb2110?characterEncoding=utf8";//第二步:获取连接
            Connection c= DriverManager.getConnection(url,"root","password");
            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);
            ps.executeUpdate();//执行增删改查的SQL
            //释放资源
            ps.close();
            c.close();
            System.out.println("恭喜您,用户信息已经入库成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("恭喜你通过doGet提交数据.....");
        String deptno=request.getParameter("deptno");
        String deptname=request.getParameter("deptname");
        String deptloc=request.getParameter("deptloc");
        System.out.println(request.getParameter("deptno"));
        System.out.println(request.getParameter("deptname"));
        System.out.println(request.getParameter("deptloc"));
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url="jdbc:mysql:///cgb2110?characterEncoding=utf8";//localhost:3306省略
            Connection c=DriverManager.getConnection(url,"root","password");
            String sql="insert into dept values(?,?,?)";
            PreparedStatement num=c.prepareStatement(sql);
            num.setObject(1,deptno);
            num.setObject(2,deptname);
            num.setObject(3,deptloc);
            num.executeUpdate();
            num.close();
            c.close();
            System.out.println("恭喜你,用户信息已经入库成功~~~");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Response:

package cn.tedu.cgb2110boot03.response;

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;
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 {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println(request.getParameter("id"));
        System.out.println(request.getParameter("name"));
        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.println(name);
        //2.获取字节流--写出数据
        ServletOutputStream out=response.getOutputStream();
        //字节流只能写出字节int.byte[],如果想要写出字符串,必须要把字符串变成byte[]---getBytes()
        out.write(id.getBytes());
        out.write(name.getBytes());
    }
}

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐