link for servlet 3.0 annotations
------------------------------------------
Servlet 3.0 (lab sheet)
-------------------------------
topics
-------------------------------
Hello World
servlet life cycle (counter)
Servlet 3.0 annotations
JDBC programming
Dispatching VS redirecting
ServletContext vs. ServletConfig
Attributes
Servlet chaining
MVC
Connection pooling
Listner
filter
0. Hello World
1. Simple form
2. configure username / password for tomcat
3. Print client information
4. Demostration of servlet life cycle
5. ServletContext vs. ServletConfig
6. Servlet 3.0 annotations
7. Asynch processing
8. creating customer form and Printing customer information
9. Storing book info in database
10. Dispatching VS redirecting
11. Attributes
12. MVC
13. Storing book info in database using connection pooling
Lab solutions Hints
--------------------
3. Print client information
------------------------------
// Get client's IP address
String ipAddress = request.getRemoteAddr(); // ip
// Get client's hostname
String hostname = request.getRemoteHost(); // hostname
4. Demostration of servlet life cycle
override init() and destroy()
Accepting i/p form checkboxes /multiple select boxes
--------------------------------------------------
==> Use HttpServletRequest.getParameterValues() method
Ex;
<td><input name="options" type="checkbox" value="option1" />
<td><input name="options" type="checkbox" value="option2" />
<td><input name="options" type="checkbox" value="option3" />
In servlet:
String[] selectedOptions = request.getParameterValues("options");
if (selectedOptions != null)
{
for (String option : selectedOptions)
{
printWriter.print(option+"<br/>");
}
}
5. ServletContext vs. ServletConfig
----------------------------------------
ServletContext:
per applications
ServletConfig:
per servlet
Annotations supports (3.0)
-----------------------------
@WebServlet annotation
-----------------------------
Ex:
@WebServlet(urlPatterns = {"/simpleservlet"})
public class SimpleServlet extends HttpServlet
{
........
.......
}
@WebServlet(urlPatterns = {"/simpleservlet", "*.foo"})
Passing initialization parameters to a servlet via annotations
@WebServlet(name = "InitParamsServlet", urlPatterns = {
"/InitParamsServlet"}, initParams = {
@WebInitParam(name = "param1", value = "value1"),
@WebInitParam(name = "param2", value = "value2")})
8. creating customer form and Printing customer information
step 1:
create form:
--------------
<form action="addCustomer.do" method="POST">
Customer ID : <input name="id" /> <br>
Name: <input name="name" /> <br>
Address: <textarea name="addr" rows="4" cols="20"></textarea> <br>
Mobile: <input name="mobile" size="9" /> <br>
Fax: <input name="fax" size="9" /> <br>
E-mail: <input name="email" size="25" /> <br><br>
<input type="submit" value="Add" />
</form>
create servlet to process form:
-------------------------------
.....
......
//retrive info
String id = request.getParameter("id");
String name = request.getParameter("name");
String addr = request.getParameter("addr");
String mobile = request.getParameter("mobile");
String fax = request.getParameter("fax");
String email = request.getParameter("email");
//Display customer informations
out.println("<h1> Customer Information </h1>");
out.println("<b>ID: </b>" + id + "<BR>");
out.println("<b>Name: </b>" + name + "<BR>");
out.println("<b>Address: </b>" + addr + "<BR>");
out.println("<b>Mobile: </b>" + mobile + "<BR>");
out.println("<b>Fax: </b>" + fax + "<BR>");
out.println("<b>E-mail: </b>" + email + "<BR>");
do Yuself:Storing customer info in database
Demo of JDBC
--------------
best practices
-------------------------
Step 1: Add jdbc driver jar to project
Step 2: create mysql table book
CREATE TABLE MYBOOKS1 (ISBN VARCHAR(20) NOT NULL ,TITLE VARCHAR(70) NULL ,AUTHOR VARCHAR(50) NULL ,PRICE FLOAT NULL ,PRIMARY KEY (ISBN) );
populate some records
INSERT INTO mybooks1 VALUES ('123', 'JAVA', 'Rajeev', 250.00);
INSERT INTO mybooks1 VALUES ('456', 'Servlet JSP', 'Rajeev ', 300.00) ;
Step 3:
Add jar to tomcat lib folder
Step 4:
create an form
<form action="addBook.do" method="POST">
ISBN : <input type="text" name="isbn" value="" size="15"/> <BR>
Title : <input type="text" name="title" value="" size="50"/> <BR>
Author : <input type="text" name="author" value="" size="50"/> <BR>
Price : <input type="text" name="price" value="" size="10"/> <BR>
<input type="submit" value="Add" />
</form>
Step 5:
create processing servlet:
i) load the driver in init() method and create an con object
con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/raj","root","root");
ii) put insertion code inside doPost()
String isbn = request.getParameter("isbn");
String author = request.getParameter("author");
String title = request.getParameter("title");
String priceStr = request.getParameter("price");
pstmt=con.prepareStatement("insert into books(isbn, author, title, price)values (?,?,?,?)");
pstmt.setString(1, isbn);
pstmt.setString(2, author);
pstmt.setString(3, title);
pstmt.setFloat(4, price);
pstmt.executeUpdate();
7. Dispatching VS redirecting
Login application
9. Attributes
10. MVC
Application 1: Calculator application
form:
<form action="Cal.do" method="post">
Enter first No : <input type="text" name="numberA"/><br/>
Enter second No:<input type="text" name="numberB"/><br/><br/>
<input type="submit"/>
</form>
Application 2: Book Advice Application
Step 1:
create view:
---------------
create form:
<html><body>
<h1 align="center">Book Selection Page</h1>
<form action="SelectBook" method="post">
Select book <p>
Book:
<select name="topic" size="1">
<option value="Java">Java</option>
<option value="Servlet">Servlet</option>
<option value="Struts">Struts</option>
</select>
<br><br>
<center>
<input type="submit">
</center>
</form>
</body>
</html>
Create controller
---------------------
String topic=request.getParameter("topic");
List<String>choices=BookAdviser.bookAdviser(topic);
request.setAttribute("booklist", choices);
RequestDispatcher rd=request.getRequestDispatcher("show2.jsp");
rd.forward(request, response);
create model
-----------------
public class BookAdviser {
public static List<String> bookAdviser(String topic){
List<String>list=new ArrayList<String>();
if(topic.equalsIgnoreCase("Java")){
list.add("head first");
list.add("thinking in java");
}else if(topic.equalsIgnoreCase("Servlet")){
list.add("head first servlet jsp");
list.add("core servlet.com");
}else if(topic.equalsIgnoreCase("Struts")){
list.add("struts2 in action");
list.add("black book");
}else
list.add("no book");
return list;
}
}
create display.jsp
---------------------
<%
List<String>list=(List<String>)request.getAttribute("key");
Iterator it=list.iterator();
while(it.hasNext()){
out.print(it.next()+"</br>");
}
%>
better view
------------
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:forEach var="book" items="${booklist}">
<b> ${book} </b><br/>
</c:forEach>
11. Storing book info in database using connection pooling
------------------------------------------------------------------
1. set JAVA_HOME
2. first u need to make a tomcat user
add to tomcat-user.xml in conf folder of tomcat installation
3. paste it
<role rolename="manager"/>
<user username="admin" password="admin" roles="manager"/>
Step 1;
mapping in context.xml
<Resource
name="jdbc/test"
auth="Container"
driverClassName="com.mysql.jdbc.Driver"
type="javax.sql.DataSource"
url="jdbc:mysql://localhost:3306/exp121"
username="root"
password="root" >
</Resource>
Step 2:
mapping in web.xml
----------------------
<resource-ref>
<description>Test Database</description>
<res-ref-name>jdbc/test</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
Step 3:
-------
@Resource(name="jdbc/test")
private DataSource ds;
private Connection conn;
conn = ds.getConnection();
then use connection object as usual;
http://tomcat.apache.org/tomcat-6.0-doc/jndi-datasource-examples-howto.html
Session Mgt: HttpSession
-------------------------------------------
HttpSession object
--------------------
simple program to check session...
HttpSession session=request.getSession();
String heading="hello";
synchronized (session) {
Integer count=(Integer)session.getAttribute("sessioncount");
if (count==null)
{
count=0;
session.setAttribute("sessioncount", count);
heading="welcome back first time user";
}
else
{
count=count+1;
session.setAttribute("sessioncount", count);
heading="welcome back "+count;
}
}
PrintWriter out=response.getWriter();
out.print(heading);
login/ logout
------------
using httpsession
Url rewriting
------------------------
// Encodes the specified URL by including the session ID in it,
// or, if encoding is not needed, returns the URL unchanged
String newURL = response.encodeURL("GetSession");
// Return a <a> tag with the new url
writer.println("Click <a href=\"" + newURL + "\">here</a> for another servlet");
------------------------------------------
Servlet 3.0 (lab sheet)
-------------------------------
topics
-------------------------------
Hello World
servlet life cycle (counter)
Servlet 3.0 annotations
JDBC programming
Dispatching VS redirecting
ServletContext vs. ServletConfig
Attributes
Servlet chaining
MVC
Connection pooling
Listner
filter
0. Hello World
1. Simple form
2. configure username / password for tomcat
3. Print client information
4. Demostration of servlet life cycle
5. ServletContext vs. ServletConfig
6. Servlet 3.0 annotations
7. Asynch processing
8. creating customer form and Printing customer information
9. Storing book info in database
10. Dispatching VS redirecting
11. Attributes
12. MVC
13. Storing book info in database using connection pooling
Lab solutions Hints
--------------------
3. Print client information
------------------------------
// Get client's IP address
String ipAddress = request.getRemoteAddr(); // ip
// Get client's hostname
String hostname = request.getRemoteHost(); // hostname
4. Demostration of servlet life cycle
override init() and destroy()
Accepting i/p form checkboxes /multiple select boxes
--------------------------------------------------
==> Use HttpServletRequest.getParameterValues() method
Ex;
<td><input name="options" type="checkbox" value="option1" />
<td><input name="options" type="checkbox" value="option2" />
<td><input name="options" type="checkbox" value="option3" />
In servlet:
String[] selectedOptions = request.getParameterValues("options");
if (selectedOptions != null)
{
for (String option : selectedOptions)
{
printWriter.print(option+"<br/>");
}
}
5. ServletContext vs. ServletConfig
----------------------------------------
ServletContext:
per applications
ServletConfig:
per servlet
Annotations supports (3.0)
-----------------------------
@WebServlet annotation
-----------------------------
Ex:
@WebServlet(urlPatterns = {"/simpleservlet"})
public class SimpleServlet extends HttpServlet
{
........
.......
}
@WebServlet(urlPatterns = {"/simpleservlet", "*.foo"})
Passing initialization parameters to a servlet via annotations
@WebServlet(name = "InitParamsServlet", urlPatterns = {
"/InitParamsServlet"}, initParams = {
@WebInitParam(name = "param1", value = "value1"),
@WebInitParam(name = "param2", value = "value2")})
8. creating customer form and Printing customer information
step 1:
create form:
--------------
<form action="addCustomer.do" method="POST">
Customer ID : <input name="id" /> <br>
Name: <input name="name" /> <br>
Address: <textarea name="addr" rows="4" cols="20"></textarea> <br>
Mobile: <input name="mobile" size="9" /> <br>
Fax: <input name="fax" size="9" /> <br>
E-mail: <input name="email" size="25" /> <br><br>
<input type="submit" value="Add" />
</form>
create servlet to process form:
-------------------------------
.....
......
//retrive info
String id = request.getParameter("id");
String name = request.getParameter("name");
String addr = request.getParameter("addr");
String mobile = request.getParameter("mobile");
String fax = request.getParameter("fax");
String email = request.getParameter("email");
//Display customer informations
out.println("<h1> Customer Information </h1>");
out.println("<b>ID: </b>" + id + "<BR>");
out.println("<b>Name: </b>" + name + "<BR>");
out.println("<b>Address: </b>" + addr + "<BR>");
out.println("<b>Mobile: </b>" + mobile + "<BR>");
out.println("<b>Fax: </b>" + fax + "<BR>");
out.println("<b>E-mail: </b>" + email + "<BR>");
do Yuself:Storing customer info in database
Demo of JDBC
--------------
best practices
-------------------------
Step 1: Add jdbc driver jar to project
Step 2: create mysql table book
CREATE TABLE MYBOOKS1 (ISBN VARCHAR(20) NOT NULL ,TITLE VARCHAR(70) NULL ,AUTHOR VARCHAR(50) NULL ,PRICE FLOAT NULL ,PRIMARY KEY (ISBN) );
populate some records
INSERT INTO mybooks1 VALUES ('123', 'JAVA', 'Rajeev', 250.00);
INSERT INTO mybooks1 VALUES ('456', 'Servlet JSP', 'Rajeev ', 300.00) ;
Step 3:
Add jar to tomcat lib folder
Step 4:
create an form
<form action="addBook.do" method="POST">
ISBN : <input type="text" name="isbn" value="" size="15"/> <BR>
Title : <input type="text" name="title" value="" size="50"/> <BR>
Author : <input type="text" name="author" value="" size="50"/> <BR>
Price : <input type="text" name="price" value="" size="10"/> <BR>
<input type="submit" value="Add" />
</form>
Step 5:
create processing servlet:
i) load the driver in init() method and create an con object
con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/raj","root","root");
ii) put insertion code inside doPost()
String isbn = request.getParameter("isbn");
String author = request.getParameter("author");
String title = request.getParameter("title");
String priceStr = request.getParameter("price");
pstmt=con.prepareStatement("insert into books(isbn, author, title, price)values (?,?,?,?)");
pstmt.setString(1, isbn);
pstmt.setString(2, author);
pstmt.setString(3, title);
pstmt.setFloat(4, price);
pstmt.executeUpdate();
7. Dispatching VS redirecting
Login application
9. Attributes
10. MVC
Application 1: Calculator application
form:
<form action="Cal.do" method="post">
Enter first No : <input type="text" name="numberA"/><br/>
Enter second No:<input type="text" name="numberB"/><br/><br/>
<input type="submit"/>
</form>
Application 2: Book Advice Application
Step 1:
create view:
---------------
create form:
<html><body>
<h1 align="center">Book Selection Page</h1>
<form action="SelectBook" method="post">
Select book <p>
Book:
<select name="topic" size="1">
<option value="Java">Java</option>
<option value="Servlet">Servlet</option>
<option value="Struts">Struts</option>
</select>
<br><br>
<center>
<input type="submit">
</center>
</form>
</body>
</html>
Create controller
---------------------
String topic=request.getParameter("topic");
List<String>choices=BookAdviser.bookAdviser(topic);
request.setAttribute("booklist", choices);
RequestDispatcher rd=request.getRequestDispatcher("show2.jsp");
rd.forward(request, response);
create model
-----------------
public class BookAdviser {
public static List<String> bookAdviser(String topic){
List<String>list=new ArrayList<String>();
if(topic.equalsIgnoreCase("Java")){
list.add("head first");
list.add("thinking in java");
}else if(topic.equalsIgnoreCase("Servlet")){
list.add("head first servlet jsp");
list.add("core servlet.com");
}else if(topic.equalsIgnoreCase("Struts")){
list.add("struts2 in action");
list.add("black book");
}else
list.add("no book");
return list;
}
}
create display.jsp
---------------------
<%
List<String>list=(List<String>)request.getAttribute("key");
Iterator it=list.iterator();
while(it.hasNext()){
out.print(it.next()+"</br>");
}
%>
better view
------------
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:forEach var="book" items="${booklist}">
<b> ${book} </b><br/>
</c:forEach>
11. Storing book info in database using connection pooling
------------------------------------------------------------------
1. set JAVA_HOME
2. first u need to make a tomcat user
add to tomcat-user.xml in conf folder of tomcat installation
3. paste it
<role rolename="manager"/>
<user username="admin" password="admin" roles="manager"/>
Step 1;
mapping in context.xml
<Resource
name="jdbc/test"
auth="Container"
driverClassName="com.mysql.jdbc.Driver"
type="javax.sql.DataSource"
url="jdbc:mysql://localhost:3306/exp121"
username="root"
password="root" >
</Resource>
Step 2:
mapping in web.xml
----------------------
<resource-ref>
<description>Test Database</description>
<res-ref-name>jdbc/test</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
Step 3:
-------
@Resource(name="jdbc/test")
private DataSource ds;
private Connection conn;
conn = ds.getConnection();
then use connection object as usual;
http://tomcat.apache.org/tomcat-6.0-doc/jndi-datasource-examples-howto.html
Session Mgt: HttpSession
-------------------------------------------
HttpSession object
--------------------
simple program to check session...
HttpSession session=request.getSession();
String heading="hello";
synchronized (session) {
Integer count=(Integer)session.getAttribute("sessioncount");
if (count==null)
{
count=0;
session.setAttribute("sessioncount", count);
heading="welcome back first time user";
}
else
{
count=count+1;
session.setAttribute("sessioncount", count);
heading="welcome back "+count;
}
}
PrintWriter out=response.getWriter();
out.print(heading);
login/ logout
------------
using httpsession
Url rewriting
------------------------
// Encodes the specified URL by including the session ID in it,
// or, if encoding is not needed, returns the URL unchanged
String newURL = response.encodeURL("GetSession");
// Return a <a> tag with the new url
writer.println("Click <a href=\"" + newURL + "\">here</a> for another servlet");
No comments:
Post a Comment