按书来的,学习阶段,一切都好新奇。。至少对比于DJANGO,好像复杂点点,但HTTP的东东,是相通的哈。
package cc.openhome.controller; import java.io.*; import java.util.*; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Register */ @WebServlet("/register.do") public class Register extends HttpServlet { private static final long serialVersionUID = 1L; private final String USERS = "C:/Users/sahara/workspace/Gossip/users"; private final String SUCCESS_VIEW = "success.view"; private final String ERROR_VIEW = "error.view"; /** * @see HttpServlet#HttpServlet() */ public Register() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String email = request.getParameter("email"); String username = request.getParameter("username"); String password = request.getParameter("password"); String confirmedPasswd = request.getParameter("confirmedPasswd"); List<String> errors = new ArrayList<String>(); if (isInvalidEmail(email)) { errors.add("no email or invalid email"); } if (isInvalidUsername(username)) { errors.add("username is empty or has existed"); } if (isInvalidPassword(password, confirmedPasswd)) { errors.add("please comfirm password again"); } String resultPage = ERROR_VIEW; if(!errors.isEmpty()) { request.setAttribute("errors", errors); } else { resultPage = SUCCESS_VIEW; createUserData(email, username, password); } request.getRequestDispatcher(resultPage).forward(request, response); } private boolean isInvalidEmail(String email){ return email == null|| !email.matches("^[_a-z0-9-]+([.][_a-z0-9-]+)*@[_a-z0-9-]+([.][_a-z0-9-]+)*$"); } private boolean isInvalidUsername(String username) { for (String file : new File(USERS).list()) { if (file.equals(username)) { return true; } } return false; } private boolean isInvalidPassword(String password, String comfirmedPasswd) { return false; } private void createUserData(String email, String username, String password) throws IOException { File userhome = new File(USERS + "/" + username); userhome.mkdir(); BufferedWriter writer = new BufferedWriter( new FileWriter(userhome + "/profile")); writer.write(email + "\t" + password); writer.close(); } }
时间: 2024-10-13 01:57:21