The third part _jsp the detailed continuation

Source: Internet
Author: User
Tags file handling

The second part left a question, is the meaning of reloadable= "true" configured in Server.xml?

In the MyEclipse for a class save is compiled, do not have to be compiled, after compilation requires the server restart, that is, the meaning of reloadable true.

The process of generating a static page using a servlet:

The browser (client) makes the request, the server (TOMCAT) receives the request, invokes the generated class file, and sends the execution result in HTML code to the browser (that is, the client).

Using JSP

Create a new JSP page in the Webroot directory (new->jsp (Advanced Templates)): test.jsp, add the following code to the body tag of the file:

<body>    

Access http://localhost:8080/test/in the browser Test.jsp, can get the same effect as the servlet in the second part, summed up is: servlet is nested HTML code Java class, and JSP is nested some Java code HTML file, but the two are essentially the same, the servlet can do things JSP can be done, Vice versa. But JSP eliminates the step of configuring the Web. xml file.

1. Use of Forms

In order to support Chinese, the pageencoding in the JSP file is set to "UTF-8", i.e. pageencoding= "UTF-8". Write the following code:

<body>    <form action= "/test/secondservlet" >   User: <input type = "text" name = "username" size = "20" &  gt;<br>  Password: <input type = "password" name = "password" size = "><br>"  <input type = "Submit" Value = "Commit" > <input type = "reset" value = "reset" >  </form></body>

The following is a description of the action of the form: it indicates where to submit when the mouse button is clicked. Below we write the handling of this resource for Secondservlet. We give up the previous purely manual way, using MyEclipse to provide us with the automation features: Under the Com.test.servlet package, a new servlet named Secondservlet, the inheritance method only retains doget () and Dopost () , click Next, its default mapping URL is/servlet/secondservlet, in order to make it easier for us to change it to/secondservlet, delete display name and description, click Finish, Switching to the Web. XML view, you can see that the appropriate information has been added:

<servlet><servlet-name>MyServlet</servlet-name><servlet-class> com.test.servlet.myservlet</servlet-class></servlet>  <servlet>    <servlet-name> Secondservlet</servlet-name>    <servlet-class>com.test.servlet.secondservlet</servlet-class >  </servlet> <servlet-mapping><servlet-name>MyServlet</servlet-name>< url-pattern>/myserv</url-pattern></servlet-mapping>  <servlet-mapping>    < Servlet-name>secondservlet</servlet-name>    <url-pattern>/SecondServlet</url-pattern>  </servlet-mapping>

Switch to the Secondservlet.java file, which has a lot of extra comments and base code, and we'll delete it to form the following:

Package Com.test.servlet;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 SecondServlet Extends Httpservlet{public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioexception{}public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, ioexception{}}

Here we write the code that allows Secondservlet to implement a function: the user name and password that the customer fills in the test.jsp, Secondservlet gets it, and displays it on a JSP page. This completes a simple client-side interaction with the server. The code is written as follows:

Package Com.test.servlet;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 SecondServlet Extends Httpservlet{public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, ioexception{process (request, response);} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, ioexception{ Process (request, response);} public void process (HttpServletRequest request, httpservletresponse response) throws Servletexception, ioexception{ String username = request.getparameter ("username"); String Password = request.getparameter ("password"); Response.setcontenttype ("text/html"); PrintWriter out = Response.getwriter (); Out.println ("<HTML><HEAD><TITLE>Result</TITLE>< /head> "); Out.println (" <BODY> "); Out.println (username + "<br>"); out.println (password); Out.println ("</BODY></HTML>");}} 

Restart the Tomcat server, type http://localhost:8080/test/test.jsp in the browser, enter the username Hello and password world, the page automatically jumps to http://localhost:8080/test/ Secondservlet?username=hello&password=world.

In addition, the form default submission method is get, of course we can also take the Post method:

<form action= "/test/secondservlet" method= "POST" >

This page jumps when the address bar is: Http://localhost:8080/test/SecondServlet, this is the use of get/post submitted by the appearance of the difference.

The difference between get and post

    • Handled differently (as stipulated by the agreement itself)
    • Different ways of dealing with it
    • The address bar renders different results

2. How to generate JSP and servlet:

The servlet is first compiled into a class file and then called by the server.

The JSP is first converted to a servlet(Java file) and then compiled into a class file, which is processed by the server call.

How do I verify this? Enter the directory below tomcat: D:\Program files\apache-tomcat-6.0.44\work\catalina\localhost\test\org\apache\jsp, you can see Test_ Jsp.java.

So since there is a servlet, why need JSP, this is because of the very simple code written in JSP, with servlet writing will become very complex, see Test_jsp.java can be very intuitive to understand this point.

3. Write a slightly more complex servlet

Create a new servlet under Com.test.servlet named Thirdservlet, and the process is the same as Secondservlet. The associated configuration is automatically added to Web. Xml. Thirdservlet.java source code is as follows:

