当前位置:网站首页>Servlet learning notes
Servlet learning notes
2022-07-04 12:27:00 【Kangkang needs to refuel】
Servlet Learning notes
- One 、 How to be in Tomcat Configure virtual host in (host)
- Two 、HttpServletRequest object
- 3、 ... and 、 Get request information
- Four 、 Get request data
- 5、 ... and 、 Get checkbox data
- 6、 ... and 、 Get all submitted data key
- 7、 ... and 、 Use Map Structure to get submitted data
- 8、 ... and 、 Set request encoding
- Nine 、 Resource access method
- Ten 、 Get request header information
- 11、 ... and 、 Get request header case
One 、 How to be in Tomcat Configure virtual host in (host)
1. Create a page
establish index.html page
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> ITBZ </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>
<BODY> Welcome to ITBZ </BODY>
</HTML>
2. modify server.xml add to Host Configuration and addition Context To configure
<Host name="www.itbz.com" appBase="webapps"
unpackWARs="true" autoDeploy="true">
<Context path="/itbz" docBase="C:\javatest"/>
</Host>
3. modify windows Of Host file
Realize domain name and IP The binding of
Host file location
C:\Windows\System32\drivers\etc
4. Access resource test results
Two 、HttpServletRequest object
HttpServletRequest Object represents the request of the client browser , When the client browser passes HTTP When the protocol accesses the server ,HTTP All information in the request will be Tomcat Parsed and encapsulated in this object , Through the methods provided by this object , You can get all the information requested by the client .
3、 ... and 、 Get request information
req.getRequestURL()
Returns the complete when the client browser makes a request URL.
req.getRequestURI()
Return the specified resource part of the request line .
req.getRemoteAddr()
Returns the client that made the request IP Address .
req.getLocalAddr()
return WEB Server's IP Address .
req.getLocalPort()
return WEB The server processes Http The protocol connector listens
// Get request information
public class DemoServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
StringBuffer requestURL = req.getRequestURL();
String requestURI = req.getRequestURI();
String remoteAddr = req.getRemoteAddr();
PrintWriter out = resp.getWriter();
out.println("<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.0 Transitional//EN'>");
out.println("<HTML>");
out.println("<HEAD><TITLE> ITBZ </TITLE><HEAD>");
out.println("<BODY>");
out.println("URL:"+requestURL+"<br/>");
out.println("URI:"+requestURI+"<br/>");
out.println("RemoteAddr:"+remoteAddr+"<br/>");
out.println("</BODY>");
out.println("</HTML>");
out.flush();
}
}
stay web.xml in :
<servlet>
<servlet-name>demoServlet</servlet-name>
<servlet-class>servlet.DemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>demoServlet</servlet-name>
<url-pattern>/demo.do</url-pattern>
</servlet-mapping>
result :
Four 、 Get request data
stay Servlet How to get the requested data
req.getParameter(“key”)
according to key Get specified value.
// Get request data
public class GetRequestDataServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
PrintWriter out = resp.getWriter();
out.println("<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.0 Transitional//EN'>");
out.println("<HTML>");
out.println("<HEAD><TITLE> ITBZ </TITLE><HEAD>");
out.println("<BODY>");
out.println("UserName:"+username+"<br/>");
out.println("</BODY>");
out.println("</HTML>");
out.flush();
}
}
HTML Interface :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="getInfo.do" method="post">
user name :<input type="text" name="username"/><br/>
<input type="submit" value="ok"/>
</form>
</body>
</html>
web.xml Interface :
<servlet>
<servlet-name>getRequestDataServlet</servlet-name>
<servlet-class>servlet.GetRequestDataServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getRequestDataServlet</servlet-name>
<url-pattern>/getInfo.do</url-pattern>
</servlet-mapping>
5、 ... and 、 Get checkbox data
Get check box (checkbox Components ) The value in
req.getParameterValues(“checkboxkey”)
Get check box (checkbox Components ) The value in , Return to one String[]
public class GetRequestDataServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String[] userlikes = req.getParameterValues("userlike");
List<String> strings = Arrays.asList(userlikes);
PrintWriter out = resp.getWriter();
out.println("<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.0 Transitional//EN'>");
out.println("<HTML>");
out.println("<HEAD><TITLE> ITBZ </TITLE><HEAD>");
out.println("<BODY>");
out.println("UserName:"+username+"<br/>");
out.println("UserName:"+strings+"<br/>");
out.println("</BODY>");
out.println("</HTML>");
out.flush();
}
}
HTML page :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="getInfo.do" method="post">
user name :<input type="text" name="username"/><br/>
hobby :<input type="checkbox" name="userlike" value="sport"/> sports
<input type="checkbox" name="userlike" value="music"/> music
<input type="submit" value="ok"/>
</form>
</body>
</html>
6、 ... and 、 Get all submitted data key
Get all submitted data key
req.getParameterNames()
Get all the data in the request key, This method returns an enumeration
public class GetRequestDataServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String[] userlikes = req.getParameterValues("userlike");
List<String> strings = Arrays.asList(userlikes);
Enumeration<String> parameterNames = req.getParameterNames();
List<String> keys = new ArrayList<>();
while (parameterNames.hasMoreElements()){
keys.add(parameterNames.nextElement());
}
PrintWriter out = resp.getWriter();
out.println("<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.0 Transitional//EN'>");
out.println("<HTML>");
out.println("<HEAD><TITLE> ITBZ </TITLE><HEAD>");
out.println("<BODY>");
out.println("UserName:"+username+"<br/>");
out.println("UserName:"+strings+"<br/>");
out.println("Keys:"+keys+"<br/>");
out.println("</BODY>");
out.println("</HTML>");
out.flush();
}
}
result :
7、 ... and 、 Use Map Structure to get submitted data
req.getParameterMap()
Get all the data in the request and store it in a Map In structure , This method returns a Map, among key by
String type value
public class GetRequestDataServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String[] userlikes = req.getParameterValues("userlike");
List<String> strings = Arrays.asList(userlikes);
Enumeration<String> parameterNames = req.getParameterNames();
List<String> keys = new ArrayList<>();
while (parameterNames.hasMoreElements()){
keys.add(parameterNames.nextElement());
}
Map<String,String[]> parameterMap = req.getParameterMap();
PrintWriter out = resp.getWriter();
out.println("<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.0 Transitional//EN'>");
out.println("<HTML>");
out.println("<HEAD><TITLE> ITBZ </TITLE><HEAD>");
out.println("<BODY>");
out.println("UserName:"+username+"<br/>");
out.println("UserName:"+strings+"<br/>");
out.println("Keys:"+keys+"<br/>");
// Acquisition iterator
Iterator<Map.Entry<String,String[]>> iterator = parameterMap.entrySet().iterator();
while (iterator.hasNext()){
Map.Entry<String,String[]> entry = iterator.next();
out.println("Keys:" + entry.getKey() +" Value:"+ Arrays.asList(entry.getValue()) +"<br/>");
}
out.println("</BODY>");
out.println("</HTML>");
out.flush();
}
}
8、 ... and 、 Set request encoding
req.setCharacterEncoding(“utf-8”)
The requested packet is transmitted over the network based on bytes ,Tomcat After receiving the requested packet, the
Byte to character . stay Tomcat Is used in ISO-8859-1 The single byte encoding of completes the conversion between bytes and characters ,
Therefore, there will be garbled code if the data contains Chinese , Can pass req.setCharacterEncoding(“utf-8”) Method to mention
Re encode the submitted data according to the specified coding method .
public class GetRequestDataServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
String username = req.getParameter("username");
String[] userlikes = req.getParameterValues("userlike");
List<String> strings = Arrays.asList(userlikes);
Enumeration<String> parameterNames = req.getParameterNames();
List<String> keys = new ArrayList<>();
while (parameterNames.hasMoreElements()){
keys.add(parameterNames.nextElement());
}
Map<String,String[]> parameterMap = req.getParameterMap();
PrintWriter out = resp.getWriter();
out.println("<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.0 Transitional//EN'>");
out.println("<HTML>");
out.println("<HEAD><TITLE> ITBZ </TITLE><HEAD>");
out.println("<BODY>");
out.println("UserName:"+username+"<br/>");
out.println("UserName:"+strings+"<br/>");
out.println("Keys:"+keys+"<br/>");
// Acquisition iterator
Iterator<Map.Entry<String,String[]>> iterator = parameterMap.entrySet().iterator();
while (iterator.hasNext()){
Map.Entry<String,String[]> entry = iterator.next();
out.println("Keys:" + entry.getKey() +" Value:"+ Arrays.asList(entry.getValue()) +"<br/>");
}
out.println("</BODY>");
out.println("</HTML>");
out.flush();
}
}
Nine 、 Resource access method
1. Absolute path
Absolute path access to resources is expressed directly in ”/” As a project Content Path. This method is applicable to ”/” As a project Content Path
<form action="/getInfo.do" method="post">
2. Relative paths
The relative path access resource indicates that it will be relative to the project Content Path As a relative path . This method is applicable to the specific... Specified for the project Content Path
<form action="getInfo.do" method="post">
Ten 、 Get request header information
req.getHeader(“headerKey”)
According to the key Get corresponding value
String headerValue = req.getHeader(“headerKey”);
.
req.getHeaderNames()
Get all in the request header key, This method returns the enumeration class
Enumeration<>
// Get request header information
public class GetRequestHeaderServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String header = req.getHeader("Accept-Language");
Enumeration<String> headerNames = req.getHeaderNames();
PrintWriter out = resp.getWriter();
out.println("<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.0 Transitional//EN'>");
out.println("<HTML>");
out.println("<HEAD><TITLE> ITBZ </TITLE><HEAD>");
out.println("<BODY>");
while (headerNames.hasMoreElements()){
String key = headerNames.nextElement();
String value = req.getHeader(key);
out.println("key:"+key+" Value:"+value+"<br/>");
}
out.println("</BODY>");
out.println("</HTML>");
}
}
web.xml:
<servlet>
<servlet-name>getRequestHeaderServlet</servlet-name>
<servlet-class>servlet.GetRequestHeaderServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getRequestHeaderServlet</servlet-name>
<url-pattern>/getHeader.do</url-pattern>
</servlet-mapping>
result :
11、 ... and 、 Get request header case
demand : Write a Servlet, If the browser language is zh-CN, Show “ Hello , Smart Chinese !”, If the browser language is set to en-US, Then it shows “Hello,American”
// Get request header case
public class LanguageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String header = req.getHeader("accept-language");
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
out.println("<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.0 Transitional//EN'>");
out.println("<HTML>");
out.println("<HEAD><TITLE> ITBZ </TITLE><HEAD>");
out.println("<BODY>");
if (header.indexOf("zh-CN") != -1){
out.println(" Hello , Smart Chinese !");
}else if(header.indexOf("en-US") != -1){
out.println("hello,American");
}else{
out.println(" I'm sorry , The language is not supported !");
}
out.println("</BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
}
web.xml:
<servlet>
<servlet-name>languageServlet</servlet-name>
<servlet-class>servlet.LanguageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>languageServlet</servlet-name>
<url-pattern>/language.do</url-pattern>
</servlet-mapping>
边栏推荐
- 13、 C window form technology and basic controls (3)
- QQ set group information
- Login operation (for user name and password)
- LxC shared directory addition and deletion
- Application of slice
- Azure solution: how can third-party tools call azure blob storage to store data?
- Some summaries of the 21st postgraduate entrance examination 823 of network security major of Shanghai Jiaotong University and ideas on how to prepare for the 22nd postgraduate entrance examination pr
- Decrypt the advantages of low code and unlock efficient application development
- How to judge the advantages and disadvantages of low code products in the market?
- Games101 Lesson 8 shading 2 Notes
猜你喜欢
2021-08-09
Automatic translation between Chinese and English
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 10
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 21
OSI model notes
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 14
QQ group collection
MySQL advanced review
Method of setting default items in C # ComboBox control code
Global function Encyclopedia
随机推荐
SAP ui5 date type sap ui. model. type. Analysis of the display format of date
QQ set group information
template<typename MAP, typename LIST, typename First, typename ... Keytypes > recursive call with indefinite parameters - beauty of Pan China
Ternsort model integration summary
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 23
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 17
DDS-YYDS
Leetcode: 408 sliding window median
IPv6 experiment
Reptile learning 3 (winter vacation learning)
queue
03_ Armv8 instruction set introduction load and store instructions
13、 C window form technology and basic controls (3)
Shift EC20 mode and switch
Btrace tells you how to debug online without restarting the JVM
[directory] search
MySQL performance optimization index
Lvs+kept highly available cluster
2018 meisai modeling summary +latex standard meisai template sharing
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 18