Dodoke September 3 study notes

Keywords: JSP JDBC MySQL encoding

Syllabus

1. jsp form data change
2. Difference between form method get and post;
3. Character encoding

Course notes

1, jsp form data change

//First, query the database through id and display it in the form
<%
    String id = request.getParameter("id");
    String name ="";
    Class.forName("com.mysql.jdbc.Driver");
    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/datt", "root", "1");
    PreparedStatement pst = conn.prepareStatement("SELECT name FROM stu WHERE id="+id);
    ResultSet rs =pst.executeQuery();
    if(rs.next()){
        name = rs.getString("name");
    }
    rs.close();
    pst.close();
    conn.close();
%>
//<%= %>Output variables and expression contents directly
<form action="update.jsp?id=<%=id %>" method = "post" onsubmit="return edit()">
    <input type = "text" name = "username1" value ="<%=name%>"/>
    <input type = "submit" value = "modify">
</form>
//Confirm the pop-up event
<script>
    var edit = function(){
        if(confirm("Are you sure to modify it?")){
            return true;
        } else {
            return false;
        }
    }
</script>
<%

    request.setCharacterEncoding("utf-8");
    //Get editPre.jspinside inputid and username Value
    String username1 = request.getParameter("username1");
    String id = request.getParameter("id");

    Class.forName("com.mysql.jdbc.Driver");
    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/datt", "root", "1");
    //Simplify the code by using? After setString and SetInt method assignment; Integer.valueOf()--take String Translate into int
    PreparedStatement pst = conn.prepareStatement("UPDATE stu SET name =? WHERE id=?");
    pst.setString(1, username1);
    pst.setInt(2,Integer.valueOf(id));
    int rs = pst.executeUpdate();
    //int rs = pst.executeUpdate();
    pst.close();
    conn.close(); 
    // jdbc programming
    out.print("<h1>modify"+rs+"Bar data</h1>");
%>

2, Difference between method property get and post in the form

<form action="update.jsp?id=<%=id %>" method = "post" >
    <input type = "text" name = "username1" value ="<%=name%>"/>
    <input type = "submit" value = "modify">
</form>

When the method in it is get, the passed in value = '<% = name% > will be displayed on the URL, with weak security, and get cannot pass in the id value of action = "update. JSP? id = <% = id% >
When the method in it is post, both id and name will be passed to the next page, and the value will not be displayed on the URL address, which has high security;

3, Change character encoding
① Eclipse > windows > Preferences > search Encoding > UTF-8
② Servers – > server.xml – > port number plus URIEncoding = "UTF-8"
③ Add request.setCharacterEncoding("utf-8") when the form method is post;

Posted by foreverhex on Wed, 01 Jan 2020 10:01:14 -0800