一个servlet其实可以实现很多个请求跟form表单的action!
比如:我们可以在要提交的form表单中设置一个隐藏的input,并命名和赋值,
然后通过servlet的请求得到这个input,从而用来区分是哪个jsp页面的action,
从而在一个servlet中复用实现多个form表单的请求。
例如下面的jsp中我们定义了<input type="hidden" name="method" value="savepwd">
,当该form表单提交到servlet之后,我们就可以获得这个input的值,从而区分是哪个form.
<form id="userForm" name="userForm" method="post" action="${pageContext.request.contextPath }/jsp/user.do">
<input type="hidden" name="method" value="savepwd">
<!--div的class 为error是验证错误,ok是验证成功-->
<div class="info">${message}</div>
<div class="">
<label for="oldPassword">旧密码:</label>
<input type="password" name="oldpassword" id="oldpassword" value="">
<font color="red"></font>
</div>
<div class="providerAddBtn">
<!--<a href="#">保存</a>-->
<input type="button" name="save" id="save" value="保存" class="input-button">
</div>
</form>
我们的servlet如下:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getParameter("method");
if(method!=null && "savepwd".equals(method)){
modifyPwd(req,resp);
}
}
public void modifyPwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
User userSession = (User) req.getSession().getAttribute(ConstantField.USER_SESSION);
String newpassword = req.getParameter("newpassword");
System.out.println("new1"+newpassword);
if(userSession != null && !StringUtils.isNullOrEmpty(newpassword)){
UserService userService = new UserServiceImpl();
boolean flag = userService.updatePwd(userSession.getUserCode(), newpassword);
if(flag){
req.setAttribute("message","修改密码成功,请重新登录账号!");
//密码修改成功,移除session
req.getSession().removeAttribute(ConstantField.USER_SESSION);
}else {//修改密码失败
req.setAttribute("message","修改密码失败!");
}
}else {
//新密码为空有问题
req.setAttribute("message","新密码为空!");
}
//以上操作进行完,重新转发到当前页面
//resp.sendRedirect("pwdmodify.jsp");
req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
}