Scala Servlet in Scala Language

Source: Internet
Author: User

To make a language "realistic" and "brilliant", it must be able to serve the real environment and applications. In this Scala guide series for Java developers, Ted Neward will introduce Scala's use in the real environment, that is, how Scala interacts with core Servlet APIs, it may even be corrected.

Scala is obviously an interesting language and is suitable for reflecting the new ideas of language theory and innovation, but it will eventually be used in a "realistic" environment, it must meet certain requirements of developers and be practical in a "realistic" environment.

After learning about some core functions of Scala, you will be able to recognize some flexibility of Scala and be able to use Scala to create DSL with confidence. now let's go to the actual application environment and see how Scala adapts to the environment. In the new phase of this series, we will first discuss most of the Java? Core of the application: Servlet API.

Servlet Review

Recall the Servlet 101 course and tutorial. The core of the servlet environment is to use HTTP client-server exchange through a socket usually port 80. The client can be any "user-proxy" defined by the HTTP specification), and the server is a servlet container. Servlet containers search, load, and execute methods on a Class I wrote. This class must ultimately implement the javax. servlet. Servlet interface.

Generally, Java developers do not write classes that directly implement interfaces. Because the original servlet specification is used to provide a common API for other protocols except HTTP, the servlet namespace is divided into two parts:

A "general" package javax. servlet)

A http-specific package javax. servlet. http)

In this way. servlet. genericServlet implements some basic functions in the general package of the abstract base class. Then, in the derived class javax. servlet. http. httpServlet implements other HTTP-specific functions, which are usually used as the base class of the actual servlet "content. HttpServlet provides a complete Servlet implementation. It delegates the GET request to a doGet method to be overwritten, delegates the POST request to a doPut method to be overwritten, and so on.

Hello, Scala, Hello, Servlet

Obviously, the first servlet written by anyone is a common "Hello, World" servlet; so is the first servlet example of Scala. Recall the servlet tutorials introduced many years ago. At that time, the basic Java "Hello, World" servlet only outputs the HTML response shown in Listing 1:

Listing 1. Expected HTML response

 
  1. <HTML> 
  2.    <HEAD><TITLE>Hello, Scala!</TITLE></HEAD> 
  3.    <BODY>Hello, Scala! This is a servlet.</BODY> 
  4. </HTML> 

Writing a simple servlet in Scala is very simple to implement this operation, and this servlet is almost the same as its corresponding Java form, as shown in Listing 2:

Listing 2. Scala Servlet!

 
  1. import javax.servlet.http.{HttpServlet,  
  2.   HttpServletRequest => HSReq, HttpServletResponse => HSResp}  
  3.  
  4. class HelloScalaServlet extends HttpServlet  
  5. {  
  6.   override def doGet(req : HSReq, resp : HSResp) =  
  7.     resp.getWriter().print("<HTML>" +  
  8.       "<HEAD><TITLE>Hello, Scala!</TITLE></HEAD>" +  
  9.       "<BODY>Hello, Scala! This is a servlet.</BODY>" +  
  10.       "</HTML>")  
  11. } 

Note that I have used some appropriate import aliases to shorten the request type name and corresponding type. In addition, this servlet is almost the same as its Java servlet form. During compilation, remember that the servlet-api.jar is usually released along with the servlet container; in Tomcat 6.0 release, it is hidden in the lib subdirectory) contains a reference; otherwise the servlet API type will not be found.

This is not fully prepared. According to the servlet specification, it must use a web. deploy the xml deployment descriptor to the Web application directory or. in the war file). This descriptor describes the URL to which the servlet should be combined. For such a simple example, it is easiest to use a simple URL to work with it, as shown in listing 3:

Listing 3. deployment descriptor web. xml

 
  1. <!DOCTYPE web-app  
  2.     PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"  
  3.     "http://java.sun.com/dtd/web-app_2_3.dtd"> 
  4. <web-app> 
  5.   <servlet> 
  6.     <servlet-name>helloWorld</servlet-name> 
  7.     <servlet-class>HelloScalaServlet</servlet-class> 
  8.   </servlet> 
  9.   <servlet-mapping> 
  10.     <servlet-name>helloWorld</servlet-name> 
  11.     <url-pattern>/sayHello</url-pattern> 
  12.   </servlet-mapping> 
  13. </web-app> 

From here on, I assume that the reader will adjust/modify the deployment descriptor as necessary, because it has nothing to do with Scala.

Of course, HTML with good format is very similar to XML with good format; In view of this, scala's support for the XML literal value makes it much easier to compile this servlet by referring to "Scala and XML" in references ). Scala does not directly embed a message in the String passed to HttpServletResponse. It can separate the logic and representation in a very simple way). It is used to store the message in an XML instance, then pass it back:

Listing 4. Hello, Scala Servlet!

 
  1. import javax.servlet.http.{HttpServlet,  
  2.   HttpServletRequest => HSReq, HttpServletResponse => HSResp}  
  3.  
  4. class HelloScalaServlet extends HttpServlet  
  5. {  
  6.   def message =  
  7.     <HTML> 
  8.       <HEAD><TITLE>Hello, Scala!</TITLE></HEAD> 
  9.       <BODY>Hello, Scala! This is a servlet.</BODY> 
  10.     </HTML> 
  11.  
  12.   override def doGet(req : HSReq, resp : HSResp) =  
  13.     resp.getWriter().print(message)  
  14. } 

Scala's inline expression evaluate tool uses the XML literal value, which means it is easy to make servlet more interesting. For example, adding the current date to a message is as simple as adding the Calendar expression to XML, but several lines are added {Textjava. util. Calendar. getInstance ). GetTime ). ToString)}. This seems a bit lengthy, as shown in listing 5:

Listing 5. Hello, timed Scala Servlet!

 
  1. import javax.servlet.http.{HttpServlet,  
  2.   HttpServletRequest => HSReq, HttpServletResponse => HSResp}  
  3.  
  4. class HelloScalaServlet extends HttpServlet  
  5. {  
  6.   def message =  
  7.     <HTML> 
  8.       <HEAD><TITLE>Hello, Scala!</TITLE></HEAD> 
  9.       <BODY>Hello, Scala! It's now { currentDate }</BODY> 
  10.     </HTML> 
  11.   def currentDate = java.util.Calendar.getInstance().getTime()  
  12.  
  13.   override def doGet(req : HSReq, resp : HSResp) =  
  14.     resp.getWriter().print(message)  
  15. } 

In fact, the Scala compiler and XML Object messages are integrated into a scala. xml. Node, and then converted to a String when passing it to the print method of the response Writer.

Don't underestimate this-the expressions are separated from the logic and are completely performed within a class. This XML message will be checked during compilation to ensure that the syntax is correct and the format is good, and some benefits are not available in standard servlet or JSP. Scala can deduce the type, so it can omit the actual type messages about message and currentDate, making it like the Dynamic Language Groovy/Grails. The first use is good. The above is a small introduction to Scala Servlet in the Scala language, hoping to be useful to everyone.

  1. Servlet Context range
  2. Brief Analysis on the concept of Servlet 3.0 API
  3. Servlet comments and deployment descriptors
  4. New Features of Java Servlet and Servlet 3.0
  5. Potential risks of Servlet and JSP

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.