Crud instances that implement the MVC pattern (not seen in the general textbook)

Source: Internet
Author: User
Tags exception handling stmt

Examples include the following files:

M: Student.java, contains the database access code, can represent the student information, encapsulates the basic method to the student operation.

Part C: Studentservlet.java, to complete the control of the increase and deletion check.

V: studentlist.jsp and edituser.jsp, the former displays a list of students, as well as additions, deletions, and modifications to the portal, which are added and modified.

Configuration file: Web.xml

The relevant files are given below respectively.

----------------------------------------Student.java-----------------------------------------------------------

Package JavaBean;

Import java.sql.Connection;
Import Java.sql.DriverManager;
Import Java.sql.ResultSet;
Import java.sql.SQLException;
Import java.sql.Statement;
Import java.util.ArrayList;
Import java.util.List;

public class Student {

Private Connection con;

Private Statement stmt;

Private ResultSet RS;

Private String SID;
Private String sname;
Private String Sage;

/*
* Get all student information
*/
Public List getallstudents () {
List List = new ArrayList ();
String sql = "SELECT * from student";
try{
rs = executequery (SQL);
while (Rs.next ()) {
Student temp = new Student ();
Temp.setsid (rs.getstring (1));
Temp.setsname (rs.getstring (2));
Temp.setsage (Rs.getstring (3));
List.add (temp);
}
}catch (Exception e) {
System.out.println (E.tostring ());
}finally{
Close ();
}
return list;
}

/*
* Add Students
*/
public void Add (Student stu) {
String sql = "INSERT into student values ('" +stu.getsid () + "', '" +stu.getsname () + "'," +stu.getsage () + ")";
try{
executeupdate (SQL);
}catch (Exception e) {
System.out.println (E.tostring ());
}finally{
Close ();
}
}

/*
* Delete Student
*/
public void Delete (String sid) {
String sql = "Delete from student where sid= '" +sid+ "";
try{
executeupdate (SQL);
}catch (Exception e) {
System.out.println (E.tostring ());
}finally{
Close ();
}
}

/*
* Revise student
*/
public void edit (Student stu) {
String sql = "Update student set Sname= '" +stu.getsname () + "', sage=" +stu.getsage () + "where sid= '" +stu.getsid () + "'";
try{
int n = executeupdate (sql);
System.out.println ("--------------" +n);
}catch (Exception e) {
System.out.println (E.tostring ());
}finally{
Close ();
}
}

/*
* Search students according to school number
*/
Public Student Findstudentbyid (String SID) {
String sql = "SELECT * from student where sid= '" +sid+ "";
try{
rs = executequery (SQL);
if (Rs.next ()) {
Student temp = new Student ();
Temp.setsid (rs.getstring (1));
Temp.setsname (rs.getstring (2));
Temp.setsage (Rs.getstring (3));
return temp;
}
}catch (Exception e) {
System.out.println (E.tostring ());
}finally{
Close ();
}
return null;
}

/*
* Perform updates and other actions
*/
public int executeupdate (String sql) throws sqlexception,classnotfoundexception{
Return Getstatement (). executeupdate (SQL);
}

/*
* Close Object
*/
public void Close () {
if (rs!=null)
Try{rs.close ();} catch (Exception e) {}
if (stmt!=null)
Try{stmt.close ();} catch (Exception e) {}
if (con!=null)
Try{con.close ();} catch (Exception e) {}
}

/*
* Execute a query that has a result set return
*/
Public ResultSet executequery (String sql) throws sqlexception,classnotfoundexception{
Return Getstatement (). executequery (SQL);
}

/*
* Get Statement Object
*/
Public Statement getstatement () throws sqlexception,classnotfoundexception{
if (stmt==null) {
stmt = getconnection (). createstatement ();
}
return stmt;
}

/*
* Get Connection
*/
Public Connection getconnection () throws sqlexception,classnotfoundexception{
if (con==null) {
Class.forName ("Oracle.jdbc.driver.OracleDriver");
con = drivermanager.getconnection ("JDBC:ORACLE:THIN:@192.168.102.206:1521:ORCL", "Training", "123456");
}
return con;
}

Public String GetSID () {
return SID;
}

public void Setsid (String sid) {
This.sid = SID;
}

Public String Getsname () {
return sname;
}

public void Setsname (String sname) {
This.sname = sname;
}

Public String Getsage () {
return sage;
}

public void Setsage (String sage) {
This.sage = Sage;
}

public static void Main (string[] args) {
Student Student = new Student ();
}
}

----------------------------------------Studentservlet.java-------------------------------------------------

Package servlet;

Import java.io.IOException;
Import java.util.List;

Import JavaBean. Student;

Import Javax.servlet.RequestDispatcher;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

