Servlet implementation of the registration

1, Servlet realize the idea of ​​registration:

 

 

 2, engineering structures

 

 

 

 

 3, functions to achieve:

(1) html enable the collection of the data:

<body bgcolor="aqua">
<center>
    <h3>注册</h3>
    <form action="/Register_servlet_war_exploded/register" method="post">
      用户名:<input type="text" name="account" size="12"><br><br>
        密码:<input type="password" name="password" size="12">
        <input type="submit" value="注册">
        <input type="reset" value="取消">
    </form>
</center>
</body>

(2) Servlet: acquiring data form submission, and encapsulate them into the Map set (code amount can be reduced)

public class ServletRegister extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        Map<String, String[]> properties=request.getParameterMap();//将表单中的数据封装到Map中
        Login log= new Login();
        try {
            BeanUtils.populate(log, properties);
        } catch (IllegalAccessException|InvocationTargetException e) {
            e.printStackTrace();
        }
        try {
            regist(log);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        response.sendRedirect(request.getContextPath()+"/log.html");//重定向
    }
    public void regist(Login log) throws SQLException{//数据库
        Connection con=null;
        try {
            con = C3p0Utils.getConnection();
            QueryRunner qr = new QueryRunner();
            String sql = "insert into Login values(?,?)";
            Object[] insert = {log.getAccount(), log.getPassword()};
            qr.update(con, sql, insert);
        }
        catch (SQLException e){
            throw new RuntimeException(e);
        }
    }

4, get and post submission garbage problem:

(1) post submission:

request.setCharacterEncoding("UTF-8");

Direct format high number of server code.

(2) get submitted:

Using request.setCharacterEncoding ( "UTF-8"); a method can not solve the problem of the Chinese distortion. Encoding format needs to be changed from the bottom:

name = new String(name,getBytes("ISO-8859-1"),"UTF-8");

 Post request submitted in the request body, can be solved by setting the coding distortion. Get the data submitted in the request line, by providing the coding method is not acceptable.

 

Guess you like

Origin www.cnblogs.com/zhai1997/p/11610207.html