javaweb项目,注册的时候,表单提交一个User信息
1.String username=request.getParameter("username");
2.String password=request.getParameter("password");
3.Map<String,String[]>map=request.getParameterMap();
Map map
====>User
request.setCharactorEncoding("UTF-8");
response.setCharactorEncoding("UTF-8");
1.步骤,创建动态web项目
2.创建RegisterServlet(urlPattern="/register")继承HttpServlet,重写doGet和doPost,所有请求交给doGet方法处理
3.修改index.jsp文件,添加一个表单。注册User(Stirng username,String password,String realname,String tel)
4.创建Userservlet处理所有的和账号密码相关的请求
/user?method=register
5.在UserServlet先读取到mehtod的值,知道用户的意图
6.使用反射在当前类中找到对应的方法处理该请求
7.提取公共类
@WebServlet(urlPatterns = "/user")
//注册 /user?method=register
//登陆 /user?method=login
//退出 /user?method=logout
//读取到method参数的值,就可以知道用户的意图
public class UserServet extends BaseServlet {
public void register(HttpServletRequest req,HttpServletResponse resp){
Map<String, String[]> parameterMap = req.getParameterMap();
Set<String>set=parameterMap.keySet();
Iterator<String>it=set.iterator();
while (it.hasNext()){
System.out.println(it.next());
}
}
public void showUsers(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
List<String> strings=new ArrayList<String>();
strings.add("一二三");
strings.add("456");
strings.add("9981");
req.setAttribute("strings",strings);
req.getRequestDispatcher("show.jsp").forward(req,resp);
}
public class BaseServlet extends HttpServlet{
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//先读取method
String m=req.getParameter("method");
// 根据m来找到对应的方法
if (m!=null){
try {
//通过用户传递过来的method参数找到对应的方法
Method method=this.getClass().getDeclaredMethod(m,HttpServletRequest.class,HttpServletResponse.class);
method.invoke(this,req,resp);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
前端servlet问题的解决方案
1.继承BaseServlet
2.servlet.service
3.不在设置单独请求映射,在请求中添加方法参数,根据方法参数,找到对应的函数处理请求
4.反射,通过函数的名称和函数的参数类型找到方法,并且invoke该方法
5.继承,当一个类继承BaseServlet之后,BaseServlet中的共有方法就直接可以被子类调用