SaveServlet
注意:
response.setContentType("text/html");
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
必须位于数据库操作和PrintWriter out=response.getWriter()之前,否则会乱码
package com.baozi;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name="saveServlet",urlPatterns="/SaveServlet") //必须支持servlet3.0注释
public class SaveServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private Connection con=null;
public SaveServlet() {
super();
}
public void init(ServletConfig config) throws ServletException{
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/javaweb";
String user="root";
String password="root";
try {
Class.forName(driver);
con=DriverManager.getConnection(url,user,password);
if(con!=null)
System.out.println("数据库连接成功!");
}catch(Exception e) {
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected 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 useremail=request.getParameter("useremail");
if(con!=null) {
try {
String sql="insert into userreg(username,useremail) values"+"(?,?)";
PreparedStatement ps=con.prepareStatement(sql);
ps.setString(1,username);
ps.setString(2, useremail);
ps.executeUpdate();
PrintWriter out=response.getWriter();
out.print(username);
out.flush();
out.close();
}catch(Exception e) {
e.printStackTrace();
}
}else {
response.sendError(500,"数据库连接错误!");
}
}
}