0% found this document useful (0 votes)
97 views

A Simple Mvc-2 Example With Mysql

This document provides steps to create a simple MVC application with MySQL database integration in Netbeans. It includes creating the project structure, adding JAR files, configuring the database, creating JSP and servlet files to handle requests and responses, and defining a bean class to interact with the database. The application allows searching student records by ID, displaying results, and updating a student's major.

Uploaded by

GeorgeAnton
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
97 views

A Simple Mvc-2 Example With Mysql

This document provides steps to create a simple MVC application with MySQL database integration in Netbeans. It includes creating the project structure, adding JAR files, configuring the database, creating JSP and servlet files to handle requests and responses, and defining a bean class to interact with the database. The application allows searching student records by ID, displaying results, and updating a student's major.

Uploaded by

GeorgeAnton
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

A Simple MVC-2 example with MySQL

A simple example of MVC architecture

1. Open Netbeans 6.9 or 7.0 2. Click File->New Project->Java Web-> Web Application
We named it MVCServlet and choose the Tomcat as server.

3. Download the mysql-connector-java-5.0.8-bin.jar file and put it into the lib folder of Tomcat. Configure the MySQL database
Choose the Service part.

Right click the MySQL(Connector/J driver) which in the Drivers folder, and choose the Connect Using

Complete the databases information and click test button

Next right click your database name and choose Connect..

create table test_students ( ID varchar(50), LNAME varchar(50), FNAME varchar(50), MAJOR varchar(50) ) insert into test_students values('1','Smith','John','CS'); insert into test_students values('2','Wong','Franklin','SWE'); insert into test_students values('3','Wallace','Jennifer','IT'); insert into test_students values('4','Borg','Jennifer','CSE');

4. Creating main.html, add the following code.


<html> <%@ page contentType="text/html;charset=gb2312"%> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <title>Name</title> </head> <body> <table border="0" width="100%"> <form name="name search" action="/MVCServlet/MyServlet" method="POST"> Student ID: <input type="text" name="stuId"></br> <input type="submit" value="Search"> </form> <tr> <td><div align="center"> <a href="/MVCServlet/MyServlet?command=showInformation">Show Information</a>

</div></td> </tr> <tr> <td><div align="center"> <a href="/MVCServlet/update.html">Update Major</a> </div></td> </tr> </table> </body> </html>

Student's

5. Creating update.html, add the following code.


<html> <%@ page contentType="text/html;charset=gb2312"%> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <title>Name</title> </head> <body> <table border="0" width="100%"> <form name="add student" action="/MVCServlet/UpdateStudent" method="POST"> Student ID :<br><input type="text" name="stuId"></br> Major: <br><input type="text" name="stuMajor"></br> <input type="submit" value="Update"> </form> <tr> <td><div align="center"> <a href="/MVCServlet/MyServlet?command=showInformation">Show Information</a> </div></td> </tr> </table> </body> </html>

6. Creating fromServlet.jsp, add the following code.

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@page import="bean.Student"%> <%@page import="myModel.MyBean"%> <%@page import="java.util.ArrayList;"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html>

<head> <title>Student Information</title> </head> <body> <table width="100%" border="1" align="center" cellpadding="0" cellspacing="1" bordercolorlight="#CCCCCC" bordercolor="#FFFFFF" bordercolordark="#FFFFFF" > <tr> <td height="22" colspan="3" align="left" ><strong class="text13">Student Information</strong></td> </tr> <tr class="stuInfo"> <td height="22" align="center" >Last Name</td> <td height="22" align="center" >First Name</td> <td height="22" align="center" >Major</td> </tr> <% ArrayList stus = (ArrayList) request.getAttribute("stus"); if (stus != null && stus.size() > 0) { Iterator it = stus.iterator(); while (it.hasNext()) { Student st = (Student) it.next(); %> <tr> <td height="22" align="center" ><%=st.getStuLname()%></td> <td height="22" align="center" ><%=st.getStuFname()%></td> <td height="22" align="center" ><%=st.getStuMajor()%></td> </tr> <%} } else { %> <tr> <td height="22" colspan="7" align="center" >Sorry, no value</td> </tr> <%}%> </table> <tr> <td><div align="center"> <a href="/MVCServlet/main.html">Return to the Main Page</a> </div></td> </tr> <tr>

<td><div align="center"> <a href="/MVCServlet/update.html">Return Page</a> </div></td> </tr> </body> </html>

to

the

Updated

7. Creating MyServlet
Right click the project name and choose new->Servlet.

