Request request summary

Keywords: Java SQL Apache JSP

 

Request line:

Request Method, Request Address and Parameters

public class LineServlet extends HttpServlet {



protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {



//1. How to get the request

String method = request.getMethod();

System.out.println("method:"+method);

//2. Getting the requested resource-related content

String requestURI = request.getRequestURI();//Client Address

StringBuffer requestURL = request.getRequestURL();//Address with http

System.out.println("uri:"+requestURI);

System.out.println("url:"+requestURL);

//Get the name of the web application

String contextPath = request.getContextPath();//Get Project Name

System.out.println("web Application:"+contextPath);

//String of parameters after address

String queryString = request.getQueryString();

System.out.println(queryString);

//3. Get Client Information - Get Visitor IP Address

String remoteAddr = request.getRemoteAddr();//Address of client

System.out.println("IP:"+remoteAddr);//Why did you get it?





}



protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response);

}

}

Summary:

The difference between a url and a URI:

Stringbuffer is different from string: somewhat like the relationship between an array and a set

String is characterized by the fact that once assigned, it cannot change the character object it points to, and if changed, it will point to a new character object

StringBuffer objects can call their methods to dynamically add, insert, modify, and delete operations (.append())

Convert: Once a StringBuffer generates the final string you want, you can invoke its toString method to convert it to a String object

     

 

Request Header:

The form of key-value pairs: stores some basic information about the client and the request

package com.ithiema.header;



import java.io.IOException;

import java.util.Enumeration;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class HeaderServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

//1. Get the specified header

String header = request.getHeader("User-Agent");//Gets the value corresponding to a key.(The type of browser the user uses)

System.out.println(header);

//2. Get the names of all headers

Enumeration<String> headerNames = request.getHeaderNames();//Get n key names and put back one Enumeration <String>type data

while(headerNames.hasMoreElements()){//.hasMoreElements() returns Boolean data

String headerName = headerNames.nextElement();//Get Key

String headerValue = request.getHeader(headerName);//Get value

System.out.println(headerName+":"+headerValue);

}

}


protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response);

}

}

Summary:

The Enumeration interface defines methods by which elements in a collection of objects can be enumerated (one at a time).(is an iterator) Interotar

A bit like a collection for storing objects.It's just a slightly different way to get objects (collections are traversed) the commonly used methods, hasMoreElements (),.NextElements ()

 


 

package com.ithiema.header;



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 RefererServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {


//Judging the source of the news

String header = request.getHeader("referer");



if(header!=null&&header.startsWith("http://localhost")){

//Jump from my own website to see the news

response.setContentType("text/html;charset=UTF-8");

response.getWriter().write("China has indeed won 100 gold medals....");

}else{

response.setContentType("text/html;charset=UTF-8");

response.getWriter().write("You are a chain stealer, shame!!");

}


}

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response);

}

}

String object commonly used method: equals("string"): whether the same as a string.startwith (string) begins with a string

response.setContentType("text/html;charset=utf-8");

response.setHeader("refresh", "5;http://www.baidu.com"); used when the position of a string is to pass in several useful parameters; separated

if() not followed by parentheses; adding an error

 

 

 

Domain object:

Forward:

public class Servlet1 extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {


request.setAttribute("name", "tom");

RequestDispatcher dispatcher = request.getRequestDispatcher("/servlet2");

dispatcher.forward(request, response);



}



protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response);

}

}









public class Servlet2 extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

//Remove data from request domain

Object attribute = request.getAttribute("name");//getAttribute is to get the content in the domain

response.getWriter().write("hello haohao..."+attribute);

}

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response);

}

}

Requestor:

public class ContentServlet extends HttpServlet {



protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

//1. Get a single form value

String username = request.getParameter("username");//getParameter is what gets in the body

System.out.println(username);

String password = request.getParameter("password");

System.out.println(password);

//2. Get values from multiple forms

String[] hobbys = request.getParameterValues("hobby");

for(String hobby:hobbys){

System.out.println(hobby);

}

//3. Get the names of all request parameters

Enumeration<String> parameterNames = request.getParameterNames();

while(parameterNames.hasMoreElements()){

System.out.println(parameterNames.nextElement());

}

System.out.println("------------------");

//4. Obtain all parameter parameters encapsulated in a Map <String, String[]>

Map<String, String[]> parameterMap = request.getParameterMap();

for(Map.Entry<String, String[]> entry:parameterMap.entrySet()){//This is how the map collection is traversed

System.out.println(entry.getKey());

for(String str:entry.getValue()){

System.out.println(str);

}

System.out.println("---------------------------");

}

}


protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response);

}

}

Summary:

Map.Entry<String, String[]> entry:

map.entrySet() takes out each key-value pair in a map and encapsulates it as an Entry object in a Set.

