1.ajax Getting Started case
1.1 Build the Web environment
Ajax for you, should be not unfamiliar, because of the production of Ajax, leading to the front page and server data transfer between the very easy, but also to achieve a local refresh page. AJAX enables asynchronous updating of Web pages by making a small amount of data exchange in the background with the server. This means you can update portions of a Web page without reloading the entire page.
For Javaweb projects, Ajax is primarily used for the transfer of data between browsers and servers.
If it is simply piling up knowledge points, it will be more boring, then according to the Convention, I do not continue to introduce Ajax, but to write a case.
Open Eclipse and create a new Web project.
If the Javaweb project is not clear enough, you can refer to my previous article. I
Directory structure:
<?xml version= "1.0" encoding= "UTF-8"?>
<web-app>
</web-app>
This is good, the Web project has been built.
Do not write down for the time being, make sure our work so far is no problem.
The verification method is to create an empty JSP page in the WebContent directory, and write what you want.
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "
pageencoding=" UTF-8 "%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
Start Tomcat and run the project.
No error.
Open the browser, enter the access address, I here the Tomcat port number is 80, the default can not write.
http://localhost/ajax/index.jsp
Come on, no problem.
OK, this shows that our web project is built without problems.
1.2 Writing server program servlet
Personal sentiment, pristine finishing
The Web environment has been set up, next, let's write a simple servlet program, Tomcat is a server, now it has a Web project called Ajax, then these servlet is like a Web project inside a small function.
Your computer has Qq,word, anti-virus software and other programs. A Web project, which is an application. is essentially the same as the QQ concept on your computer.
You open QQ, you can chat, voice, video. These small functions, analogy to the Javaweb project, is a servlet.
Many people know the framework, such as the famous SPRINGMVC, there are a controller, in fact, these controller what is the thing, do not be afraid, they are actually to the servlet to do a package, essentially the same.
We write a servlet, all need to go to the web.xml inside register, otherwise will not use. You install a QQ, the registry is not sure you also need to register Ah, this is not the same?
Well, there's not much to gossip about. Let's write a small function, which is a servlet.
Inherit HttpServlet and rewrite Doget method at the same time
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 Myservlet extends httpservlet{
@Override
protected void doget (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {
System.out.println ("a");
}
We don't write anything in there first.
Next, we're going to register this servlet inside the web.xml.
<?xml version= "1.0" encoding= "UTF-8"?>
<web-app>
<servlet>
<!--This is the name of the servlet- >
<servlet-name>MyServlet</servlet-name>
<servlet-class>myservlet</ Servlet-class>
<!--here Write the servlet class in the package path
-->
</servlet>
<servlet-mapping> <! --Here is the address map-->
<servlet-name>MyServlet</servlet-name>
<!--write the servlet mapping address here-->
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
</web-app>
Ok,servlet Registration is complete, we first visit to ask this function.
Restart Tomcat.
Visit: Http://localhost/ajax/MyServlet
1.3 Front Page Design
The server applet is almost done, and now we need to write a front page to interact with the server. This page is also for the user to see. In other words, users can access our servlet only through the foreground page.
Let's write a small case, send a word to the server on the page, and then the server gives a response.
This is a simple case, mainly used to familiarize yourself with the process.
For the sake of simplicity, I do not adjust the CSS style, directly with Bootstrap bar.
Introduce bootstrap's core CSS file.
Then, modify the index.jsp
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%> <!
DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
Page effect:
1.4 Data requests based on Get mode
When we click on the Submit button, alert (), if successful, then there is no problem with the Click event. Then, continue writing down the code.
If this is the case, we are submitting it through form forms, but then there is a problem that the page will refresh and the code is relatively difficult to understand.
Since the Ajax came out, this situation has been greatly improved, local refresh technology at that time, is still very good.
I first give the implementation code:
Btn.onclick = function () {
var xhr = window. Xmlhttprequest?new XMLHttpRequest (): New ActiveXObject ("Microsoft.XMLHTTP");
Xhr.open ("Get", "myservlet?message=" +document.getelementsbytagname ("input") [0].value,true);
Xhr.send ();
Xhr.onreadystatechange = function () {
if (xhr.readystate==4 && xhr.status==200) {
alert ( Xhr.responsetext);}}
At the same time modify the Myservlet
@Override
protected void doget (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {
String msg = req.getparameter ("message");
SYSTEM.OUT.PRINTLN (msg);
Restart Tomcat to access the index.jsp page.
Now the browser generally has debugging function, click F12, Debugging interface came out. Then, find a network, take Google browser as an example
The network view will display all the data interactively, including the introduction of JS, CSS files, and various requests and responses, which will be shown here.
For example, now I refresh the page
I was so refreshed that the first thing the server received was such a url:http://localhost/ajax/index.jsp
This is a request, the server received this request, returned to me index.jsp page and bootstrap.min.css this file.
Because I did introduce bootstrap.min.css in index.jsp, so he just loaded it in together.
Now, I type in a word, click Submit, and see what happens?
We submit the contents of the input box to the server program Myservlet
The console has been accepted, here more fortunate, did not encounter the problem of Chinese garbled, then no matter what garbled.
Because nothing was returned in the Myservlet, the alert came out empty.
OK, let's return a word to the browser.
@Override
protected void doget (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {
String msg = req.getparameter ("message");
SYSTEM.OUT.PRINTLN (msg);
Resp.setcontenttype ("Text/html;charset=utf-8");
PrintWriter out=resp.getwriter ();
Out.println ("Hello, this is the information returned by the server!") ");
Out.flush ();
Out.close ();
}
Click the Submit button again
OK, okay.
Next, take a look at the details of the request.
In the comparison of the JS code, it is clear at a glance.
Btn.onclick = function () {
var xhr = window. Xmlhttprequest?new XMLHttpRequest (): New ActiveXObject ("Microsoft.XMLHTTP");
Xhr.open ("Get", "myservlet?message=" +document.getelementsbytagname ("input") [0].value,true);
Xhr.send ();
Xhr.onreadystatechange = function () {
if (xhr.readystate==4 && xhr.status==200) {
alert ( Xhr.responsetext);}}
ReadyState:
0: Request not initialized
1: The server connection has been established and has not been sent
2: Request received
3: In Request processing
4: The request is complete and the response is ready
When the readyState equals 4 and the status is 200, the response is ready.
The request is a get, and the responsetext is printed only when the returned status code is 200, which is the corresponding
Out.println ("Hello, this is the information returned by the server!") ");
This sentence.
1.5 post-based data requests
The Get method will display the value you submitted in the URL address bar, and the Post method will not. So, relatively speaking, the post method is relatively safe.
The Post method is about the same as the Get method on the process, and I go directly to the code:
Window.onload = function () {
var btn = document.getElementById ("submit");
Btn.onclick = function () {
var xhr = window. Xmlhttprequest?new XMLHttpRequest (): New ActiveXObject ("Microsoft.XMLHTTP");
Xhr.open ("Post", "Myservlet", true);
Xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
var postdata = {message:document.getElementsByTagName ("input") [0].value};
var postdatastr = (function (obj) {//converted to the string required by post.
var str = "";
For (var prop in obj) {
str + + prop + ' = ' + Obj[prop] + ' & '
} return
str;
}) (postdata);
alert (POSTDATASTR);
Xhr.send (POSTDATASTR);
Xhr.onreadystatechange = function () {
if (xhr.readystate==4 && xhr.status==200) {
alert ( Xhr.responsetext);};}};
Myservlet.java
Import java.io.IOException;
Import Java.io.PrintWriter;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
public class Myservlet extends httpservlet{
@Override
protected void doget (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {
req.setcharacterencoding ("UTF-8");
String msg = req.getparameter ("message");
SYSTEM.OUT.PRINTLN (msg);
Resp.setcontenttype ("Text/html;charset=utf-8");
PrintWriter out=resp.getwriter ();
Out.println ("Hello, this is the information returned by the server!") ");
Out.flush ();
Out.close ();
}
@Override
protected void DoPost (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {
doget (req, resp);
}
}
The above is a small set of JavaScript to introduce you to talk about Ajax graphics and text detailed, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!