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, "test2", "1234");
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 (Exception e)
{
e.printStackTrace();
response.getWriter().append(e.getMessage());
}
}
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @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);
}
}