SHARE
TWEET

web

a guest Apr 27th, 2016 37 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 9. Session Handling using cookies
  2. index.html
  3. <form method="post" action=" validate ">
  4. Name:<input type="text" name="user" /><br/>
  5. Password:<input type="text" name="pass" ><br/>
  6. <input type="submit" value="submit">
  7. </form>
  8. web.xml
  9. <webapp...>
  10. <servlet>
  11. <servletname>
  12. validate </servletname>
  13. <servletclass>
  14. MyServlet </servletclass>
  15. </servlet>
  16. <servletmapping>
  17. <servletname>
  18. validate </servletname>
  19. <urlpattern>/
  20. validate</urlpattern>
  21. </servletmapping>
  22. <servlet>
  23. <servletname>
  24. First </servletname>
  25. <servletclass>
  26. First </servletclass>
  27. </servlet>
  28. <servletmapping>
  29. <servletname>
  30. First </servletname>
  31. <urlpattern>/
  32. First</urlpattern>
  33. </servletmapping>
  34. <welcomefilelist>
  35. <welcomefile>
  36. index.html </welcomefile>
  37. </welcomefilelist>
  38. </webapp>
  39. MyServlet.java
  40. import java.io.*;
  41. import javax.servlet.*;
  42. import javax.servlet.http.*;
  43. public class MyServlet extends HttpServlet {
  44. protected void doPost (HttpServletRequest request, HttpServletResponse response)
  45. throws ServletException, IOException {
  46. response.setContentType("text/html;charset=UTF8");
  47. String name = request.getParameter(" user ");
  48. String pass = request.getParameter(" pass ");
  49. if(pass. equals ("1234"))
  50. {
  51. Cookie ck = new Cookie(" username ", name );
  52. response. addCookie ( ck );
  53. response.sendRedirect(" First ");
  54. }
  55. }
  56. }
  57. First.java
  58. import java.io.*;
  59. import javax.servlet.*;
  60. import javax.servlet.http.*;
  61. public class First extends HttpServlet {
  62. protected void doGet (HttpServletRequest request, HttpServletResponse response)
  63. throws ServletException, IOException {
  64. response.setContentType("text/html;charset=UTF8");
  65. PrintWriter out = response.getWriter();
  66. Cookie[] cks = request.getCookies();
  67. out.println("Welcome "+ cks[0].getValue() );
  68. }
  69. }
  70. 10.
  71. Session Hndling using URL Rewriting
  72. index.html
  73. <form method="post" action=" validate ">
  74. Name:<input type="text" name="user" /><br/>
  75. Password:<input type="text" name="pass" ><br/>
  76. <input type="submit" value="submit">
  77. </form>
  78. web.xml
  79. <webapp...>
  80. <servlet>
  81. <servletname>
  82. validate </servletname>
  83. <servletclass>
  84. MyServlet </servletclass>
  85. </servlet>
  86. <servletmapping>
  87. <servletname>
  88. validate </servletname>
  89. <urlpattern>/
  90. validate</urlpattern>
  91. </servletmapping>
  92. <servlet>
  93. <servletname>
  94. First </servletname>
  95. <servletclass>
  96. First </servletclass>
  97. </servlet>
  98. <servletmapping>
  99. <servletname>
  100. First </servletname>
  101. <urlpattern>/
  102. First</urlpattern>
  103. </servletmapping>
  104. <welcomefilelist>
  105. <welcomefile>
  106. index.html </welcomefile>
  107. </welcomefilelist>
  108. </webapp>
  109. MyServlet.java
  110. import java.io.*;
  111. import javax.servlet.*;
  112. import javax.servlet.http.*;
  113. public class MyServlet extends HttpServlet {
  114. protected void doPost (HttpServletRequest request, HttpServletResponse response)
  115. throws ServletException, IOException {
  116. response.setContentType("text/html;charset=UTF8");
  117. String name = request.getParameter(" user ");
  118. String pass = request.getParameter(" pass ");
  119. if(pass. equals ("1234"))
  120. {
  121. response.sendRedirect( "First?user_name="+ name +"" );
  122. }
  123. }
  124. }
  125. First.java
  126. import java.io.*;
  127. import javax.servlet.*;
  128. import javax.servlet.http.*;
  129. public class First extends HttpServlet {
  130. protected void doGet (HttpServletRequest request, HttpServletResponse response)
  131. throws ServletException, IOException {
  132. response.setContentType("text/html;charset=UTF8");
  133. PrintWriter out = response.getWriter();
  134. String user = request.getParameter(" user_name ");
  135. out.println("Welcome "+user);
  136. }
  137. }
  138. 11. Session management using hidden form fields :
  139. index.html
  140. <form method="post" action=" validate ">
  141. Name:<input type="text" name="user" /><br/>
  142. Password:<input type="text" name="pass" ><br/>
  143. <input type="submit" value="submit">
  144. </form>
  145. web.xml
  146. <webapp...>
  147. <servlet>
  148. <servletname>
  149. First </servletname>
  150. <servletclass>
  151. First </servletclass>
  152. </servlet>
  153. <servletmapping>
  154. <servletname>
  155. First </servletname>
  156. <urlpattern>/
  157. First</urlpattern>
  158. </servletmapping>
  159. <servlet>
  160. <servletname>
  161. Second </servletname>
  162. <servletclass>
  163. Second </servletclass>
  164. </servlet>
  165. <servletmapping>
  166. <servletname>
  167. Second </servletname>
  168. <urlpattern>/
  169. Second</urlpattern>
  170. </servletmapping>
  171. <welcomefilelist>
  172. <welcomefile>
  173. index.html </welcomefile>
  174. </welcomefilelist>
  175. </webapp>
  176. First.java
  177. import java.io.*;
  178. import javax.servlet.*;
  179. import javax.servlet.http.*;
  180. public class First extends HttpServlet {
  181. protected void doPost (HttpServletRequest request, HttpServletResponse response)
  182. throws ServletException, IOException {
  183. response.setContentType("text/html;charset=UTF8");
  184. PrintWriter out = response.getWriter();
  185. //getting value submitted in form from HTML file
  186. String user = request.getParameter("user");
  187. //creating a new hidden form field
  188. out.println("<form action='Second'>");
  189. out.println("<input type='hidden' name='user' value='"+ user +"'>");
  190. out.println("<input type='submit' value='submit' >");
  191. out.println("</form>");
  192. }
  193. }
  194. Second.java
  195. import java.io.*;
  196. import javax.servlet.*;
  197. import javax.servlet.http.*;
  198. public class Second extends HttpServlet {
  199. protected void doGet (HttpServletRequest request, HttpServletResponse response)
  200. throws ServletException, IOException {
  201. response.setContentType("text/html;charset=UTF8");
  202. PrintWriter out = response.getWriter();
  203. //getting parameter from the hidden field
  204. String user = request.getParameter(" user ");
  205. out.println("Welcome "+ user );
  206. }
  207. }
  208. HTTP Session
  209. 12. http://www.studytonight.com/servlet/httpsession.php
  210. index.html
  211. <form method="post" action=" Validate ">
  212. User: <input type="text" name="user" /><br/>
  213. Password: <input type="text" name="pass" ><br/>
  214. <input type="submit" value="submit">
  215. </form>
  216. web.xml
  217. <webapp..>
  218. <servlet>
  219. <servletname>
  220. Validate </servletname>
  221. <servletclass>
  222. Validate </servletclass>
  223. </servlet>
  224. <servlet>
  225. <servletname>
  226. Welcome </servletname>
  227. <servletclass>
  228. Welcome </servletclass>
  229. </servlet>
  230. <servletmapping>
  231. <servletname>
  232. Validate</servletname>
  233. <urlpattern>/
  234. Validate</urlpattern>
  235. </servletmapping>
  236. <servletmapping>
  237. <servletname>
  238. Welcome</servletname>
  239. <urlpattern>/
  240. Welcome</urlpattern>
  241. </servletmapping>
  242. <welcomefilelist>
  243. <welcomefile>
  244. index.html </welcomefile>
  245. </welcomefilelist>
  246. </webapp>
  247. Validate.java
  248. import java.io.*;
  249. import javax.servlet.*;
  250. import javax.servlet.http.*;
  251. public class Validate extends HttpServlet {
  252. protected void doPost (HttpServletRequest request, HttpServletResponse
  253. response)
  254. throws ServletException, IOException {
  255. response.setContentType("text/html;charset=UTF8");
  256. String name = request.getParameter("user");
  257. String pass = request.getParameter("pass");
  258. if(pass. equals ("1234"))
  259. {
  260. //creating a session
  261. HttpSession session = request.getSession();
  262. session. setAttribute (" user ", name );
  263. response. sendRedirect ("Welcome");
  264. }
  265. }
  266. }
  267. Welcome.java
  268. import java.io.*;
  269. import javax.servlet.*;
  270. import javax.servlet.http.*;
  271. public class Welcome extends HttpServlet {
  272. protected void doGet (HttpServletRequest request, HttpServletResponse
  273. response)
  274. throws ServletException, IOException {
  275. response.setContentType("text/html;charset=UTF8");
  276. PrintWriter out = response.getWriter();
  277. HttpSession session = request.getSession();
  278. String user = (String)session.getAttribute(" user ");
  279. out.println("Hello "+ user );
  280. }
  281. }
  282. 13. Servelet Collaboration REquest
  283. dispatch
  284. http://www.javatpoint.com/requestdispatcherinservlet
  285. index.html
  286. <form action= "servlet1" method= "post" >
  287. Name:<input type= "text" name= "userName" /><br/>
  288. Password:<input type= "password" name= "userPass" /><br/>
  289. <input type= "submit" value= "login" />
  290. </form>
  291. Login.java
  292. import java.io.*;
  293. import javax.servlet.*;
  294. import javax.servlet.http.*;
  295. public class Login extends HttpServlet {
  296. public void doPost(HttpServletRequest request, HttpServletResponse response)
  297. throws ServletException, IOException {
  298. response.setContentType( "text/html" );
  299. PrintWriter out = response.getWriter();
  300. String n=request.getParameter( "userName" );
  301. String p=request.getParameter( "userPass" );
  302. if (p.equals( "servlet" ){
  303. RequestDispatcher rd=request.getRequestDispatcher( "servlet2" );
  304. rd.forward(request, response);
  305. }
  306. else {
  307. out.print( "Sorry UserName or Password Error!" );
  308. RequestDispatcher rd=request.getRequestDispatcher( "/index.html" );
  309. rd.include(request, response);
  310. }
  311. }
  312. }
  313. WelcomeServlet.java
  314. import java.io.*;
  315. import javax.servlet.*;
  316. import javax.servlet.http.*;
  317. public class WelcomeServlet extends HttpServlet {
  318. public void doPost(HttpServletRequest request, HttpServletResponse response)
  319. throws ServletException, IOException {
  320. response.setContentType( "text/html" );
  321. PrintWriter out = response.getWriter();
  322. String n=request.getParameter( "userName" );
  323. out.print( "Welcome " +n);
  324. }
  325. }
  326. web.xml<webapp>
  327. <servlet>
  328. <servletname>
  329. Login</servletname>
  330. <servletclass
  331. >Login</servletclass
  332. >
  333. </servlet>
  334. <servlet>
  335. <servletname>
  336. WelcomeServlet</servletname>
  337. <servletclass
  338. >WelcomeServlet</servletclass
  339. >
  340. </servlet>
  341. <servletmapping>
  342. <servletname>
  343. Login</servletname>
  344. <urlpattern>/
  345. servlet1</urlpattern>
  346. </servletmapping>
  347. <servletmapping>
  348. <servletname>
  349. WelcomeServlet</servletname>
  350. <urlpattern>/
  351. servlet2</urlpattern>
  352. </servletmapping>
  353. <welcomefilelist>
  354. <welcomefile>
  355. index.html</welcomefile>
  356. </welcomefilelist>
  357. </webapp>
  358. 14. Servlet Collab using Servlet context
  359. 15. Filterss
  360. http://www.javatpoint.com/servletfilter
  361. 16. Jdbc for insert and extract details from a table
  362. //STEP 1. Import required packages
  363. import java . sql .*;
  364. public class JDBCExample {
  365. // JDBC driver name and database URL
  366. static final String JDBC_DRIVER = "com.mysql.jdbc.Driver" ;
  367. static final String DB_URL = "jdbc:mysql://localhost/STUDENTS" ;
  368. // Database credentials
  369. static final String USER = "username" ;
  370. static final String PASS = "password" ;
  371. public static void main ( String [] args ) {
  372. Connection conn = null ;
  373. Statement stmt = null ;
  374. try {
  375. //STEP 2: Register JDBC driver
  376. Class . forName ( "com.mysql.jdbc.Driver" );
  377. //STEP 3: Open a connection
  378. System . out . println ( "Connecting to a selected database..." );
  379. conn = DriverManager . getConnection ( DB_URL , USER , PASS );
  380. System . out . println ( "Connected database successfully..." );
  381. //STEP 4: Execute a query
  382. System . out . println ( "Creating statement..." );
  383. stmt = conn . createStatement ();
  384. String sql = "SELECT id, first, last, age FROM Registration" ;
  385. ResultSet rs = stmt . executeQuery ( sql );
  386. //STEP 5: Extract data from result set
  387. while ( rs . next ()){
  388. //Retrieve by column name
  389. int id = rs . getInt ( "id" );
  390. int age = rs . getInt ( "age" );
  391. String first = rs . getString ( "first" );
  392. String last = rs . getString ( "last" );
  393. //Display values
  394. System . out . print ( "ID: " + id );
  395. System . out . print ( ", Age: " + age );
  396. System . out . print ( ", First: " + first );
  397. System . out . println ( ", Last: " + last );
  398. }
  399. rs . close ();
  400. } catch ( SQLException se ){
  401. //Handle errors for JDBC
  402. se . printStackTrace ();
  403. } catch ( Exception e ){
  404. //Handle errors for Class.forName
  405. e . printStackTrace ();
  406. } finally {
  407. //finally block used to close resources
  408. try {
  409. if ( stmt != null )
  410. conn . close ();
  411. } catch ( SQLException se ){
  412. } // do nothing
  413. try {
  414. if ( conn != null )
  415. conn . close ();
  416. } catch ( SQLException se ){
  417. se . printStackTrace ();
  418. } //end finally try
  419. } //end try
  420. System . out . println ( "Goodbye!" );
  421. } //end main
  422. } //end JDBCExample
  423. 17. Servlet databse insert:
  424. http://www.tutorialspoint.com/servlets/pdf/servletsdatabaseaccess.
  425. pdf
  426. // Loading required libraries
  427. import java . io .*;
  428. import java . util .*;
  429. import javax . servlet .*;
  430. import javax . servlet . http .*;
  431. import java . sql .*;
  432. public class DatabaseAccess extends HttpServlet {
  433. public void doGet ( HttpServletRequest request ,
  434. HttpServletResponse response )
  435. throws ServletException , IOException
  436. {
  437. // JDBC driver name and database URL
  438. static final String JDBC_DRIVER = "com.mysql.jdbc.Driver" ;
  439. static final String DB_URL = "jdbc:mysql://localhost/TEST" ;
  440. // Database credentials
  441. static final String USER = "root" ;
  442. static final String PASS = "password" ;
  443. // Set response content type
  444. response . setContentType ( "text/html" );
  445. PrintWriter out = response . getWriter ();
  446. String title = "Database Result" ;
  447. String docType =
  448. "<!doctype html public \"//
  449. w3c//dtd html 4.0 " +
  450. "transitional//en\">\n" ;
  451. out . println ( docType +
  452. "<html>\n" +
  453. "<head><title>" + title + "</title></head>\n" +
  454. "<body bgcolor=\"#f0f0f0\">\n" +
  455. "<h1 align=\"center\">" + title + "</h1>\n" );
  456. try {
  457. // Register JDBC driver
  458. Class . forName ( "com.mysql.jdbc.Driver" );
  459. // Open a connection
  460. Connection conn = DriverManager . getConnection ( DB_URL , USER , PASS );
  461. // Execute SQL query
  462. Statement stmt = conn . createStatement ();
  463. String sql ;
  464. sql = "SELECT id, first, last, age FROM Employees" ;
  465. ResultSet rs = stmt . executeQuery ( sql );
  466. // Extract data from result set
  467. while ( rs . next ()){
  468. //Retrieve by column name
  469. int id = rs . getInt ( "id" );
  470. int age = rs . getInt ( "age" );
  471. String first = rs . getString ( "first" );
  472. String last = rs . getString ( "last" );
  473. //Display values
  474. out . println ( "ID: " + id + "<br>" );
  475. out . println ( ", Age: " + age + "<br>" );
  476. out . println ( ", First: " + first + "<br>" );
  477. out . println ( ", Last: " + last + "<br>" );
  478. }
  479. out . println ( "</body></html>" );
  480. // Cleanup
  481. environment
  482. rs . close ();
  483. stmt . close ();
  484. conn . close ();
  485. } catch ( SQLException se ){
  486. //Handle errors for JDBC
  487. se . printStackTrace ();
  488. } catch ( Exception e ){
  489. //Handle errors for Class.forName
  490. e . printStackTrace ();
  491. } finally {
  492. //finally block used to close resources
  493. try {
  494. if ( stmt != null )
  495. stmt . close ();
  496. } catch ( SQLException se2 ){
  497. } // nothing we can do
  498. try {
  499. if ( conn != null )
  500. conn . close ();
  501. } catch ( SQLException se ){
  502. se . printStackTrace ();
  503. } //end finally try
  504. } //end try
  505. }
  506. }
  507. Now let us compile above servlet and create following entries in web.xml
  508. ....
  509. <servlet>
  510. < servlet name
  511. > DatabaseAccess </ servlet name
  512. >
  513. < servlet class
  514. > DatabaseAccess </ servlet class
  515. >
  516. </ servlet >
  517. < servlet mapping
  518. >
  519. < servlet name
  520. > DatabaseAccess </ servlet name
  521. >
  522. < url pattern
  523. > /DatabaseAccess</ url pattern
  524. >
  525. </ servlet mapping
  526. >
  527. O/P :
  528. ID: 100, Age: 18, First: Zara, Last: Ali
  529. ID: 101, Age: 25, First: Mahnaz, Last: Fatma
  530. ID: 102, Age: 30, First: Zaid, Last: Khan
  531. ID: 103, Age: 28, First: Sumit, Last: Mittal
  532. 18. HTML Form and retrieving inputs using jsp
  533. What You'll Learn in This Hour:
  534. ● How to use a JSP to receive form data
  535. ● How to work with form parameters
  536. ● How servlets interact with forms
  537. ● How to use a single JSP to present a form and handle its submission
  538. By now you are probably comfortable with the fundamentals of JavaServer Pages and servlets. In the
  539. examples presented so far, you have learned how to send output back to the browser. One of the
  540. advantages of the Web is that you can create forms to send data from the browser to the server. You are
  541. finally ready to begin creating forms with JSP and servlets, and that's where the fun really begins!
  542. A Simple HTML Form
  543. To start off the exploration of HTML forms, it's best to start with a small form and expand from there. Also,
  544. it's better to start with a JSP rather than a servlet, because it is easier to write out the HTML. Most of the
  545. form handling for JSPs and servlets is identical, so after you know how to retrieve form information from a
  546. JSP, you know how to do it from a servlet. Listing 3.1 shows an HTML file containing a simple input form
  547. that calls a JSP to handle the form.
  548. Listing 3.1 Source Code for SimpleForm.html
  549. <html>
  550. <body>
  551. <h1>Please tell me about yourself</h1>
  552. <form action="SimpleFormHandler.jsp" method="get">
  553. Name: <input type="text" name="firstName">
  554. <input type="text" name="lastName"><br>
  555. Sex:
  556. <input type="radio" checked name="sex" value="male">Male
  557. <input type="radio" name="sex" value="female">Female
  558. <p>
  559. What Java primitive type best describes your personality:
  560. <select name="javaType">
  561. <option value="boolean">boolean</option>
  562. <option value="byte">byte</option>
  563. <option value="char" selected>char</option>
  564. <option value="double">double</option>
  565. <option value="float">float</option>
  566. <option value="int">int</option>
  567. <option value="long">long</option>
  568. </select>
  569. <br>
  570. <input type="submit">
  571. </form>
  572. </body>
  573. </html>
  574. The <form> tag in Listing 3.1 sends the input from the form to a JSP called SimpleFormHandler.jsp . Figure
  575. 3.1 shows this form running in a browser.
  576. Figure
  577. 3.1 HTML forms frequently serve as the front end for a JSP.
  578. The SimpleFormHandler JSP does little more than retrieve the form variables and print out their values.
  579. Listing 3.2 shows the contents of SimpleFormHandler.jsp , which you can see is pretty short.
  580. Listing 3.2 Source Code for SimpleFormHandler.jsp
  581. <html>
  582. <body>
  583. <%
  584. // Grab the variables from the form.
  585. String firstName = request.getParameter("firstName");
  586. String lastName = request.getParameter("lastName");
  587. String sex = request.getParameter("sex");
  588. String javaType = request.getParameter("javaType");
  589. %>
  590. <%Print
  591. out the variables. %>
  592. <h1>Hello, <%=firstName%> <%=lastName%>!</h1>
  593. I see that you are <%=sex%>. You know, you remind me of a
  594. <%=javaType%> variable I once knew.
  595. </body>
  596. </html>
  597. 19. JSP Tags’
  598. Tag handler class:
  599. A tag handler class should implement Tag / IterationTag / BodyTag interface or it can
  600. also extend TagSupport / BodyTagSupport / SimpleTagSupport class. All the classes
  601. that support custom tags are present inside javax.servlet.jsp.tagext . In the below
  602. we are extending the class SimpleTagSupport .
  603. Details.java
  604. package beginnersbook.com;
  605. import javax.servlet.jsp.tagext.*;
  606. import javax.servlet.jsp.*;
  607. import java.io.*;
  608. public class Details extends SimpleTagSupport {
  609. public void doTag() throws JspException , IOException {
  610. /*This is just to display a message, when
  611. * we will use our custom tag. This message
  612. * would be displayed
  613. */
  614. JspWriter out = getJspContext().getOut();
  615. out .println( "This is my own custom tag" );
  616. }
  617. }
  618. TLD File
  619. This file should present at the location: Project Name/WebContent/WEB‐INF/ and
  620. it should have a .tld extension.
  621. Note:
  622. <name> tag: custom tag name. In this example we have given it as MyMsg
  623. <tag‐class> tag: Fully qualified class name. Our tag handler class Details.java is in
  624. package beginnersbook.com so we have given the value as
  625. beginnersbook.com.Details .
  626. message.tld
  627. <taglib>
  628. <tlibversion>
  629. 1.0 </tlibversion>
  630. <jspversion>
  631. 2.0 </jspversion>
  632. <shortname>
  633. My Custom Tag </shortname>
  634. <tag>
  635. <name> MyMsg </name>
  636. <tagclass>
  637. beginnersbook.com.Details </tagclass>
  638. <bodycontent>
  639. empty </bodycontent>
  640. </tag>
  641. </taglib>
  642. Using custom tag in JSP:
  643. Above we have created a custom tag named MyMsg . Here we will be using it.
  644. Note: taglib directive should have the TLD file path in uri field. Above we have
  645. created the message.tld file so we have given the path of that file.
  646. Choose any prefix and specify it in taglib directive’s prefix field. Here we have
  647. specified it as myprefix .
  648. Custom tag is called like this: <prefix:tagName/> . Our prefix is myprefix and tag
  649. name is MyMsg so we have called it as <myprefix:MyMsg/> in the below JSP page.
  650. <%@ taglib prefix= "myprefix" uri= "WEBINF/
  651. message.tld" %>
  652. <html>
  653. <head>
  654. <title> Custom Tags in JSP Example </title>
  655. </head>
  656. <body>
  657. <myprefix:MyMsg/>
  658. </body>
  659. </html>
  660. Output:
  661. This is my own custom tag
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top