Create CSS styles easily.

There Many CSS style creators in the Internet. Form Generators, Button Generators etc. Because of the people who spent their precious time to create things like frameworks, we don’t need to spend our time reinventing the wheel.

Today I’m going to talk about http://enjoycss.com/.  The specialty of this site  is  you can add create a custom css for specially for a http element. In there site you can see What are the elements you can add css.

enjoy css elements

Above is some elements that you can use to add css into elements. Lets start over journey with a <input> tag. Select Input from the web site.

In the next step you will get below window.

screenshot-from-2016-11-10-13-53-28

On the left pane You can see live look of the elements, when Style are applied. The Right pane is where magic happen 😀 You can see Input box is already on the left pane.

On the right pane you can see style are divided into sub categories according to their scope. If you select the Text category you can see all kind of styles you want to add is there. If you try some changes you can see the input on the left changes accordingly. Not only text but also there are all most all styles like positioning, Shadows and borders etc.

So how to get the style to our application? Simply changes the element you want using the control and press  Get the Code Button on the Right below. Then you will get below the below window.

screenshot-from-2016-11-10-14-05-51

Then you can see the style you generated in a css class named enjoy-css. You just have to add it to your input ( or the element you want).

This site is a blessing when you had to generate your own styles. It is very easy. This save the developer from reinventing the wheel and fast developments.

Advertisements

Dynamic web content with HttpSession in jsp .

Most of the time when you create a web application you need to change you page content according to content in session. Today we discuss it for jsp but you can use it for Spring MVC too. (If you decided to use HttpSession in Spring MVC).

