【javaweb源码】JSP+Servlet+MySQL实现注册功能

来源:互联网 发布:solidworks软件画足球 编辑:程序博客网 时间:2024/05/17 21:06

JSP+Servlet+MySQL实现注册功能  

本文来自:http://blog.csdn.net/liuhangbiao

注册页面 index.jsp<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="http://venusf.blog.163.com/blog/<%=basePath%>">  </head>    <body>    <div align="center" width="400">     <form action="LoginServlet" method="post">      <table border="1">       <tr>        <td>username</td>        <td><input type="text" name="username"/></td>       </tr>       <tr>        <td>password</td>        <td><input type="password" name="password"></td>       </tr>       <tr align="center">        <td colspan="2">        <input type="submit" value="注册"/>                    <input type="reset" value="重置"/></td>       </tr>      </table>          </form>    </div>  </body></html>




处理注册的Servlet:LoginServlet.javapackage com.servlet;import java.io.IOException;import java.io.PrintWriter;import java.sql.*;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class LoginServlet extends HttpServlet { private Connection conn;  public void destroy() {  super.destroy(); // Just puts "destroy" string in log  // Put your code here } public void doPost(HttpServletRequest request, HttpServletResponse response)   throws ServletException, IOException {  response.setContentType("text/html");  request.setCharacterEncoding("UTF-8");  response.setCharacterEncoding("UTF-8");  String username=request.getParameter("username");  String password=request.getParameter("password");  if(conn!=null){      try {    String sql = "insert into tb_user(username,password) value(?,?)";    PreparedStatement ps = conn.prepareStatement(sql);    ps.setString(1,username);    ps.setString(2, password);    ps.executeUpdate();    PrintWriter out = response.getWriter();    out.print("<h1 align='center'>");    out.print(username+"注册成功");   } catch (SQLException e) {    // TODO Auto-generated catch block    e.printStackTrace();   }  }  } public void init() throws ServletException {  super.init();  try{   Class.forName("com.mysql.jdbc.Driver");   String url = "jdbc:mysql://localhost:3306/tb_test";   conn = DriverManager.getConnection(url, "root", "admin");     }catch(Exception e){   e.printStackTrace();   System.out.println("数据库连接失败");  } }}


web.xml文件的配置  <servlet>    <servlet-name>LoginServlet</servlet-name>    <servlet-class>com.servlet.LoginServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>LoginServlet</servlet-name>    <url-pattern>/LoginServlet</url-pattern>  </servlet-mapping>



原创粉丝点击