Unit02: Servlet工作原理
点击注册按钮,返回注册信息
package web;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RegServlet extends HttpServlet {
@Override
protected void service(
HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
//1.接收请求数据
String userName =
req.getParameter("userName");
String pwd = req.getParameter("pwd");
String sex = req.getParameter("sex");
String[] interests =
req.getParameterValues("interest");
//处理乱码
//byte[] bs = userName.getBytes("iso8859-1");
//userName = new String(bs,"utf-8");
//2.处理业务逻辑
System.out.println(userName);
System.out.println(pwd);
System.out.println(sex);
if(interests != null) {
for(String interest: interests) {
System.out.println(interest);
}
}
//3.发送响应信息
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<p>Welcome,"+userName+"</p>");
out.close();
}
}
reg.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>注册</title>
</head>
<body>
<!--
访问路径是书写方式:
1.完整路径
http://localhost:8080/servlet2/reg
2.绝对路径
/servlet2/reg
注意:以"/项目名"开头
3.相对路径
写出当前访问的资源和将要访问的资源的相对关系.
当前:/servlet2/reg.html
目标:/servlet2/reg
-->
<form action="reg" method="post">
<p>
账号:<input type="text" name="userName"/>
</p>
<p>
密码:<input type="password" name="pwd"/>
</p>
<p>
性别:
<input type="radio" name="sex" value="M"/>男
<input type="radio" name="sex" value="F"/>女
</p>
<p>
兴趣:
<input type="checkbox" name="interest" value="friend"/>社交
<input type="checkbox" name="interest" value="read"/>阅读
<input type="checkbox" name="interest" value="game"/>竞技
</p>
<p><input type="submit" value="注册"/></p>
</form>
</body>
</html>
web.xml
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<display-name>servlet2</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>reg</servlet-name>
<servlet-class>web.RegServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>reg</servlet-name>
<url-pattern>/reg</url-pattern>
</servlet-mapping>
</web-app>
View Code