Map.Entry<String, String[]>means a generic type.

Indicates that Entry contains two string s, key and value of allrecordmap

Breakpoint Debugging: F8 is tuned to the next breakpoint (if not, run directly to the end)

F5 is a step-by-step debugging into the function.

F6 is a step-by-step debugging that does not go inside the function.

F7 is returned from within a function to the caller.

 

 

Case demo:

Sign in:

package com.ithiema.login;



import java.io.IOException;

import java.sql.SQLException;



import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;



import org.apache.commons.dbutils.QueryRunner;

import org.apache.commons.dbutils.handlers.BeanHandler;



import com.ithiema.register.User;

import com.ithiema.utils.DataSourceUtils;



public class LoginServlet extends HttpServlet {



protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {



request.setCharacterEncoding("UTF-8");



//1. Get user name and password

String username = request.getParameter("username");

String password = request.getParameter("password");

//2. Call a business method to query the user

User login = null;

try {

login = login(username,password);

} catch (SQLException e) {

e.printStackTrace();

}

//3. Determine if the username and password are correct by whether or not the user is null

if(login!=null){

//User name and password are correct

//Logon successfully jumped to the home page of the website

response.sendRedirect(request.getContextPath());

}else{

//ERROR Incorrect username or password

//Jump back to current login.jsp

//Store error information in request domain using forward to login.jsp

request.setAttribute("loginInfo", "ERROR Incorrect username or password");

request.getRequestDispatcher("/login.jsp").forward(request, response);

}



}



public User login(String username,String password) throws SQLException{

QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());

String sql = "select * from user04 where uname=? and upassword=?";

User user = runner.query(sql, new BeanHandler<User>(User.class), username,password);

return user;

}



protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response);

}

}

Summary: There are generally 404 possible causes: code issues, profile reasons.Write wrong server or client address for jump

 

 

Registration:

package com.ithiema.register;


import java.io.IOException;

import java.lang.reflect.InvocationTargetException;

import java.sql.SQLException;

import java.util.Map;

import java.util.UUID;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import org.apache.commons.beanutils.BeanUtils;

import org.apache.commons.dbutils.QueryRunner;

import com.ithiema.utils.DataSourceUtils;

public class RegisterServlet extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

//Set the encoding for request - only for post

request.setCharacterEncoding("UTF-8");

//get-style scrambling resolution

//String username = request.getParameter("username"); //Scrambled code. What if there are more parameters??

//Decode using utf-8 with iso8859-1 encoding first

//username = new String(username.getBytes("iso8859-1"),"UTF-8");


//1. Getting data

//String username = request.getParameter("username"); when there are few elements in the body of the request.Use this

//System.out.println(username);

//String password = request.getParameter("password");

//.....



//2. Encapsulate Bulk to javaBean

//User user = new User();

//user.setUsername(username);

//user.setPassword(password);



//Use BeanUtils for automatic mapping encapsulation

//How BeanUtils works: Encapsulate data in a map according to the corresponding relationship between key and entity attributes

//The name of the key is automatically encapsulated in the entity as long as it is the same as the name of the entity's attributes (the name is assigned automatically as it is determined)

Map<String, String[]> properties = request.getParameterMap();//Everything that uses this method should be encapsulated.Use this when requesting bodies are more frequent

User user = new User();//The fields in the object can only be encapsulated as User, not manually.

try {

BeanUtils.populate(user, properties);

} catch (IllegalAccessException | InvocationTargetException e) {

e.printStackTrace();

}



//The user object at this location is now encapsulated

//Manual encapsulation uid--uuid--32 bits of random, non-repeating string--36 bits after java code generation

user.setUid(UUID.randomUUID().toString());



//3. Pass parameters to a business operation method

try {

regist(user);

} catch (SQLException e) {

e.printStackTrace();

}


//4. Jump to the login page if you think your registration was successful

response.sendRedirect(request.getContextPath()+"/login.jsp");



}



//Method of registration

public void regist(User user) throws SQLException{

//Operational Database

QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());

String sql = "insert into user values(?,?,?,?,?,?,?)"; //Standard on tables in a database



    int row=r

/*System.out.println(user.getUsername());

System.out.println(user.getPassword());

System.out.println(user.getBirthday());

System.out.println(user.getSex());*/

    if(row>0)

    {

     System.out.println("login was successful");

    }

    else{

     System.out.println("login has failed");

    }

}



protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response);

}




}

  

Summary: General Issues Summary: 404 jump issues (server address, client address, and configuration file) 500 ([configuration file]), code issues, sql statement issues

36 original articles were published. 54 were praised. 10,000 visits+
Private letter follow

Posted by witham on Mon, 09 Mar 2020 20:05:58 -0700