In This session we don’t discuss how we set session or  add attributes to the session ( http://stackoverflow.com/a/5766544/2940265 ).  For This we need to use jstl tags. You can read more about jstl tag if you complete new https://www.tutorialspoint.com/jsp/jsp_standard_tag_library.htm  You might face problem with integrating jstl with jsp. If such a case please refer this https://menukablog.wordpress.com/2016/05/10/add-jstl-tab-library-to-you-project-correctly/

Lets assume you have set a attribute in session as “username”.

If you want to show it on jsp you just have to do is add it anywhere in the jsp like below.

<p>${firstName}</p>

This will show in the browser as text. So you can use above one for links or whatever you want as text.

Now lets discuss how to change if a particular session is set or not. For that we use <c:if> tag https://www.tutorialspoint.com/jsp/jstl_core_if_tag.htm.  Check below code.

<c:if test=”${not empty username}”>
<%–If you want to print content from session–%>
<p>${firstName}</p>

<%–If you want to include html–%>
<%@include file=”/your/path/to/include/file.jsp” %>

<%–include only get wrong if you give the –%>
</c:if>
<c:if test=”${empty username}”>
<p>Username is empty</p>
</c:if>

 

As Syntax say First c;if tag check whether username is not empty. Then it show content middle of that. Of course <%@include file=”/your/path/to/include/file.jsp” %> is including another jsp to the file.

 

 

 

How to add .property file for Spring MVC project.

It is a best practice to not to include parameters in your source codes. It makes maintenance and development lot easier. Just imagine you are consuming a RESTful service and suddenly some urls changed? You will have to correct every single usage for that. It you put you parameter values in .property file, you just have to change one place. In the file only.

Let see how  we can add  .property file. First you have to create your config.property file. Since I using the Intellij Idea, I create config.property file under the resource folder like below.

property

I’m here going to use it for One of My controller. Now add some variables to test the .property file.

screenshot-from-2016-10-12-16-50-10

First You have to set the path of File

@PropertySource("classpath:config.properties")

Remember you give value for @PropertySource with classpath:config.properties . This will automatically take the config.property file in the resources folder. Now We have to assign values in the file to variables in the class. For that We use @Value annotations like below

@Value("${test}")
private String testProperty;

Check below code sample for complete coding. (Don’t confused with loggers and other Spring imports. you just have to look above mentioned codes only)

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@PropertySource("classpath:config.properties")
public class HomeController {

@Value("${test}")
private String testProperty;

final Logger logger = LoggerFactory.getLogger(HomeController.class);

@RequestMapping({"/", "/home"})
public String home() {
logger.info("Web Application Started");
logger.info(testProperty);
return "/home/self-care-home";
}

}

If I go to my logs folder and check it, I can see the below content (I check log files because in Spring web app you can’t see System.out.println() in you Ide terminal)

screenshot-from-2016-10-12-16-53-17

Configuring slf4j with log4j using log4j.xml

SLF4J is a simple facade for logging systems allowing the end-user to plug-in the desired logging system at deployment time. As The meaning of facade, it does not provide a complete logging solution. Operations such as configuring appenders or setting logging levels cannot be performed with SLF4J.

If you are completely beginner to logging frameworks above paragraph mean that, you can’t set  log levels, different error types in different files, log file creation with date etc like you can do it in log4j. refer this link for log4j http://logging.apache.org/log4j/2.x/manual/configuration.html

So if we can do them in log4j why we need slf4j? Because in log4j if we need to add parameter to log

LOG.debug("There are now " + count + " user accounts: " + userAccountList); // slow
LOG.debug("There are now {} user accounts: {}", count, userAccountList); // faster

Because String concatenate without string builder is more memory consuming than slf4j logging.

So Lets check How we add slf4j for log4j (You have to create you log4j.xml as mentioned in above link. I here consider you know how to use log4j. If you not it’s pretty easy you just have to read documentation and create log4j.xml as you want then (in Intellij) add it to the resources folder.)

For that you need three maven dependencies.

  • slf4j-api
  • log4j-core
  • log4j-slf4j-impl
<dependency>
 <groupId>org.slf4j</groupId>
 <artifactId>slf4j-api</artifactId>
 <version>1.7.21</version>
 </dependency>
 <dependency>
 <groupId>org.apache.logging.log4j</groupId>
 <artifactId>log4j-core</artifactId>
 <version>2.7</version>
 </dependency>
 <dependency>
 <groupId>org.apache.logging.log4j</groupId>
 <artifactId>log4j-slf4j-impl</artifactId>
 <version>2.1</version>
 </dependency>

Add above dependencies (or .jar ) to pom.xml.

Now run a test class to check integration is correct

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Random;

public class TestSL4J {

 final static Logger logger = LoggerFactory.getLogger(TestSL4J.class);

 public static void main(String[] args) {

 Random randomGenerator = new Random();
 int randomInt = randomGenerator.nextInt(100);
 logger.info("Temperature set to {}. Old temperature was {}.", randomGenerator.nextInt(100), randomGenerator.nextInt(100));
 }
}

If you gets integers where the {} should be then you have correctly integrated the slf4j for log4j

Screen Recording with recordMyDesktop in Ubuntu

One of these days you might need to record your desktop in Ubuntu. Today we are going to record the screen in Ubuntu.

We are going to use recordMyDesktop application. First of all install it using below link.

https://apps.ubuntu.com/cat/applications/gtk-recordmydesktop/

Click Available of Software Center to install it. You will get below dialog box

exter

Click Launch Application. Then press Install. After finishing install you can run application either using terminal command

gtk-recordmydesktop

or clicking below icon of side pane of Ubuntu

icon

Now we will get the below window window

dilap

Before we start Screen recording we need few basic configurations to set. First one is to set where to set the saved screen recorded video. To do that press Save As in the window and browse where you need to save the videos.This is the window you get when you click on save as button on recordmydesktop application

Give appropriate name for your video. This name will use to Recorded videos which comes after unless you change it( name 1, name 2, name 3 …)

Basically Now we are good to go. But before that let me explain about the Select Window button. This is Useful when you want to record part of window, like a dialog box. Generally recordMyDesktop will record the full screen. If you want part of window select Select Window button and select the dialog box you want to record.

Now you are good to go. Just click the Record button. Then do the what you want to record. Now lets check how to generate the recorded video.

If you look top task ban of Ubuntu, you can see there is a Red Square button on left of it.

reording

When you want to stop the recording and get the video press that red square button (Stop Button). Then you will get below window.

ebn

Wait till window automatically get close. Then check the place you set to save the video. There you can see your video.

Spring 4 MVC configuring view with controller with java configurations

If you are new to Spring MVC, configuring views with controllers is the first step you have to take into Spring world. There are few ways to configure views, such as xml based, spring boot etc. But today we are going to discuss using java configurations.

As usually we use maven web arch type as our template. ( if you don’t know about maven web arch type template, don’t worry it’s template structure nothing serious.). So if you have installed maven (apt-cache search maven

sudo apt-get install maven)

Then run below command to generate template (FirstDay)

mvn archetype:generate -DgroupId=menuka.hsenid -DartifactId=FirstDay -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

Now open project on Intellij ( or your IDE).

Now we have to add dependencies to the project. Since this is just to we just add spring-webmvc to enable Spring MVC (when you add Spring MVC dependency you don’t need to add basic spring dependency like spring-core, spring-context etc. They automatically added to the project ) and javax.servlet-api to handle servlets.

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>

(I hope you know where to put dependencies, if not, in pom.xml file, within < dependencies> tags)

Just one more step before starting development. We have to declare where our source code reside. Create a folder name java inside main folder. Then File -> Project Structure -> Modules  then select the java folder under Sources tab. Now click Sources button under the Sources tab. Then Apply and Ok. 

Now we need to create to packages one for configuration, other one for Controllers.

I use below two packages hsenid.config and hsenid.web

In config package I use Below three classes

WebConfig


package hsenid.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan("hsenid.web")
public class WebConfig extends WebMvcConfigurerAdapter {
@Bean
public ViewResolver viewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/pages/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}

@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer){
configurer.enable();
}

