The MVC mode enables logon and addition, deletion, modification, and query (1). the mvc mode adds and deletes

Source: Internet
Author: User

The MVC mode enables logon and addition, deletion, modification, and query (1). the mvc mode adds and deletes

I am not using maven projects here, but general web projects. Therefore, you need to download and add the required racks. In the project, pay attention to the environment configuration, I use jre1.7.

 

1. Create a project

2. Create the MVC management package and import the corresponding architecture package servlet

3. Set up the entity class teacher. java corresponding to the database.

public class Teacher {            private  int  tid;            private  String tname;            private  String tpsw;            public int getTid() {                return tid;            }            public void setTid(int tid) {                this.tid = tid;            }            public String getTname() {                return tname;            }            public void setTname(String tname) {                this.tname = tname;            }            public String getTpsw() {                return tpsw;            }            public void setTpsw(String tpsw) {                this.tpsw = tpsw;            }            public Teacher(String tname, String tpsw) {                super();                this.tname = tname;                this.tpsw = tpsw;            }            public Teacher(int tid, String tname, String tpsw) {                super();                this.tid = tid;                this.tname = tname;                this.tpsw = tpsw;            }            public Teacher() {                super();            }}

4. Create a login. jsp file in WebContent.

1 <body> 2 <form action = "login" method = "post"> 3 Username: <input type = "text" name = "tname"> 4 password: <input type = "text" name = "tpsw"> 5 <input type = "submit" value = "login"> 6 </form>

5. Configure the form request login for the web. xml file

Web. xml file

Note: <servlet-name> before configuration, otherwise, an error is returned. <servlet-class>

<! -- Submit a Logon Request --> <servlet-name> login </servlet-name> <servlet-class> com. zr. controller. loginController </servlet-class> </servlet> <servlet-mapping> <servlet-name> login </servlet-name> <url-pattern>/login </url-pattern> </servlet-mapping>

6. Write the corresponding Request Entity class LoginController. java: inherits the doget () and dopost () Methods rewritten by HttpServlet, and calls the doget or dopost methods according to different method requests.

LoginController. java

Import java. io. IOException; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import javax. servlet. http. httpSession; import com. zr. model. teacher; import com. zr. service. valiDateService; import com. zr. serviceIm. valiDateServiceImpl; public class LoginController extends HttpServlet {protected Void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {super. doPost (req, resp);} protected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// obtain the input box String tname = req of the front-end form. getParameter ("tname"); String tpsw = req. getParameter ("tpsw"); Teacher tc = new Teacher (); tc. setTname (tname); tc. setTpsw (tpsw ); ValiDateService vds = new valiDateServiceImpl (); Teacher t = vds. valiDateTeacher (tc); HttpSession session = req. getSession (); session. setAttribute ("teacher", t); if (t! = Null) {// The returned value is not a null value. Redirect to req on the logon success page. getRequestDispatcher ("main. jsp "). forward (req, resp);} else {// return a null value and forward the request to the logon interface resp. sendRedirect ("login. jsp ");}}}

7. Write Data from the daos layer to the control layer

Public interface TeacherDao {/*** verify whether the instructor exists * @ param tc * @ return */public Teacher validateTeacher (Teacher tc );}

8.1 compile the encapsulation class to establish a connection with the database JDBCUtil. java

Package JDBCUtil; import java. SQL. connection; import java. SQL. driverManager; import java. SQL. SQLException; import java. SQL. statement; public class JDBCUtil {// 1. database address (different according to different data standards) private final static String DBURL = "jdbc: mysql: // localhost: 3306/student_crm? UseUnicode = true & characterEncoding = UTF8 "; // 2. set the user and PASSWORD private final static String USERNAME = "root"; private final static String PASSWORD = "root"; // 3. set the driver name (different based on different data standards) private final static String DBDRIVER = "com. mysql. jdbc. driver ";/*** get database Connection * @ return Returns database Connection */public static Connection getConnection () {Connection con = null; try {Class. forName (DBDRIVER); con = DriverManager. getConnection (DBURL, USERNAME, PASSWORD);} catch (ClassNotFoundException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (SQLException e) {// TODO Auto-generated catch block e. printStackTrace ();} return con ;}
// Close the Connection public static void closeJDBC (Statement st, Connection con) throws SQLException {if (st! = Null) {st. close () ;}if (con! = Null) {con. close ();}}}

 

8.2 Implementation of dao Layer

Import java. SQL. connection; import java. SQL. preparedStatement; import java. SQL. resultSet; import java. SQL. SQLException; import com. zr. dao. teacherDao; import com. zr. model. teacher; import JDBCUtil. JDBCUtil; public class TeacherDaoImpl implements TeacherDao {/*** enter the instructor object and return the instructor object * @ param args */public Teacher validateTeacher (Teacher tc) {Teacher teacher = new Teacher (); // SQL statement StringBuffer SQL = new StringBuf Fer ("select * from teacher where tname =? And tpsw =? "); // Get the database Connection con = JDBCUtil. getConnection (); try {PreparedStatement pst = con. prepareStatement (SQL. toString (); pst. setString (1, tc. getTname (); pst. setString (2, tc. getTpsw (); // returns a result set ResultSet rs1_pst.exe cuteQuery (); if (rs. next () {// put the data in the result set into the corresponding teacher object teacher = new Teacher (rs. getInt ("tid"), rs. getString ("tname"), rs. getString ("tpsw");} catch (SQLException e) {e. printStackTrace () ;}return teacher ;}}

9 Service layer

Public interface valiDateService {/*** @ param tc * @ return instructor object * verifies whether the instructor exists based on user input values */public Teacher valiDateTeacher (Teacher tc );}

Implement ServiceImpl. java on the 10 Service layer

Import com. zr. dao. teacherDao; import com. zr. daoIm. teacherDaoImpl; import com. zr. model. teacher; import com. zr. service. valiDateService; public class valiDateServiceImpl implements valiDateService {public Teacher valiDateTeacher (Teacher tc) {// reference of the parent class to the subclass object, the parent class can directly call the subclass method TeacherDao teacherDao = new TeacherDaoImpl (); // call the dao layer method to verify that Teacher teacher = teacherDao exists. validateTeacher (tc); return teacher ;}}

11 com. zr. controller Layer

Import java. io. IOException; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import javax. servlet. http. httpSession; import com. zr. model. teacher; import com. zr. service. valiDateService; import com. zr. serviceIm. valiDateServiceImpl; public class LoginController extends HttpServlet {protecte D void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {super. doPost (req, resp);} protected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// obtain the input box String tname = req of the front-end form. getParameter ("tname"); String tpsw = req. getParameter ("tpsw"); // puts the foreground object into the tc object as the input parameter Teacher tc = new Teacher (); tc. se TTname (tname); tc. setTpsw (tpsw); // call the Service-layer method to pass in the tc object, and use t to receive the returned result valiDateService vds = new valiDateServiceImpl (); Teacher t = vds. valiDateTeacher (tc); // obtain the JSP-scope session and put the instructor t object into the session HttpSession session = req. getSession (); int a = t. getTid (); // it is best to judge if (! = 0) {// The returned id is redirected to req on the logon success page. getRequestDispatcher ("main. jsp "). forward (req, resp); session. setAttribute ("teacher", t);} else {// return a null value. The request is forwarded to the logon interface req. getRequestDispatcher ("login. jsp "). forward (req, resp );}}}

 

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.