一个简单的javaBean+JSP+Servlet案例

时间:2021-07-19 19:06:09

大体过程如下:

新建javaWab项目,写javaBean代码:

package com.helloworld.servletImple.model;

public class HelloWorld {
private String account;
private String password;
private String submitFlag;

public String getAccount() {
return account;
}

public void setAccount(String account) {
this.account = account;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String getSubmitFlag() {
return submitFlag;
}

public void setSubmitFlag(String submitFlag) {
this.submitFlag = submitFlag;
}
}

再写servlet控制层:

package com.helloworld.servletImple.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.helloworld.servletImple.model.HelloWorld;

public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
doPost(request, response);
}
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
HelloWorld hw=(HelloWorld)request.getAttribute("helloModel");

System.out.println("用戶輸入的參數為"+"hw");
request.setAttribute("hw",hw);
request.getRequestDispatcher("/servletImple/welcome.jsp").forward(request,response);
}
}

在web.xml进行对servlet进行配置:

  <servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.helloworld.servletImple.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
最后写视图层,输出jsp页面:登录界面login.jsp和欢迎界面welcome.jsp

login.jsp

<body>
<jsp:useBean id="helloModel" class="com.helloworld.servletImple.model.HelloWorld" scope="request"></jsp:useBean>
<jsp:setProperty property="*" name="helloModel"/>
<%
if("login".equals(helloModel.getSubmitFlag())){
%>
<jsp:forward page="/hello"></jsp:forward>
<%
}
%>

<form action="/ss/servletImple/login.jsp" method="post">
<input type="hidden" name="submitFlag" value="login">
用戶名:<input type="text" name="account"><br>
密 碼:<input type="password" name="password"><br>
<input type="submit" value="提交">
</form>
</body>
welcome.jsp

<body>
<jsp:useBean id="hw" class="com.helloworld.servletImple.model.HelloWorld" scope="request">
</jsp:useBean>
歡迎 賬號為 <%=hw.getAccount() %> 盆友來訪.
</body>


整体的思路是:到登录界面输入用户名和密码,提交信息后 向servlet发出登录请求,到web.xml中配置配对,到servlet程序中,再在servlet中完成转发到欢迎界面.