Random
using-lishys-notes.notes

Guide


The guide pane on the right contains information organized into sections.

Use the and buttons to move through the sections, or click an accordion tab (shown below) to go directly to a particular topic.



Code Reference


Each paragraph in the guide is usually associated with a particular piece of code. An orange arrow indicates that the code displayed in the middle pane is relevant to the guide text.



If the arrow is gray, simply click anywhere on the paragraph and the relevant code will be displayed.



Code Highlighter


The highlight feature identifies areas of the code which relate to a word or term in the guide. Hover the mouse over any underlined word and the relevant code will be highlighted.



You can disable the highlighting feature at any time by clicking on the button.

Don't forget to make the appropriate code page visible by clicking on any paragraph with a gray arrow.
RandomService.java
package com.lishman.random.service;

import java.util.List;

import com.lishman.random.web.RandomData;


public interface RandomService {
    
    public int randomNumber();
    
    public int randomNumberInRange(int startOfRange, int endOfRange);

    public RandomData randomData();
    
    public List<Integer> randomNumberList();
}

RandomServiceImpl.java
package com.lishman.random.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.springframework.stereotype.Service;

import com.lishman.random.web.RandomData;


@Service
public class RandomServiceImpl implements RandomService {

    public int randomNumber() {
        return new Random().nextInt();        
    }
    
    public int randomNumberInRange(int startOfRange, int endOfRange) {
        return new Random().nextInt(endOfRange - startOfRange) + startOfRange;        
    }

    public RandomData randomData() {  
        Random generator = new Random();      
        RandomData data = new RandomData();
        data.setBoolean(generator.nextBoolean());
        data.setDouble(generator.nextDouble());
        data.setInteger(generator.nextInt());   
        return data;        
    }
    
    public List<Integer> randomNumberList() {
        Random generator = new Random();        
        List<Integer> numbers = new ArrayList<Integer>(10);
        for (int i=0; i<10; i++) {
            numbers.add(generator.nextInt());
        }        
        return numbers;
    } 
    
}

RandomController.java
package com.lishman.random.web;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.lishman.random.service.RandomService;

@Controller
public class RandomController {
    
    @Autowired
    private RandomService random;

    @RequestMapping("/random.html")
    @ModelAttribute("randomNumber") public int randomNumber() {
        return random.randomNumber();        
    }
    
    @RequestMapping(value="/random.html", params={"start", "end"})
    public ModelAndView randomNumberInRange(@RequestParam("start") int startOfRange,
                                            @RequestParam("end") int endOfRange) {
        int result = random.randomNumberInRange(startOfRange, endOfRange);     
        return new ModelAndView("random", "randomNumber", result);
    }

    @RequestMapping("/random-data.html")
    @ModelAttribute public RandomData randomData() {    
        return random.randomData();        
    }
    
    @RequestMapping("/random-list.html")
    @ModelAttribute("randomNumbers") public List<Integer> randomNumberList() {  
        return random.randomNumberList();
    } 
}
RandomData.java
package com.lishman.random.web;

public class RandomData {
    
    public boolean randomBoolean;
    public int randomInteger;
    public double randomDouble;

    public boolean isBoolean() {
        return randomBoolean;
    }

    public void setBoolean(boolean randomBoolean) {
        this.randomBoolean = randomBoolean;
    }

    public int getInteger() {
        return randomInteger;
    }

    public void setInteger(int randomInteger) {
        this.randomInteger = randomInteger;
    }

    public double getDouble() {
        return randomDouble;
    }

    public void setDouble(double randomDouble) {
        this.randomDouble = randomDouble;
    }
    

}

random-data.jsp
<html>
  <body>
  
    <h1>Random Data</h1>
    
    <p>A random boolean is ${randomData.boolean}</p>
    <p>A random double is ${randomData.double}</p>
    <p>A random integer is ${randomData.integer}</p>
    
    <p><a href="../index.html">Back</a></p>
    
  </body>
</html> 

random-list.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  

<html>
  <body>
  
    <h1>Random Numbers</h1>
    <p>Here are 10 random numbers:</p>
    
    <c:forEach items="${randomNumbers}" var="randomNumber">
      <div>${randomNumber}</div>
    </c:forEach>
      
    <p><a href="../index.html">Back</a></p>

  </body>
</html> 

random.jsp
<html>
  <body>
  
    <h1>Random Number</h1>
    <p>A random number is ${randomNumber}</p>
    
    <p><a href="../index.html">Back</a></p>
    
  </body>
</html> 

random-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
           http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">

  <context:component-scan base-package="com.lishman.random.web"/>
  <context:component-scan base-package="com.lishman.random.service"/>
  
  <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver"
        p:prefix="/WEB-INF/jsp/"
        p:suffix=".jsp"/>
        
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         id="WebApp_ID"
         version="2.5">
  
  <display-name>Random</display-name>
  
  <servlet>
    <servlet-name>random</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>random</servlet-name>
    <url-pattern>/app/*</url-pattern>
  </servlet-mapping>
  
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
  
</web-app>
index.html
<html>
  <body>
  
    <h1>Randomizer</h1>
   
    <p>
      <a href="app/random.html">Random number</a><br/>
      
      <a href="app/random.html?start=1000&end=1040">Random number in range</a><br/> 
           
      <a href="app/random-data.html">Random data</a><br/>
      
      <a href="app/random-list.html">List of random numbers</a>
    </p>
 
  </body>
</html> 
server.log
INFO: Mapped URL path [/random.html] onto handler 'randomController'
INFO: Mapped URL path [/random-data.html] onto handler 'randomController'
INFO: Mapped URL path [/random-list.html] onto handler 'randomController'

Application Overview

Random is a simple application designed to demonstrate basic MVC functionality in Spring.
The user can request a single random numberrandom.html", a random number within a rangerandom.html?, different types of random datarandom-data or a list of random numbersrandom-list.
Results are displayed on one of three JSP pages, depending the type of data to be presented.

We use component scanningcomponent-scan to detect our services and controllers, and specify the location of the JSP files/WEB-INF/jsp/ to be used during view resolution.

Our controller responds to requests for random numbers using the RandomServiceRandomService:eq(1) implementation, which is injected into the controller during initialization.



Controller Details

The randomNumber()randomNumber:eq(1) method is triggered by a request to the /random.html/random.html:eq(0) URL path.

RandomServiceRandomService:eq(1) is used to produce a single random number which is added to the model as the randomNumberrandomNumber:eq(0) attribute.

No view name is specified by this method so DefaultRequestToViewNameTranslator is used to derive it from the URL/random.html:eq(0).
random.jsp displays the randomNumberp:lt(2) attribute from the model.
randomNumberInRangerandomNumberInRange:eq(0) is also associated with the /random.html/random.html:eq(1) path, but requests will only arrive at this method if the startstart:eq(0) and endend:eq(0) request parameters are present.
This method is executed by the second optionstart=1000 on the index.html page.
@RequestParam annotations set the startOfRange and endOfRange method parameters to the values in the start and end request parameters.

This time we use a ModelAndViewModelAndView:last object to return the view name and the model data.
randomDatarandomData:first returns an instance of the RandomData class which is bound to the model using a default name of randomData.
We can see how this objectp:lt(6) is accessed from the model on the random-data.jsp page.
A ListInteger of random numbers is added to the model by randomNumberListrandomNumberList:first.
random-list.jsp uses the standard JSTL forEach tag to display the results.
Home  |  Random  |  World  |  Questions & Answers  |   lishblog  |  Email Lishy