Servlet代码
package project0816;
import java.io.IOException;
import java.io.PrintWriter;
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("/MyServlet02")
public class MyServlet02 extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//解决乱码
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//获得数据
String name=request.getParameter("username");
String password=request.getParameter("password");
String gender=request.getParameter("gender");
String city=request.getParameter("city");
String[]hobby=request.getParameterValues("hobby");
//在控制台输出
System.out.println("用户名:"+name);
System.out.println("密码:"+password);
System.out.println("性别:"+gender);
System.out.println("所在城市:"+city);
System.out.println("爱好:");
//在网页输出
PrintWriter out=response.getWriter();
out.print(name+"<br/>");
out.print(password+"<br/>");
out.print(gender+"<br/>");
out.print(city+"<br/>");
for(String n:hobby){
System.out.print(n);
out.print(n);
}
}
}
超链接请求提交数据
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>MyHtml01.html</title>
</head>
<body>
<a href="http://localhost:8080/JGWProjectText01/MyServlet02?username=张三&password=123&gender=男&city=北京&hobby=A">提交</a>
</body>
</html>
表单请求提交数据
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>MyHtml02.html</title>
</head>
<body>
<form action="http://localhost:8080/JGWProjectText01/MyServlet02" method="post">
用户名:<input type="text" name="username"><br/>
密码:<input type="password" name="password"><br/>
性别:<input type="radio" name="gender" value="男">男
<input type="radio" name="gender" value="女">女<br/>
所在城市:<select name="city">
<option value="北京">北京</option>
<option value="上海">上海</option>
<option value="广州">广州</option>
<option value="深圳">深圳</option>
</select><br/>
爱好:<input type="checkbox" value="A" name="hobby">A
<input type="checkbox" value="B" name="hobby">B
<input type="checkbox" value="C" name="hobby">C
<input type="checkbox" value="D" name="hobby">D<br/>
<input type="submit" value="提交">
</form>
</body>
</html>