public class Studentservlet extends HttpServlet {

public void doget (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {

DoPost (Request,response);
}


public void DoPost (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
Request.setcharacterencoding ("gb2312");
String sid = Request.getparameter ("Sid");
String sname = Request.getparameter ("sname");
String sage = request.getparameter ("sage");
String action = request.getparameter ("action");

Calling a business method
Student Student = new Student ();
if (action.equals ("list")) {//Display list
List List = Student.getallstudents ();
Request.setattribute ("studentlist", list);
}else if (action.equals ("add")) {//Add
Student info = new Student ();
Info.setsid (SID);
Info.setsname (sname);
Info.setsage (SAGE);
Student.add (info);
}else if (action.equals ("edit")) {//Modify
Student info = new Student ();
Info.setsid (SID);
Info.setsname (sname);
Info.setsage (SAGE);
Student.edit (info);
}else if (action.equals ("Findedit")) {//Modify previous query
Student info = Student.findstudentbyid (SID);
Request.setattribute ("student", info);
}else if (action.equals ("delete")) {//delete student
Student.delete (SID);
}else if (action.equals ("Findadd")) {

}

String forward;
if (Action.equals ("Findedit")) {
Request.setattribute ("type", "edit"); In the interface to determine whether to add an interface or modify the interface
Forward = "edituser.jsp";
}else if (action.equals ("Findadd")) {
Request.setattribute ("type", "add"); In the interface to determine whether to add an interface or modify the interface
Forward = "edituser.jsp";
}else if (action.equals ("list")) {
Forward = "studentlist.jsp";
}else{
Forward = "Student?action=list";
}

RequestDispatcher rd = Request.getrequestdispatcher (forward);
Rd.forward (Request,response);
}

}

----------------------------------------studentlist.jsp---------------------------------------------------------

<%@ page contenttype= "text/html;charset=gb2312"%>
<%@ taglib prefix= "C" uri= "Http://java.sun.com/jsp/jstl/core"%>
<title> All student Information </title>
<body>
<table>
<tr>
<td> number </td><td> name </td><td> age </td>
</tr>
<c:foreach var= "Student" items= "${studentlist}" >
<tr>
<td>${student.sid}</td>
<td>${student.sname}</td>
<td>${student.sage}</td>
<td><a href= "Student?action=delete&sid=${student.sid}" > Delete </a></td>
<td><a href= "Student?action=findedit&sid=${student.sid}" > Modify </a></td>
</tr>
</c:forEach>
</table>
<a href= "Student?action=findadd" > Add students </a>
</body>

----------------------------------------edituser.jsp-----------------------------------------------------------

<%@ page language= "java" pageencoding= "gb2312" contenttype= "text/html;charset=gb2312"%>
<%@ taglib prefix= "C" uri= "Http://java.sun.com/jsp/jstl/core"%>

<%
String path = Request.getcontextpath ();
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";
%>

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
<base href= "<%=basePath%>" >
<title>my JSP ' edituser.jsp ' starting page</title>

<body>
<form action= "Student?action=${type}" method= "POST" >
<table>
<tr>
<td> School Number </td>

<td>

<c:if test= "${Empty Student}" > <input type= "text" name= "Sid" ></c:if>

<c:if test= "${! Empty Student}" > <input type= "hidden" name= "Sid" Value= "${student.sid}" >${student.sid} </c:if>

</td>
</tr>
<tr>
<td> name </td><td><input type= "text" name= "sname" <c:if test= "${! Empty Student}" > value= "${ Student.sname} "</c:if> ></td>
</tr>
<tr>
<td> Age </td><td><input type= "text" name= "Sage" <c:if test= "${! Empty Student}" > value= "${ Student.sage} "</c:if>></td>
</tr>
<tr>
<td><input type= "Submit" value= "OK" ></td><td><input type= "reset" value= "reset" ></td >
</tr>
</table>
</form>
</body>

----------------------------------------Web.xml-----------------------------------------------------------------

<?xml version= "1.0" encoding= "UTF-8"?>
<web-app version= "2.4"
Xmlns= "HTTP://JAVA.SUN.COM/XML/NS/J2EE"
Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
Xsi:schemalocation= "Http://java.sun.com/xml/ns/j2ee
Http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd ">
<servlet>
<description>this is the description i-Java component</description>
<display-name>this is the display name of my Java EE component</display-name>
<servlet-name>StudentServlet</servlet-name>
<servlet-class>servlet. Studentservlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>StudentServlet</servlet-name>
<url-pattern>/student</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>


What the instance needs to add:
1. Increase the verification part.
2, increase the exception handling part.
3, increase the log section.
4, increase the internationalization part.
5, increase the paging function.
6, to increase the flexibility of the query function.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.