import java.io.OutputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.edu.hpu.stumanager.register.User;
import cn.edu.hpu.stumanager.register.UserManagerImpl;
//插入时自动生成
public class AddUser extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
//一般使用post,代码长的时间用post
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("GB18030");//设置对客户端请求重新编码
response.setCharacterEncoding("GB18030");//指定对服务器响应进行重新编码
String userid=request.getParameter("userid");//request.getParameter (String name)是获取相应名的数据,如果出现重复,则返回第一个的值
//request.getParameterValuees(String name)是获取如checkbox类,(名字相同,但值有多个)的数据,接收数组变量,如checkbox类型
String password=request.getParameter("password");
String password2=request.getParameter("password2");
String username=request.getParameter("username");
//定义多个需要的字符变量
if(!password.equals(password2)){//如果两次密码不相同
//'=='比较两个变量本身的值,即两个对象在内存中的首地址,equals()比较字符串中所包含的内容是否相同,分别为s1==s2,s1.equals(s2).equals如果在String Buffer中使用,需要重新定义,因为其实属于object中的
OutputStream out =response.getOutputStream(); //response.getOutputStream();实现文章下载,但报错(抛出异常的) 在要下载的jsp后面加上out.clear(); out=pageContext.pushBody();
out.write("<html>".getBytes());// write(byte[] b)将 b.length 个字节从指定的 byte 数组写入此输出流。输出,
request.setCharacterEncoding("GB18030");
response.setCharacterEncoding("GB18030");
String data="<br/>输入的两次密码不一致,请重新输入!<br/>";
//用html技术中meta标签模拟了一个http响应头,来控制浏览器的行为
out.write("<meta http-equiv='content-type' content='text/html;charset=GB18030'>".getBytes());
out.write(data.getBytes("GB18030"));
out.write("</html>".getBytes());
}
else
{
User user=new User();//如果输入两次密码判断一致的条件下,进行值的重新设定。新建用户
user.setUserid(userid);
user.setPassword(password);
user.setName(username);
UserManagerImpl umi=new UserManagerImpl();//新建UserManagerImpl
boolean flag=umi.add(user);//定义一个bool值,如果增加了user则调用下面所链接的jsp
if(flag==true){
response.sendRedirect("welcome.jsp");
}
}
}
}
jsp界面
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%
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="<%=basePath%>">
<title>My JSP 'reg.jsp' starting page</title>
</head>
<body>
<form action="AddUser" method="post">
账号<input type="text" name="userid"><br/>
密码<input type="password" name="password"><br/>
密码重复<input type="password" name="password2"><br/>
用户名<input type="text" name="username"><br/>
<input type="submit" value="确定">
</form>
</body>
</html>