当前位置:网站首页>Servlet API

Servlet API

2022-06-12 16:22:00 A snail at the end of a pyramid

HttpServlet

Handle GET 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("/hello")
public class helloServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
        // This line of code needs to be commented out , Cannot call a parent class's doget
       // super.doGet(req, resp);

        // This is to let the server print on its own console 
        System.out.println("hello hello");
        // Also print on the page  hello world, hold hello world character string , Put it in http Responsive body in , The browser will put body The contents of are displayed on the page 
        resp.getWriter().write("hello hello");

    }
}

Handle POST request

@WebServlet("/method")
public class MethodServlet extends HttpServlet {
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
        //super.doPost(req, resp);
        resp.setContentType("test/html;charset=utf8");
        resp.getWriter().write("POST Respond to ");
    }
}
<body>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
        $.ajax({
    
            type:'post',
            url:'method',
            success:function(body){
    
                console.log(body);
                

            }

        });
    </script>

</body>

 Insert picture description here

Execution results :
 Insert picture description here

HttpServletRequest

HttpServletRequest It corresponds to a HTTP request ,HTTP What is in the request , There's something here .

The core approach

 Insert picture description here

Print request information

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.Enumeration;

@WebServlet("/showRequest")
public class showRequestServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
        // Call the API, And organize the results into a html in , And in response body

       // hold api Results of execution , Put it in stringBuilder in 
        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append("<h3> First line   part </h3>");
        stringBuilder.append(req.getProtocol());
        stringBuilder.append("<br>");
        stringBuilder.append(req.getMethod());
        stringBuilder.append("<br>");
        stringBuilder.append(req.getRequestURI());
        stringBuilder.append("<br>");
        stringBuilder.append(req.getContextPath());
        stringBuilder.append("<br>");
        stringBuilder.append(req.getQueryString());
        stringBuilder.append("<br>");
        stringBuilder.append("<h3>header  part </h3>");
        Enumeration<String> headerNames=req.getHeaderNames();
        while(headerNames.hasMoreElements()) {
    
            String headerName=headerNames.nextElement();
            String headerValue= req.getHeader(headerName);
            stringBuilder.append(headerName+": "+headerValue+"<br>");
        }
        resp.setContentType("text/html;charset=utf8");
        resp.getWriter().write(stringBuilder.toString());

    }
}

result :
 Insert picture description here

obtain GET Parameters in the 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("/getParameter")
public class getParameterServlet extends HttpServlet {
    
    // Expect a request from the browser to describe this :/getParameter?userId=123&classId=456
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
      String userId=req.getParameter("userId");
      String classId=req.getParameter("classId");
      resp.getWriter().write("userId="+userId+", classId="+classId);
  }


}

 Here is the reference

obtain POST Parameters in the request

POST The parameters in the request are generally passed through body Pass it to the server .
POST request body Format
(1)x-www-form-urlencoded
(2)form-data
(3)json
1. If the request is x-www-form-urlencoded This format , How does the server get parameters ?
How to get parameters and GET equally , It's also getParameter
Pass at the front form Form construction request

 Insert a code chip here 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("/postGetParameter")
public class PostGetParameterServlet extends HttpServlet {
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
        // Suppose the parameters passed from the front end are userId=10&classId=20
        // The server is also through req.getParameter To get the content 
        String userId=req.getParameter("userId");
        String classId=req.getParameter("classId");
        resp.getWriter().write("userId="+userId+",classId="+classId);
    }
}

<body>
    <form action="postGetParameter" method="POST">
        <input type="text" name="userId">
        <input type="text" name="classId">
        <input type="submit" value=" Submit ">
    </form>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
        // $.ajax({
    
        // type:'post',
        // url:'method',
        // success:function(body){
    
        // console.log(body);
                

        // }

        // });
    </script>



</body>

 Insert picture description here

 Here is the reference

2. If the request is json The way , How to deal with ?
This can be done through a third-party library , Deal directly with json Format data .
Mainly used libraries , be called Jackson.
adopt maven hold Jackson This library , Download to local , And into the project .
 Insert picture description here
 Insert picture description here
( One ) In the browser front-end code , adopt JS Construct out body by json Format request

<input type="text" id="userId">
<input type="text" id="classId">
<input type="button" value=" Submit " id="submit">
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
     let userIdinput=document.querySelector("#userId");
        let classIdinput=document.querySelector("#classId");
        let button=document.querySelector("#submit");
        button.onclick=function(){
    
            $.ajax({
    
                type:'post',
                url:'postJson',
                contentType:'application/json',
                data:JSON.stringify({
    
                    userId:userIdinput.value,
                    classId:classIdinput.value

                }),
                success:function(body){
    
                    console.log(body);
                    
                }



            });


        }
    </script>
        

( Two ) stay Java In the back-end code , adopt Jackson To deal with .

