反射在Servlet里的应用
package com.wangqiang.servlet;
import java.io.IOException;
import java.lang.reflect.Method;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.wangqiang.pojo.User;
import com.wangqiang.service.LoginService;
import com.wangqiang.service.RegisterService;
import com.wangqiang.service.UserNameLegalService;
public class UserServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
String action=req.getParameter("action");
System.out.println(action);
try {
Method declaredMethod = this.getClass().getDeclaredMethod(action,HttpServletRequest.class,HttpServletResponse.class);
declaredMethod.invoke(this,req,resp);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("处理登陆的需求");
System.out.println("进入LoginServlet_WangQiang");
LoginService login=new LoginService();
String username=req.getParameter("username");
String password=req.getParameter("password");
System.out.println(username+","+password);
User user = new User(username,password);
if(login.login(user)) {
req.getRequestDispatcher("/studentInformation.jsp").forward(req, resp);
}else {
req.setAttribute("msg", "用户名或密码错误");
req.setAttribute("username",username );
req.getRequestDispatcher("/wangqiang_login.jsp").forward(req, resp);
}
}
protected void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
System.out.println("进入RegisterServlet_WangQiang");
RegisterService register=new RegisterService();
UserNameLegalService userNameLegalService=new UserNameLegalService();
String username=req.getParameter("username");
String password=req.getParameter("password");
User user = new User(username,password);
System.out.println(username+","+password);
System.out.println(userNameLegalService.userNameLegal(user));
if(userNameLegalService.userNameLegal(user)) {
if(register.register(user)) {
req.getRequestDispatcher("/studentInformation.jsp").forward(req, resp);
}else {
req.getRequestDispatcher("/wangqiang_register.jsp").forward(req, resp);
}
}else {
System.out.println("用户名已经存在");
req.getRequestDispatcher("/wangqiang_register.jsp").forward(req, resp);
}
}
}