一、创建两个jsp页面:a.jsp和b.jsp。
1、a.jsp
1 <!-- 登陆表单 --> 2 <form action="CheckLoginServlet.do" method="post"> 3 <input type="text" name="username"> 4 <input type="password" name="password" /> 5 <input type="submit" value="submit"> 6 </form>
2、b.jsp
1 <!-- 登录成功,打印欢迎信息 --> 2 ${requestScope.username } 欢迎您。。。。。。
二、创建用于进行登录判断的Servlet:CheckLoginServlet.js
1 import java.io.IOException; 2 import javax.servlet.ServletException; 3 import javax.servlet.annotation.WebServlet; 4 import javax.servlet.http.HttpServlet; 5 import javax.servlet.http.HttpServletRequest; 6 import javax.servlet.http.HttpServletResponse; 7 8 @WebServlet("/CheckLoginServlet.do") 9 public class CheckLoginServlet extends HttpServlet { 10 private static final long serialVersionUID = 1L; 11 12 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 13 /** 14 * 登录验证:如果用户名和密码相同,跳转到b.jsp页面。否则跳回到a.jsp页面重新登录。 15 */ 16 String name = request.getParameter("username"); 17 String password = request.getParameter("password"); 18 if(name.equals(password) && name.trim()!="" && password.trim()!=""){ 19 request.setAttribute("username", name); 20 request.getRequestDispatcher("b.jsp").forward(request, response); 21 return; 22 }else{ 23 response.sendRedirect("a.jsp"); 24 } 25 } 26 }
三、在web.xml文件中配置初始化参数encoding,值为utf-8。
<context-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </context-param>
四、编写字符编码过滤器:EncodingFilter.java,过滤根目录下所有的文件。
1 import java.io.IOException; 2 import javax.servlet.Filter; 3 import javax.servlet.FilterChain; 4 import javax.servlet.FilterConfig; 5 import javax.servlet.ServletException; 6 import javax.servlet.ServletRequest; 7 import javax.servlet.ServletResponse; 8 import javax.servlet.annotation.WebFilter; 9 10 @WebFilter("/*") 11 public class EncodingFilter implements Filter { 12 13 private String encoding; 14 15 public EncodingFilter() {} 16 17 public void init(FilterConfig fConfig) throws ServletException { 18 encoding = fConfig.getServletContext().getInitParameter("encoding"); 19 } 20 21 public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException { 22 request.setCharacterEncoding(encoding); 23 chain.doFilter(request, response); 24 } 25 26 public void destroy() {} 27 28 }
五、完成。。。。。。
时间: 2024-12-22 11:47:27