跟永哥学MVC:Jsp+Servlet+JavaBean开发后台登录程序,125建站网原创,转载请务必注明出版。
Jsp+Servlet+JavaBean开发后台登录程序-实现一
login.html(视图)
<form action="loginServlet" method="post"> 用户名: <input type="text" name="name"/><br/> 密码: <input type="text" name="pas"/><br/> <input type="submit" value="Login"/> </form>
login_model.java(JavaBean模型)
package com; public class login_model { String name=null, pas=null; public String getName() {return name;} public void setName(String name) { this.name = name;} public String getPas( ) { return pas; } public void setPas(String pas) {this.pas = pas;} public boolean login() { if(name.trim().equals("admin")&&(pas.trim().equals("1234"))) { return true; } else { return false; } } }
loginServlet.java(Servlet控制器)
package form; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import com.login_model; public class loginServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String name=request.getParameter("name"); String pas=request.getParameter("pas"); login_model newModel=new login_model();//调用模型 newModel.setName(name); newModel.setPas(pas); if(newModel.login()) { //out.print("<script Lanuage='JavaScript'>window.alert('登录成功!')</script>"); request.setAttribute("message","登录成功!"); } else { //out.print("<script Lanuage='JavaScript'>window.alert('登录失败!')</script>"); request.setAttribute("message","登录失败!"); } RequestDispatcher requestDispatcher=request.getRequestDispatcher("/viewMessages.jsp"); //将请求转发到viewMessages.jsp requestDispatcher.forward(request,response); out.flush(); out.close(); }
知识点:
RequestDispatcher requestDispatcher=request.getRequestDispatcher("/viewMessages.jsp");
是请求转发,将请求转发到viewMessages.jsp,前后页面共享一个request ;
requestDispatcher.forward(request,response);
void forward(ServletRequest request,ServletResponse response)
用来传递request的,request就是客户端的请求,通过response可以往客户端写响应
web.xml(配置)
<servlet> <servlet-name>loginServlet</servlet-name> <servlet-class>form.loginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>loginServlet</servlet-name> <url-pattern>/loginServlet</url-pattern> </servlet-mapping>
viewMessages.jsp(视图)
<% request.setCharacterEncoding("UTF-8"); String login_message=(String)request.getAttribute("message"); out.println(login_message); %>
以上就是《Jsp+Servlet+JavaBean开发后台登录程序》的内容,希望对你理解MVC有所帮助,看完后请继续阅读下一页《Jsp+Servlet+JavaBean开发后台登录程序》实现方法二,同样的程序,实现略有不同。
125jz网原创文章。发布者:江山如画,转载请注明出处:http://www.125jz.com/1385.html