BaseServlet
public class BaseServlet extends HttpServlet {
//重写HttpServlet中的service方法自定义分发方式
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
String requestURI = req.getRequestURI();// /travel/user/login
//截取字符串,因为我只要被调用的方法名称。
int index = requestURI.lastIndexOf("/");
String methodName = requestURI.substring(index + 1);
//获取指定方法对象
Method method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
System.out.println(method);
method.invoke(this, req, resp);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
UserServlet
@WebServlet("/user/*")
public class UserServlet extends BaseServlet {
/**
* 注册用户
*
* @param request
* @param response
* @throws IOException
*/
protected void register(HttpServletRequest request, HttpServletResponse response) throws IOException {
//获取所有请求参数
Map<String, String[]> parameterMap = request.getParameterMap();
//创建User对象
User user = new User();
try {
//使用BeanUtils封装请求参数
BeanUtils.populate(user, parameterMap);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//创建UserServiceImpl对象
UserServiceImpl usi = new UserServiceImpl();
boolean flag = usi.register(user);
ResultInfo ri = new ResultInfo();
//判断是否注册成功
if (flag) {
ri.setFlag(true);
} else {
ri.setFlag(false);
ri.setErrorMsg("注册失败,用户名已经存请重新输入!");
}
//使用jackson将对象转化为json响应给客户端
ObjectMapper om = new ObjectMapper();
response.setContentType("application/json;charset=utf-8");
System.out.println(om.writeValueAsString(ri));
om.writeValue(response.getWriter(), ri);
}
/**
* 激活用户状态
*
* @param request
* @param response
* @throws IOException
*/
protected void activeServlet(HttpServletRequest request, HttpServletResponse response) throws IOException {
//获取请求参数
String code = request.getParameter("code");
UserServiceImpl usi = new UserServiceImpl();
boolean flag = usi.updateUserStatus(code);
//创建结果集对象
ResultInfo ri = new ResultInfo();
if (flag) {
ri.setFlag(true);
} else {
ri.setFlag(false);
ri.setErrorMsg("注册失败,请联系管理员!");
}
response.setContentType("application/json;charset=utf-8");
ObjectMapper om = new ObjectMapper();
om.writeValue(response.getWriter(), ri);
}
/**
* 用户登录
*
* @param request
* @param response
* @throws IOException
*/
protected void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
//获取客户端请求参数
String username = request.getParameter("username");
String password = request.getParameter("password");
UserServiceImpl usi = new UserServiceImpl();
//登录功能
User user = usi.login(username, password);
//创建结果对象
ResultInfo ri = new ResultInfo();
//判断用户是否存在
if (user == null) {
ri.setFlag(false);
ri.setErrorMsg("用户名或密码错误!");
}
//判断用户邮箱是否激活
if (user != null && !"Y".equals(user.getStatus())) {
ri.setFlag(false);
ri.setErrorMsg("邮箱未激活,请先激活");
}
//判断用户登录成功
if (user != null && "Y".equals(user.getStatus())) {
//用户登录成功后将用户信息存储到session中
request.getSession().setAttribute("user", user);
ri.setFlag(true);
}
//设置响应格式
response.setContentType("application/json;charset=utf-8");
//创建ObjectMapper对象
ObjectMapper om = new ObjectMapper();
//将对象转化为json格式字符串
System.out.println(om.writeValueAsString(ri));
om.writeValue(response.getWriter(), ri);
}
/**
* 页面显示用户名称
*
* @param request
* @param response
* @throws IOException
*/
protected void showUsername(HttpServletRequest request, HttpServletResponse response) throws IOException {
//获取session
HttpSession session = request.getSession();
//从session中获取User
User user = (User) session.getAttribute("user");
response.setContentType("application/json;charset=utf-8");
ObjectMapper om = new ObjectMapper();
om.writeValue(response.getWriter(), user);
}
/**
* 退出用户登录
*
* @param request
* @param response
* @throws IOException
*/
protected void clearUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
//获取session
HttpSession session = request.getSession();
session.invalidate();
}
}
出现的异常
java.lang.NoSuchMethodException: cn.itcast.travel.web.servlet.UserServlet.showUsername(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
at java.lang.Class.getMethod(Class.java:1786)
at cn.itcast.travel.web.servlet.BaseServlet.service(BaseServlet.java:24)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
通过分析未发现的方法其实是存在的,是因为方法的权限修饰符是protected,所以访问不了。
一般有两种解决方法:
方式1:
将getMethod()更改为getDeclaredMethod()方法。
setAccessible(true);取消 Java 语言访问检查。
方式2:
修改权限修饰符为public,使用第二种。