Wednesday, June 18, 2008

Convert Date object to Mysql Date Format


public static String toMysqlDateStr(Date date){
if (date==null) return "NULL";
SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sqlValueWithQuotas(sdf.format(date));
}

public static String sqlValueWithQuotas(Object obj){
if ( obj == null ) return "NULL";

String str = obj.toString();
str.replaceAll("'", "\\'");
str = '\''+str+'\'';

return str;

}

Saturday, June 14, 2008

JSP Sessions Example

Sessions are started automatically in JSP pages.
You can access current session by prebuilt session object.

Create sessions.jsp file on your Tomcat's webapps/ROOT directory :


<%@page import="java.util.Date"%>
<%
out.print("Session Creation Time:" + new Date(session.getCreationTime()));
out.print("<BR>");
out.print("Last accessed Time:" + new Date(session.getLastAccessedTime()));
out.print("<BR>");
out.print("Session ID:"+session.getId());
%>


and launch it (for example http://localhost:8080/sessions.jsp)

it prints:

Session Creation Time:Sat Jun 14 19:28:06 EEST 2008
Last accessed Time:Sat Jun 14 19:33:34 EEST 2008
Session ID:365A3F239D1E54FD43EA0F7CBA1931EF

Now we are able to access the session. We can store objects in session objects.
This can help share objects between JSP pages.

Sessions are widely used for authentication purposes.

For example , let this be index.jsp as default page :


<%
String userName = request.getParameter("userName");
String password = request.getParameter("password");
if ("admin".equals(userName) && "adminpass".equals(password) ) { //Session start
session.setAttribute("userName",userName);
session.setAttribute("role","admin");
response.sendRedirect("/main.jsp");
}
else out.print("Logon failed");
%>
<form action="index.jsp" method="post">
Enter Username: <input name="userName"> <br>
Enter Password: <input name="password"> <br>
<input type="submit">
</form>


The sample code above get username and password from user. If username and password are ok , username and role objects are stored in session and redirects to main.jsp otherwise sends an http error.

And in main.jsp we authenticate user based on username and role :


<%
String userName = session.getAttribute("userName");
String role = session.getAttribute("role");
if ( userName == null || ! "admin".equals(role) ) {
response.sendError(403,"You are not authorized to view this page");
return;
}
%>

This authentication part can be a seperate jsp and included in every page that needs authentication. Ideally , username , password and role lookup should be from database or from a directory service like LDAP or Active Directory.

Technorati Profile

Monday, June 9, 2008

Simple JSP Tutorial

This jsp accepts a number from an html form and prints squareroot of that number on the same page. Paste this code to file "first.jsp" and move it to tomcat's webapps/ROOT directory. Start tomcat and browse to localhost:8080/first.jsp. We put java code in <% %> block , other parts are standart html. <%=variable %> prints variable into html code just like <%out.print(variable);%> does.

request , response and out objects are standart JSP objects that can be used to access http request and response.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Sample JSP</title>
</head>
<body>
<%
String strNumber= request.getParameter("number");
double mySqrt = 0.0;
if ( strNumber == null )
strNumber = "";
else {
double dNumber = Double.parseDouble(strNumber);
mySqrt = Math.sqrt(dNumber);
}
%>

<form action="first.jsp" method="post">
Enter Number: <input type="text" name="number" value="<%=strNumber%>">
<input type="submit">
<br><br>
The Sqrt is <%out.print(mySqrt);%>
</body>
</html>