Package Com.test.servlet;import Java.io.ioexception;import Java.io.printwriter;import java.util.Random;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;public class ThirdServlet Extends Httpservlet{private static string[] responses = {"Yes", "No", "Maybe", "later", "It is Your call", "Not a Chance"} ;p ublic void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, ioexception{ Process (request, response);} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, ioexception{ Process (request, response);} public void process (HttpServletRequest request, httpservletresponse response) throws Servletexception, ioexception{ String reply = Generatereply (); Response.setcontenttype ("text/html"); PrintWriter out = Response.getwriter (); Out.println ("

Reboot Tomcat, which is constantly refreshed in Http://localhost:8080/test/ThirdServlet, will be displayed randomly.

4. Replace Secondservlet with JSP

In Webroot, new a JSP named result, and then make changes to the form in test.jsp:

Add the following code to the body of the result.jsp:

<body>    <%string username = request.getparameter ("username");      String Password = request.getparameter ("password");     %>     Username: <%= username%><br>     Password: <%= password%> </body>

Enter http://localhost:8080/test/test.jsp, fill in the information Hello, world, automatically jump to http://localhost:8080/test/result.jsp?username= Hello&password=world

A few notes:

    • Request and response are the nine default objects in the JSP two, do not need to declare, directly can be used, analogy in Java lang Packet does not need to import, they use too frequently, resulting in this situation.
    • Username: <%= username%>, where <%=%> is a JSP expression, it can also be scripted: Username: <% out.print (username);
    • JSP in the Inverted package: <%@ page language= "java" import= "java.util.*" pageencoding= "iso-8859-1"%>, multiple packages are separated by commas.

5. Consolidate JSP expressions

Create the code in the third.jsp,<body> tag as follows:

  <body>  <%calendar Calendar = Calendar.getinstance ();   int currenthour = Calendar.get (calendar.hour_of_day);  %>  <% if (Currenthour <) {%>  good morning!  <%}else if (Currenthour > && currenthour <) {%>  good afternoon!  <%}else{%>  Good evening!  <%}%>  </body>

Refresh http://localhost:8080/test/third.jsp in the browser, you can get the current system time is morning/noon/night.

JavaServer Pages (JSP) syntax and built-in objects

    • Introduction to JSP

In the traditional Web page HTML file (*.htm,*.html), if the Java program fragment (scriptlet) and JSP tags, it constitutes a JSP Web page.

Java program fragments can operate the database, redirect Web pages and send e-mail, and so on, to establish dynamic Web site required functions.

All program operations are performed on the server side, and only the resulting results are sent to the client on the network, which greatly reduces the requirement for the customer's browser, even if the customer's browser does not support Java, but can also access the JSP Web page.

JSP file structure and main tags

<%@ page contenttype= "text/html;charset=gb2312"%><%@ page import= "java.util.*"%>...

JSP Example

JSP execution Process

JSP Example

    • JSP Syntax overview

JSP original code contains the JSP element and template data two categories

Template data refers to parts of the JSP engine that are not processed, that is, tags <%......%> other parts, such as the contents of HTML in the code, which are transmitted directly to the client's browser

The JSP element refers to the part that will be processed directly by the JSP engine, which must conform to the Java syntax or cause a compilation error

JSP syntax is divided into three different types:

Compiler directives (DIRECTIVE) For example: <%@ page import= "java.io.*"%> compiler directives include directives, page directives, and taglib directives, which are included in the <%@%> label. The two main instructions are page and include.

Scripting Syntax (SCRIPTING): Includes HTML annotations (<!--Comments-->, which are sent to the client, but not directly displayed, visible in the source code), hidden annotations (<%--COMMENTS--%> Does not occur to the client, for programmers to view the used), declarations, expressions, script segments

Action syntax (action) such as:<jsp:forward>,<jsp:getproperty>,<jsp:setproperty>,<jsp:include> and <jsp :usebean>

JSP syntax format: <%! Declaration [Declaration;] ...%>, see the following example:

<body><center><%! Data date = new Date (); %><%! int A, b, C; %><% A = 12; b = A; c = a + B; %><font color= "Blue" ><%=date.tostring ()%></font><br><b>a=<%= a%></b ><br><b>b=<%= b%></b><br><b>c=<%= C%></b><br></ Center></body>

Of course, we put the two above! Removing does not affect the result of execution, so what is the difference between the two? You can get a conclusion by looking at the servlet code it generates: Band! The position of the variable that generated the variable is the member variable, not added! is the local variable

An expression:

Used to output information on a page, syntax format: <%= expression%>

Script segment:

JSP syntax format: <% code fragment%>, see a JSP instance:

<%@ page language= "java" pageencoding= "gb2312"%><%! int condition; %>

Include directives:

Include directive: Inserts the contents of a static file into the current page. JSP syntax format: <%@ include file= "Realativeurl", such as:

<%--a.jsp contains b.jsp--><%@ page language= "java" pageencoding= "gb2312"%>

Page directive:

The page directive defines the global properties in the JSP file, Syntax format: <%@ page [language= "Java"] [extends= "Package.class"] [import= "{Package.class | package . *}, ... "] [session=] true | false"] [isthreadsafe= "true | false"] [ErrorPage = "Relativeurl"] [ContentType = "Mimetype[;ch Arset=characterset] "| "Text/html;charset=iso-8859-1"] [iserrorpage= "true | false"]%> The important attributes are:

1.language= "Java" declares the kind of scripting language that can currently only be used with "Java"

2.import= "{package.class | package.*},..." A list of Java packages that need to be imported, which act on a program segment, an expression, and a declaration. The following package has been imported at JSP compile time, so there is no need to specify:java.lang.* java.servlet.* javax.servlet.jsp.* javax.servlet.http.*

 3.errorpage= "Realativeurl" to set the JSP file handling exception events

4.iserrorpage= "true | False to set whether this page is an error page, and if set to True, you can use the exception object

TAGLIB directive:

JSP syntax format: <%@ taglib uri= "uritotaglibrary" prefix= "TagPrefix"%> for introduction of custom tag libraries

Jsp:forward

<%--a.jsp Jump to b.jsp--><%@ page contenttype= "text/html"; charset=gb2312 pageencoding= "gb2312"%>

Jsp:include

Contains a static or dynamic file

<%--a.jsp include b.jsp--><%@ page contenttype= "text/html"; charset=gb2312 pageencoding= "gb2312"%>< html>

The third part _jsp the detailed continuation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.