1.用户信息提交界面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>注册新用户
2.用户信息存储代码
package com.hanqi;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.sql.*;/** * Servlet implementation class SaveUser */@WebServlet("/SaveUser")public class SaveUser extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public SaveUser() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //转换中文字符防止出现乱码 request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); String userID = request.getParameter("userid"); String userName = request.getParameter("username"); String pw = request.getParameter("password"); if(userID == null || userID.trim().length() == 0) { response.getWriter().append("用户ID不能为空"); } else if(userName == null || userName.trim().length() == 0) { response.getWriter().append("用户名称不能为空"); } else { //异常信息捕获 try{ Class.forName("oracle.jdbc.driver.OracleDriver"); String url = "jdbc:oracle:thin:@localhost:1521:ORCL"; Connection conn = DriverManager.getConnection(url,"test1","test1"); if(conn != null) { //操作数据库 String sql = "insert into t_user (user_id,user_name,password)" + "values (?,?,?)"; //执行SQL的类 PreparedStatement pps = conn.prepareStatement(sql); userName = new String(userName.getBytes("ISO-8859-1"),"UTF-8"); pps.setString(1, userID); pps.setString(2, userName); pps.setString(3, pw); int row = pps.executeUpdate();//执行SQL语句并返回数据行数 if(row > 0) { response.getWriter().append("保存了" + row + "条数据"); } else { response.getWriter().append("保存数据失败"); } //释放 pps.close(); conn.close(); } else { response.getWriter().append("连接数据库失败"); } } catch(ClassNotFoundException e){ e.printStackTrace(); } catch(Exception e){ e.printStackTrace(); response.getWriter().append(e.getMessage()); } } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); }}