import com.fasterxml.jackson.databind.ObjectMapper;

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;
class User {
    
    public int userId;
    public int classId;

}
@WebServlet("/postJson")
public class PostJsonServlet extends HttpServlet {
    
    //1. Create a Jackson Core objects of 
    private ObjectMapper objectMapper=new ObjectMapper();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
        //2. Read body The request , And then use objectMapper To parse into the required object 
        //readValue Is to put json Format string , Turn into Java The object of 
        // The first parameter , Indicates which string to convert , This parameter can be filled in as String, You can also fill in a InputStream object , It can also be filled in File
        // The second parameter , Express   We need to take this. json Format string , To which Java object 
        User user=objectMapper.readValue(req.getInputStream(),User.class);
        resp.getWriter().write("userId:"+user.userId+",classId"+user.classId);




    }
}

result : Here is the reference
 Insert picture description here
After clicking submit , You can see , In the browser console , The response data of the server is printed out . Currently using ajax The way to submit data , This operation will not generate page Jump by default , And use form The styles vary greatly .

HttpServletResponse

HttpServletResponse It corresponds to a HTTP Respond to ,HTTP In the response
what , There's something here .

The core approach

 Insert picture description here

Set status code

200

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("/status")
public class StatusServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
        resp.setStatus(200);
        resp.getWriter().write("hello");
    }
}

adopt fiddler Grab the bag , You can see the result  Here is the reference

404

@WebServlet("/status")
public class StatusServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
        resp.setStatus(404);
        resp.getWriter().write("hello");
    }
}

 Here is the reference

Automatically refresh

to http Set one in the response header.Refresh

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("/autoRefresh")
public class AutoRefresh extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
        resp.setHeader("Refresh","1");
        resp.getWriter().write("timeStamp:"+System.currentTimeMillis());

    }
}

Redirect

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("/redirect")
public class RedirectServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
        // Here we return a 302 Redirect response , Let the browser automatically jump to   Sogou homepage 
        resp.setStatus(302);
        resp.setHeader("Location","https://www.sogou.com/");
    }
}

Simpler usage

@WebServlet("/redirect")
public class RedirectServlet extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
        // Here we return a 302 Redirect response , Let the browser automatically jump to   Sogou homepage 
       resp.sendRedirect("https:www.baidu.com");
    }
}

The server version of the confession wall

The previously implemented confession wall , As soon as the page is refreshed , The content doesn't exist , So you can use the server , To save the data , So that “ Persistence ” Storage .

When implementing this program , You need to first consider how the client and server interact .
That is to say, the front and back end interaction interfaces should be agreed .

For the confession wall , It mainly provides two interfaces .
1. Tell the server , What kind of data is left in the current message
( When the user clicks the submit button , Will send a message to the server HTTP request , Let the server save this message )
2. Get... From the server , What is the current message data .( When the page loads , You need to get the stored message content from the server )

import com.fasterxml.jackson.databind.ObjectMapper;

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.ArrayList;
import java.util.List;

class Message {
    
    public String from;
    public String to;
    public String message;
}
@WebServlet("/message")
public class MessageServlet extends HttpServlet {
    
    private ObjectMapper objectMapper=new ObjectMapper();

    private List<Message> messages=new ArrayList<>();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
        // Processing requests to submit messages 
       Message message= objectMapper.readValue(req.getInputStream(),Message.class);
      // The simplest way to save is to save to memory 
       messages.add(message);
       // adopt ContentType Notification page , The data returned is json Format 
       resp.setContentType("application/json;charset=utf8");
       resp.getWriter().write("{\"ok\":true}");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
        // Get message list , Just return the whole message list to the client 
        // You need to use objectMapper hold Java object , Turn into json Format string 

