Javaweb servlet Redirect + example of an operation that uses a servlet to change the employee's additions and deletions __java that road.

Source: Internet
Author: User
redirect

What is redirection
The server notifies the browser to send a request to a new address
Note: You can send a 302 status code and a location message header
The message header contains an address. This address is called a redirected address. Once the browser receives it, it sends a request to the redirected address immediately

2. How to redirect
Response.sendredirect (String URL);
Note: The URL is the redirected address.
After redirection, the container empties the data saved in the Response object
3, features
The redirected address is arbitrary.
After redirection, the address of the browser's address bar will send a change

Just in the original click on the Jump Employee list changed to

            Response.sendredirect ("Emplist");  

Automatically jumps to the Emplist page.

The redirected Java code will continue to execute.

Every time the out.println didn't happen, it was written in the response.
Of course, can also occur a section of JS code timer, a few seconds later to send requests to the server.
can be implemented after adding finish wait a few s in jump to the employee list

Implementation can delete an employee
1, ID passed to the server
2, by the ID delete
3. redirect the current page

Then implement the modification, click Modify, with the ID parameter to a page, with this ID for the query returned with details of form forms, and then can modify the form information, in addition to the ID. Then submit it to a servlet. Update updates. Jump to the employee list again

Del.java: Deleting
Empdemo.java: Adding Employees
Emplist: Listing Employee List
Loadempservlet: Returning a form based on ID
Modify.java: Really modified, Loadempservlet submitted to this code: Del.java

Package web;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import Java.sql.DriverManager;
Import Java.sql.ResultSet;