@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}

There are several things this class do.

One is addResourceHandlers  method set resource path. Because you can’t use paths like you use them in html. Here we use resources folder (which is under webapp folder ) so you can add your images, js, css etc, files under here. (one thin you must remember is when you referring some file in a jsp you must use webapp folder as root folder. )

Other one is resolving jsp page names using viewResolver. Here we declare if we use a url home it is really name is”/WEB-INF/pages/home.jsp”.  Lets create  other two classes

RootConfig


package hsenid.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@ComponentScan(basePackages={"hsenid"},
excludeFilters={
@Filter(type= FilterType.ANNOTATION, value=EnableWebMvc.class)
})
public class RootConfig {
}

Here you must add you base package name for basePackages variable.

WebAppInitializer

package hsenid.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
 @Override
 protected String[] getServletMappings(){
 return new String[]{"/"};
 }

 @Override
 protected Class<?>[] getRootConfigClasses(){
 return new Class<?>[]{RootConfig.class};
 }

 @Override
 protected Class<?>[] getServletConfigClasses(){
 return new Class<?>[]{WebConfig.class};
 }

}

Now we are configurations are good to go.

Now we have to create view jsp for connect with controllers.

create below jsp pages in the pages folder in the WEB-INF folder (Because this is the path we set in the configurations).

home.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Home</title>
</head>
<body>
This is home
</body>
</html>

test.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
 <title>Test</title>
</head>
<body>
This is test
</body>
</html>

So lets create a controller in hsenid.web folder.

HomeController


package hsenid.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller

public class HomeController {

@RequestMapping("/")
public String home() {
return "home";
}

@RequestMapping("test")
public String test()
{
return "test";
}
}

Now run mvn clean install in terminal (in the location where the pom.xml is) to generate the war file and put the war File in the tomcat webapp folder.

As you can see in the controller, http://localhost:8080/FirstDay/ url is connected with home.jsp and http://localhost:8080/FirstDay/test url is connected with test.jsp.

Well this is simple tutorial to get start with MVC

 

How to center a div tag without using deprecated center tag.

Life was easy when there is <center> tag to center things for us. But now it’s deprecated. (Of course you can use it lazy, but it’s not recommended to use deprecated tags to your web pages. )  But if you search for alternative for deprecated center tag frequently come text-align : center  As you might already experienced this doesn’t go well with div’s (which might force you to use deprecated center tags) which contents other than text, such as tables.

So how you we center a div?

That’s what we going to learn today. This method need two div for this operation. One div is to apply a css and other div (with your content inside such as table) to apply inline css so first lets check the css.

.youroutercss{
position: absolute; left: 50%;
}

Now you css ready lets see next step. You have add inline css style=”position: relative; left: -50%;”  like below.

 

code

It is must to be two div tags as above. Now you can see the table is being center of the page.