        String jsonString=objectMapper.writeValueAsString(messages);
        System.out.println("jsonString: " + jsonString);
        resp.setContentType("application/json;charset=utf8");
        resp.getWriter().write(jsonString);
    }


}
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
    //  Join in ajax Code for , The logic to be added here has two parts 
    //  When you click the submit button ,ajax To be able to construct data to send to the server 
    //  When the page is loaded , Get the message list from the server , And display directly on the interface  
        function getMessages(){
    
            $.ajax({
    
                type:'get',
                url:'message',
                success:function(body){
    
                  // Current body Is already a JS Object array ,ajax According to the response content type To automatically parse 
                  // If the server returns content type It's already application/json 了 ,ajax It will body Automatically convert to JS The object of 
                  // If the client does not automatically transfer , It can also be done through JSON.parse() To switch manually 
                    let container=document.querySelector('.container');
                    for(let message of body){
    
                        let div=document.createElement('div');
                        div.innerHTML=message.from+' Yes '+message.to+' say :'+message.message;
                        div.className='row';
                        container.appendChild(div);

                    }

                }

            });
        }
        // Function call 
        getMessages();

    
        // When the user clicks submit, You'll get it input The content in , So as to construct the content into a div, Insert at the end of the page 
        let submitBtn=document.querySelector('#submit');
        submitBtn.onclick=function() {
    
            //1. Get it first 3 individual input The content in 
            let inputs=document.querySelectorAll('input');
            let from=inputs[0].value;
            let to=inputs[1].value;
            let msg=inputs[2].value;
            if(from=='' || to=='' || msg==''){
    
                // The user hasn't finished filling in , Don't submit data for the time being 
                return;
            }
            //2. Generate a new div, The content is input Contents of Li , Put this new div Add to page 
            let div=document.createElement('div');
            div.innerHTML=from+' Yes '+to+' say :'+msg;
            div.className='row';
            let container=document.querySelector('.container');
            container.appendChild(div);
            //3. Clear the contents of the previous input box 
            for(let i=0;i<inputs.length;i++){
    
                inputs[i].value='';
            }
            //4.  Put the contents of the currently obtained input box , Construct into a HTTP POST request , adopt ajax To the server 
            let body={
    
                from:from,
                to:to,
                message:msg
            };
            $.ajax({
    
                type:"post",
                url:"message",
                contentType:"application/json;charset=utf8",
                data:JSON.stringify(body),
                success:function(body){
    
                    alert(" Message submitted successfully ");
                },
                error:function(){
    
                    alert(" Message submission failed ");
                }
            });



        }
    </script>

Refresh the page , The data is still there , But restart the server , The data doesn't exist , So you need to save the data on your hard disk .

Use JDBC The basic flow :

  1. create data source
  2. Establish connection with database
  3. structure SQL sentence
  4. perform SQL sentence
  5. If it's a query statement , Need to traverse the result set , If it's insertion / Delete / modify , You don't need to
  6. Close the connection , Release resources

Part of the source code :

private void save(Message message){
    
        // Save a message in the database 
        Connection connection=null;
        PreparedStatement statement=null;
        try {
    
            //1. Establish a connection to the database 
             connection=DBUtil.getConnection();
            //2. structure SQL
            String sql="insert into message values(?,?,?)";
             statement=connection.prepareStatement(sql);
            statement.setString(1,message.from);
            statement.setString(2,message.to);
            statement.setString(3,message.message);
            //3. perform sql
            statement.executeUpdate();
            //4. Release resources 

        } catch (SQLException e) {
    
            e.printStackTrace();
        }finally {
    
            DBUtil.close(connection,statement,null);
        }
    }

    private List<Message> load(){
    
        List<Message> messages=new ArrayList<>();
        // Get all the messages from the database 
        Connection connection=null;
        PreparedStatement statement=null;
        ResultSet resultSet=null;
        try {
    
            connection=DBUtil.getConnection();
            String sql="select * from message";
            statement=connection.prepareStatement(sql);
            resultSet=statement.executeQuery();
            while(resultSet.next()){
    
                Message message=new Message();
                message.from=resultSet.getString("from");
                message.to=resultSet.getString("to");
                message.message=resultSet.getString("message");
                messages.add(message);
            }
        } catch (SQLException e) {
    
            e.printStackTrace();
        }finally {
    
            DBUtil.close(connection,statement,resultSet);
        }
        return  messages;
    }
public class DBUtil {
    private static final String URL="jdbc:mysql://127.0.0.1:3306/java?characterEncoding=utf8&useSSL=false";
    private static  final  String USERNAME="root";
    private static  final  String PASSWORD="999990";
    private volatile static DataSource dataSource = null;

    private  static DataSource getDataSource() {
        if(dataSource == null){
            synchronized (DBUtil.class){
                if(dataSource==null) {
                    dataSource = new MysqlDataSource();
                    ((MysqlDataSource)dataSource).setURL(URL);
                    ((MysqlDataSource)dataSource).setUser(USERNAME);
                    ((MysqlDataSource)dataSource).setPassword(PASSWORD);
                }
            }
        }


        return dataSource;
    }

    public static Connection getConnection() throws SQLException {
        return getDataSource().getConnection();
    }

    public static void close(Connection connection, PreparedStatement statement, ResultSet resultSet) {
        if(resultSet != null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(statement != null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(connection != null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

The basic steps of developing the confession wall :
(1) Agree on the front and back-end interaction interface ( What is the request , What is the response )
(2) Development server code
Write first Servlet Able to handle requests from the front end
Write database code , To store / Get key data
(3) Develop client code
be based on ajax Ability to construct requests and parse responses
Be able to respond to user's operation ( After clicking the button , Trigger the behavior of sending a request to the server )

MVC
Model( Logic for operating data access )
View( User interface )
Controller( controller , The key logic after processing the request )
 Insert picture description here

原网站

版权声明
本文为[A snail at the end of a pyramid]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206121617102074.html