Import java.sql.SQLException;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse; public class Del extends HttpServlet {public void service (httpservletrequest request,httpservletresponse response) th
        Rows servletexception,ioexception{response.setcontenttype ("Text/html;charset=utf-8");

        int id = integer.parseint (request.getparameter ("id"));



        PrintWriter out = Response.getwriter ();
        Java.sql.Connection conn = null;

        Java.sql.PreparedStatement prep = NULL;

                try {//Load driver Class.forName ("Com.mysql.jdbc.Driver");

                conn = Drivermanager.getconnection ("Jdbc:mysql://localhost:3306/jsd1507db", "root", "root"); Prep =conn.preparestatemeNT ("Delete from emp where id=?");


                 Prep.setint (1, id);
                Prep.executeupdate ();

            Generate Table Response.sendredirect ("Emplist") based on the data queried;
                 catch (SQLException e) {//TODO auto-generated Catch block * * 1, log
                * * E.printstacktrace ();
                 * * 1, see if the exception can be restored, if you can restore immediately restore, if not able to restore * (for example, database services paused, network interruption, etc., such as the exception is generally called system anomalies)
                * Prompt the user to retry/out.println later ("Retry later");
            E.printstacktrace (); catch (ClassNotFoundException e) {//TODO auto-generated catch block E.printstacktrac
        E ();
                }finally{if (conn!=null) {} try {conn.close ();
             catch (SQLException e) {//TODO auto-generated catch block       E.printstacktrace ();

                OUT.PRINTLN ("error occurred");
 }}//finally}}
Empdemo.java
Package web;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import Java.sql.DriverManager;

Import java.sql.SQLException;
Import javax.servlet.ServletException;
Import Javax.servlet.ServletRequest;
Import Javax.servlet.ServletResponse;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse;
Import com.mysql.jdbc.Connection;

Import com.mysql.jdbc.PreparedStatement; public class Empdemo extends HttpServlet {public void service (HttpServletRequest request,httpservletresponse respons
        E) throws servletexception,ioexception{request.setcharacterencoding ("GBK");
        String name = Request.getparameter ("name");
        String salary = Request.getparameter ("salary");
        String age = request.getparameter (' age '); * * * Check the request parameters must be checked for legality */String str = " 
 Emplist.java   
Package web;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import Java.sql.DriverManager;
Import Java.sql.ResultSet;

Import java.sql.SQLException;
Import javax.servlet.ServletException;
Import Javax.servlet.ServletRequest;
Import Javax.servlet.ServletResponse;

Import Javax.servlet.http.HttpServlet; 
public class Emplist extends HttpServlet {public void service (ServletRequest request,servletresponse response) throws servletexception,ioexception{//Set the data type and encoding Response.setcontenttype ("TEXT/HTML;CHARSET=GBK") returned by the server
                );

                Get an output stream and send the content to the browser printwriter out = Response.getwriter ();
                The employee information is then inserted into the database java.sql.Connection conn = null;
                Java.sql.PreparedStatement prep = NULL;

                ResultSet rst = null;

                        try {//Load driver Class.forName ("Com.mysql.jdbc.Driver"); conn = Drivermanager.getconnectiOn ("Jdbc:mysql://localhost:3306/jsd1507db", "root", "root");

                        Prep =conn.preparestatement ("SELECT * from emp");
                        rst = Prep.executequery ();
                        OUT.PRINTLN ("Inquiry normal ~ ~ ~");

                        Generate tables based on query data out.println ("<table border= ' 1 ' width= ' 60% ' >"); Out.println ("<tr><td>ID</td><td> name </td><td> salary </td><td> age </

                        Td> "+" <td> operation </td></tr> ");
                            while (Rst.next ()) {int id = rst.getint ("id");
                            String name = rst.getstring ("name");
                            Double salary = rst.getdouble ("salary");
                            int age = Rst.getint (' age '); Out.println ("<tr><td>" +id+ "</td><td>" +name+ "</td><td>" +salary+ "</td>
       <td> "+age+" </td> "+                             "<td><a href= ' del?id=" +id+ "' > Delete </a>&nbsp;&nbsp;<a href= ' load?id=



                        "+id+" ' > Modification </a></td></tr> ');

                        } out.println ("</table><br/>");

                    Out.println ("<a href = ' emp.html ' > Add Employee </a>");
                         catch (SQLException e) {//TODO auto-generated catch block/*
                        * 1, Log/E.printstacktrace (); 
                         * * 1, see if the exception can be restored, if you can restore immediately restore, if not able to restore * (for example, database services paused, network interruption, etc., such as the exception is generally called system anomalies)
                        * Prompt the user to retry/out.println later ("Retry later");
                    E.printstacktrace (); catch (ClassNotFoundException e) {//TODO auto-Generated catch block E.printstacktrace ();


                            }finally{if (conn!=null) {} try {
                        Conn.close (); catch (SQLException e) {//TODO auto-generated catch block e.pr
                            Intstacktrace ();

                        OUT.PRINTLN ("error occurred");
 }}//finally}}
Loadempservlet.java
Package web;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import Java.sql.DriverManager;
Import Java.sql.ResultSet;

Import java.sql.SQLException;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse; public class Loadempservlet extends httpservlet{public void service (HttpServletRequest request,httpservletresponse R
        Esponse) throws servletexception,ioexception{Response.setcontenttype ("Text/html;charset=utf-8");

        int id = integer.parseint (request.getparameter ("id"));



        PrintWriter out = Response.getwriter ();
        Read the ID java.sql.Connection conn = null for the employee to be modified;
        Java.sql.PreparedStatement prep = NULL;

        ResultSet rst = null;

                try {//Load driver Class.forName ("Com.mysql.jdbc.Driver"); conn = Drivermanager.getconnection ("jdbc:mysql://localhost:3306/jsd1507db"," root "," root ");
                Prep =conn.preparestatement ("SELECT * from emp where id=?");

                Prep.setint (1, id);

                rst = Prep.executequery ();
                    Generates a modified page if (Rst.next ()) {String name = rst.getstring (' name ') based on the employee information that is queried;
                    Double salary = rst.getdouble ("salary");
                    int age = Rst.getint (' age ');
                    Out.println ("<form action= ' modify ' method= ' post ' >");
                    Out.println ("ID:" +id+ "<br>");
                    Out.println ("Name:" + "<input name= ' name ' value=" +name+ ">");
                    Out.println ("Salary:" + "<input name= ' salary ' value=" +salary+ ">");
                    Out.println ("Age:" + "<input name= ' ages ' value=" +age+ ">"); The ID parameter is also passed, so a hidden name=id is made, and only the write name will be submitted to the form out.println ("<input type= ' hidden ' name= ' id ' value= '").
                    +id+ "' >"); Out.println ("<input Type= ' Submit ' value= ' OK ' > ');
                Out.println ("<form>");
                //} catch (SQLException e) {//TODO auto-generated catch block
                * * 1, Log/E.printstacktrace ();
                 * * 1, see if the exception can be restored, if you can restore immediately restore, if not able to restore * (for example, database services paused, network interruption, etc., such as the exception is generally called system anomalies)
                * Prompt the user to retry/out.println later ("Retry later");
            E.printstacktrace (); catch (ClassNotFoundException e) {//TODO auto-generated catch block E.printstacktrac
        E ();
                }finally{if (conn!=null) {} try {conn.close (); catch (SQLException e) {//TODO auto-generated catch block e.printstacktr
                    Ace ();

OUT.PRINTLN ("error occurred");                }}//finally}}
 
Modify.java
Package web;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import Java.sql.DriverManager;

Import java.sql.SQLException;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse; public class Modify extends httpservlet{public void service (HttpServletRequest request,httpservletresponse response)
        Throws servletexception,ioexception{Response.setcontenttype ("Text/html;charset=utf-8");
        int id = integer.parseint (request.getparameter ("id"));
        String name = Request.getparameter ("name");
        Double salary = double.parsedouble (Request.getparameter ("salary"));



        int age = Integer.parseint (Request.getparameter (' age '));


        PrintWriter out = Response.getwriter ();
        Update it java.sql.Connection conn = null;

        Java.sql.PreparedStatement prep = NULL; try {//load driver ClasS.forname ("Com.mysql.jdbc.") 

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.