综合案例-黑马旅游网_异步提交表单
在此使用异步提交表单是为了获取服务器响应的数据 因为前台使用的是html作为视图层 不能够直接从servlet相关的域对象获取值 只能通过ajax获取响应数据
HTML代码
$(function () { //当表单提交时 调用所有的校验方法 $("#registerForm").submit(function () { //发送数据到服务器 if ( checkUsername() && checkPassword() && checkEmail() && checkname() && checktelephone() && checkbirthday() && check()){ //校验通过 发送ajax请求 提交表单的数据 $.post("registUserServlet",$(this).serialize(),function (data) { //处理服务器响应的数据 data }) } //跳转页面 return false; //如果这个方法没有返回值 或者返回位true 则表单提交 如果返回为false 则表单不提交 });
运行结果
综合案例-黑马旅游网_servlet代码实现
java代码
package com.bai.web.servlet; import com.bai.domain.ResultInfo; import com.bai.domain.User; import com.bai.service.UserService; import com.bai.service.impl.UserServiceImpl; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.beanutils.BeanUtils; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Map; @WebServlet("/registUserServlet") public class RegistUserServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取数据 Map<String, String[]> map = req.getParameterMap(); //封装对象 User user = new User(); try { BeanUtils.populate(user,map); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } //调用service完成注册 UserServiceImpl service = new UserServiceImpl(); boolean flag = service.regist(user); ResultInfo info = new ResultInfo(); //响应结果 if (flag){ //注册成功 info.setFlag(true); }else{ //注册失败 info.setFlag(false); info.setErrorMsg("注册失败!"); } //将info对象序列化为json ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(info); //将json数据写回客户端 //设置content-type resp.setContentType("application/json;charset=utf-8"); resp.getWriter().write(json); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
UserService接口
package com.bai.service; import com.bai.domain.User; public interface UserService { //注册用户 boolean regist(User user); }
UserServiceImpl实现类
package com.bai.service.impl; import com.bai.domain.User; import com.bai.service.UserService; public class UserServiceImpl implements UserService { /** *注册用户 * @param user * @return */ @Override public boolean regist(User user) { return false; } }标签:service,com,表单,旅游网,import,servlet,bai From: https://www.cnblogs.com/aimz01/p/16619651.html