Add the following code package myControler; import bean.Student; import java.io.IOException;

import java.util.ArrayList; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import myModel.MyBean; /** * * @author zfu */ //@WebServlet(name = "MyServlet", urlPatterns = {"/MyServlet"}) public class MyServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String stuId = request.getParameter("stuId"); MyBean myBean = new MyBean(); ArrayList<Student> stus = myBean.queryStu(stuId); request.setAttribute("stus", stus); ServletContext app = this.getServletContext(); RequestDispatcher rd = app.getRequestDispatcher("/fromServlet.jsp"); rd.forward(request, response); } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }

8. Creating another servlet, UpdateStudent.java


/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package myControler; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import myModel.MyBean;

public class UpdateStudent extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String stuId = request.getParameter("stuId"); String stuMajor = request.getParameter("stuMajor"); MyBean myBean = new MyBean(); int j = myBean.updateStu(stuId, stuMajor); if(j!=0){ out.println("<script>alert('Update Sucessfully')</script>"); response.setHeader("refresh", "3;URL=update.html"); }else{ out.println("<script>alert('Update fail')</script>"); response.setHeader("refresh", "3;URL=update.html"); }

} // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs

*/ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }

9. Creating bean package and Student class.


Right click the project name, as the following graph.

Add the following code into it. package bean; /** * * @author zfu */ public class Student { private String stuId; private String stuLname; private String stuFname; private String stuMajor; public void setStuId(String stuId) { this.stuId = stuId; } public String getStuId() { return stuId; } public void setStuLname(String stuLname) { this.stuLname = stuLname;

} public String getStuLname() { return stuLname; } public void setStuFname(String stuFname) { this.stuFname = stuFname; } public String getStuFname() { return stuFname; } public void setStuMajor(String stuMajor) { this.stuMajor = stuMajor; } public String getStuMajor() { return stuMajor; }

Creating bean 10. Creating myModel page and myBean Class

package myModel; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import java.sql.ResultSet; import bean.Student; import java.util.ArrayList; /** * * @author zfu */ public class MyBean { private Connection conn = null;

private String db_user = "root"; private String db_password = "850326"; private String db_url "jdbc:mysql://localhost/yourdatabase?useUnicode=true&amp;characterEncoding=utf-8"; private String db_driver = "org.gjt.mm.mysql.Driver"; private Statement stmt = null; private ResultSet rs = null;

public void initConnection() { try{ Class.forName(db_driver); conn = DriverManager.getConnection(db_url,db_user,db_password); }catch(Exception e){ e.printStackTrace(); } } public ArrayList<Student> queryStu(String stuId) {

ArrayList<Student> stus = new ArrayList<Student>(); //String sql = "Select LNAME,FNAME,MAJOR from test_students where ID= '" + stuId + "'"; String sql = "Select LNAME,FNAME,MAJOR from test_students"; if(stuId!=null&&stuId.trim().length()!=0) { sql += " where ID = '" + stuId + "'"; } try { this.initConnection();

stmt = conn.createStatement(); rs = stmt.executeQuery(sql); while(rs.next()) { Student stu = new Student(); stu.setStuLname(rs.getString("LNAME")); stu.setStuFname(rs.getString("FNAME"));

stu.setStuMajor(rs.getString("MAJOR")); stus.add(stu); } }catch(Exception e) { e.printStackTrace(); } finally{ this.closeConn(); } return stus; } public int updateStu(String stuId, String stuMajor) {

String sql = "update test_students set MAJOR='"+stuMajor + "' where ID='"+stuId+"'" ; try { this.initConnection(); stmt = conn.createStatement(); int i = stmt.executeUpdate(sql); if(i!=0){ return 1; }else{ return 0; } }catch(Exception e) { e.printStackTrace(); } finally{ this.closeConn(); } return 1; } public void closeConn(){ try{ if(conn!=null){ conn.close(); conn = null; }

}catch(Exception e){ e.printStackTrace(); } }

11.Configure web.xml file.


<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <servlet> <servlet-name>MyServlet</servlet-name> <servlet-class>myControler.MyServlet</servlet-class> </servlet> <servlet> <servlet-name>UpdateStudent</servlet-name> <servlet-class>myControler.UpdateStudent</servlet-class> </servlet> <servlet-mapping> <servlet-name>MyServlet</servlet-name> <url-pattern>/MyServlet</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>UpdateStudent</servlet-name> <url-pattern>/UpdateStudent</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>main.html</welcome-file> </welcome-file-list> </web-app>

Finally, Click Run button to run the Project

Have Fun!!!

You might also like