myeclipse 中new Servlet: package名字com.hw.controller name StudentServlet(com.hw.entity中Student) 去掉URL的/servlet
(loginservlet中 action="StudentServlet")
(<script type="text/javascript">function go(){if(kk.name.value==""){//表单名.文框名.value
alert("姓名不能为空!!!")}else if(kk.pwd.value==""){alert("密码不能为空!!!")}else{
kk.submit();//表单名.submit() 即为提交}}</script></head>
<body><form name="kk" action="StudentServlet" method="post">
姓名:<input type="text" name="name"><br>
密码:<input type="password" name="pwd"><br>
爱好:<input type="checkbox" name="love" value="唱歌">唱歌 跳舞 武术 跑步 踢足球
<input type="button" value="登录" onclick="go()"></form></body>)
直接浏览器开默认是doget()
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class StudentServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// servlet解决乱码
request.setCharacterEncoding("utf-8");// 设置请求编码
response.setCharacterEncoding("utf-8");// 设置响应编码
response.setContentType("text/html;charset=utf-8");// 设置响应编码类型
String name = request.getParameter("name");// 取姓名
String pwd = request.getParameter("pwd");// 取姓名
String[] ss = request.getParameterValues("love");
if (name.equals("qq") && pwd.equals("123")) {
request.setAttribute("name", name);
// servlet中使用session
HttpSession session = request.getSession();
session.setAttribute("name", name);
response.sendRedirect("admin.jsp");
} else {
String love = "";
for (int i = 0; i < ss.length; i++) {
love += ss[i] + ",";
}
// servlet中使用out
PrintWriter out = response.getWriter();
out.println("你的爱号太多了:" + love.substring(0,love.length()-1));
}
}
}
重启服务器