JSP based on an MVC user login example (JavaBean + Servlet)

Source: Internet
Author: User
Tags html page reset xmlns

Let's look at the interactive diagram.

Example One,

Implementation of user login based on MVC (JavaBean + Servlet + JSP)

1, web.xml Configuration

<?xml version= "1.0″encoding=" utf-8″?>
<web-app version= "2.5″
Xmlns= "Http://java.sun.com/xml/ns/javaee"
Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
Xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee
Http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd ">
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>

<servlet>
<servlet-name>loginServlet</servlet-name>
<servlet-class>org.zxj.mvcdemo.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
</web-app>

2, User

Package org.zxj.mvcdemo.vo;

public class user{
Private String userid;
private String name;
private String password;
public void Setuserid (String userid) {
This.userid = userid;
}
public void SetName (String name) {
THIS.name = name;
}
public void SetPassword (String password) {
This.password = password;
}
Public String GetUserID () {
return This.userid;
}
Public String GetName () {
return this.name;
}
Public String GetPassword () {
return This.password;
}

}

3, DatabaseConnection

Package ORG.ZXJ.MVCDEMO.DBC;

Import java.sql.*;

public class databaseconnection{

private static final String Dbdriver = "Com.mysql.jdbc.Driver";
private static final String Dburl = "JDBC:MYSQL://LOCALHOST:3306/ZXJ";
private static final String Dbuser = "root";
private static final String Dbpassword = "PF";
private static Connection con = null;
Public DatabaseConnection () throws exception{
try{
Class.forName (Dbdriver);
This.con = Drivermanager.getconnection (Dburl,dbuser,dbpassword);
}catch (Exception e) {
Throw e;
}
}
Public Connection getconnection () {
return This.con;
}
public void Close () throws Exception {
if (This.con!= null) {
try{
This.con.close ();
}catch (Exception e) {
Throw e;
}
}
}
}

4, Iuserdao

Package Org.zxj.mvcdemo.dao;

Import Org.zxj.mvcdemo.vo.User;

public interface iuserdao{
public boolean findlogin (user user) throws Exception;
}

5, Userdaoimpl

Package Org.zxj.mvcdemo.dao.impl;

Import Org.zxj.mvcdemo.vo.User;
Import org.zxj.mvcdemo.dao.*;
Import java.sql.*;

public class Userdaoimpl implements iuserdao{
PRIVATE Connection conn = null;
Private PreparedStatement pstmt = null;
Public Userdaoimpl (Connection conn) {
This.conn = conn;
}
public boolean findlogin (user user) throws exception{
Boolean flag = false;
String sql = "SELECT name from user where userid=?" and password =? ";
this.pstmt = this.conn.prepareStatement (sql);
This.pstmt.setString (1,user.getuserid ());
This.pstmt.setString (2,user.getpassword ());
ResultSet rs = This.pstmt.executeQuery ();
if (Rs.next ()) {
User.setname (rs.getstring ("name"));
Flag = true;
}
This.pstmt.close ();
return flag;
}
}

6, Userdaoproxy

Package org.zxj.mvcdemo.dao.proxy;

Import Org.zxj.mvcdemo.vo.User;
Import org.zxj.mvcdemo.dbc.*;
Import org.zxj.mvcdemo.dao.*;
Import org.zxj.mvcdemo.dao.impl.*;
Import java.sql.*;

public class Userdaoproxy implements iuserdao{
Private databaseconnection DBC = null;
Private Iuserdao DAO = null;
Private PreparedStatement pstmt = null;
Public Userdaoproxy () {
try{
THIS.DBC = new DatabaseConnection ();
}catch (Exception e) {
E.printstacktrace ();
}
This.dao = new Userdaoimpl (Dbc.getconnection ());
}
public boolean findlogin (user user) throws exception{
Boolean flag = false;
try{
Flag = this.dao.findLogin (user);
}catch (Exception e) {
Throw e;
}finally{
This.dbc.close ();
}
return flag;
}
}

7, Daofactory

Package org.zxj.mvcdemo.factory;

Import org.zxj.mvcdemo.dao.*;
Import org.zxj.mvcdemo.dao.proxy.*;
public class daofactory{
public static Iuserdao Getiuserdaoinstance () {
return new Userdaoproxy ();
}
}

8, Loginservlet

Package org.zxj.mvcdemo.servlet;

Import java.io.*;
Import java.util.*;
Import javax.servlet.*;
Import javax.servlet.http.*;
Import org.zxj.mvcdemo.factory.*;
Import org.zxj.mvcdemo.vo.*;

public class Loginservlet extends httpservlet{
public void Doget (HttpServletRequest req, httpservletresponse res) throws Servletexception,ioexception {
String Path = "login.jsp";
String UserID = req.getparameter ("userid");
String Userpass = Req.getparameter ("Userpass");
list<string> info = new arraylist<string> ();
if (UserID = null | | "". Equals (userid)) {
Info.add ("User ID cannot be empty");
}
if (Userpass = null | | "". Equals (Userpass)) {
Info.add ("Password cannot be blank");
}
if (info.size () = = 0) {
User user = new user ();
User.setuserid (userid);
User.setpassword (Userpass);
try{
if (Daofactory.getiuserdaoinstance (). Findlogin (user)) {
Info.add ("User login successful, welcome" +user.getname () + "login");
}else{
Info.add ("User Login failed");
}
}catch (Exception e) {
E.printstacktrace ();
}
}
Req.setattribute ("info", info);
Req.getrequestdispatcher (Path). Forward (Req,res);
RequestDispatcher rd = null;
RD = Req.getrequestdispatcher (path);
Rd.forward (Req,res);

}
public void DoPost (HttpServletRequest req, httpservletresponse res) throws Servletexception,ioexception {
Doget (Req,res);
}
}

9, login.jsp

<%@ page language= "java" contenttype= "text/html" pageencoding= "GBK"%>
<%@ page import= "java.util.*"%>
<title> Login </title>
<meta http-equiv= "Content-type" content= "TEXT/HTML;CHARSET=GBK" >

<body>
<%
Request.setcharacterencoding ("GBK");
list<string> info = (list<string>) request.getattribute ("info");
if (info!= null) {
Iterator<string> iter = Info.iterator ();
while (Iter.hasnext ()) {
Out.println (Iter.next ());
}
}
%>
<form action= "Loginservlet" method= "POST" >
User: <input type= "text" name= "userid"/> <br/>
Password: <input type= "password" name= "Userpass"/><br/>
<input type= "Submit" value= "Login"/>
<input type= "reset" value= "reset"/>
</body

Example Two,

First: JSP: the page instruction and HTML composition of the query interface query_condention.jsp, that is, we now HTML page and ASP page similar.


<%@ page language= "java" contenttype= "TEXT/HTML;CHARSET=GBK"%>
<title> Student Information </title>
<body>
<form action= "Searchstudentservlet" method= "POST" >
Date of birth: <input type= "text" name= "Begindate" > to <input type= "text" name= "EndDate" >
<input type= "Submit" value= "inquiry student" >
</form>
</body>


Second: The control layer Searchstudentservlet is used to accept the client's request to process the process, call model (Studentmanager.java), and forward to the student_list.jsp page of the backend server to be requested

Import java.text.*;
Import java.util.*;
Import java.io.*;
Import javax.servlet.http.*;
Import javax.servlet.*;

Import com.bjpowernode.exam.model.*;
Import com.bjpowernode.exam.manager.*;

public class Searchstudentservlet 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 {

String sbegindate = Request.getparameter ("Begindate");
String senddate = Request.getparameter ("EndDate");

Date begindate = new Date ();
Date EndDate = new Date ();
try {
Begindate = new SimpleDateFormat ("Yyyy-mm-dd"). Parse (sbegindate);
EndDate = new SimpleDateFormat ("Yyyy-mm-dd"). Parse (senddate);
}catch (Exception e) {
E.printstacktrace ();
}

Studentmanager Studentmanager = new Studentmanagerimpl ();
list<student> studentlist = studentmanager.findstudentlist (begindate, EndDate);

Set the student list to the Requet range
Request.setattribute ("Student_list", studentlist);

Forwarding, forwarding is forwarded on the server side, the client is not aware of
Request.getrequestdispatcher ("/student_list.jsp"). Forward (request, response);


Put the studentlist in the session
HttpSession session = Request.getsession ();
Session.setattribute ("Student_list", studentlist);

Redirect does not share the request
The following is a wrong notation, which represents the port 8080
Response.sendredirect ("/student_list.jsp");
Response.sendredirect (Request.getcontextpath () + "/student_list.jsp");
}
}

Third: The student_list.jsp page receives the data to form the HTML, returns to the browser, renders in the interface

<%@ page language= "java" contenttype= "TEXT/HTML;CHARSET=GBK"%>
<%@ page import= "java.util.*"%>
<%@ page import= "java.text.*"%>
<%@ page import= "com.bjpowernode.exam.model.*"%>
<%@ page import= "com.bjpowernode.exam.manager.*"%>
<title> Student Information </title>
<style type= "Text/css" >
/* Table width is 1px, solid line, black */
table{
BORDER:1PX solid black;
Border-collapse:collapse;
}

TD {
BORDER:1PX solid black;
Border-collapse:collapse;
}

</style>
<body>
<table border= "1" >
<tr>
<td> Student Code </td>
<td> name </td>
<td> Sex </td>
<td> Birth date </td>
<td> Contact Tel </td>
<td> Home Address </td>
<td> class name </td>
<td> Age </td>
</tr>
<%
List<student> studentlist = (List) request.getattribute ("Student_list");
List<student> studentlist = (List) session.getattribute ("Student_list");
For (iterator<student> iter=studentlist.iterator (); Iter.hasnext ();) {
Student Student = Iter.next ();
%>
<tr>
<td><%=student.getstudentid ()%></td>
<td><%=student.getstudentname ()%></td>
<td><%=student.getsex ()%></td>
<td><%=new SimpleDateFormat ("Yyyy-mm-dd"). Format (Student.getbirthday ())%></td>
<td><%=student.getcontacttel ()%></td>
<td><%=student.getaddress ()%></td>
<td><%=student.getclasses (). Getclassesname ()%></td>
<%
Long B = 1000l*60l*60l*24l*365l;
Long a = System.currenttimemillis ()-Student.getbirthday (). GetTime ();
%>
<td><%=a/b%></td>
</tr>
<%
}
%>
</table>
</body>

The student_list.jsp page of the view is a mixture of HTML and Java code, where the query conditional interface query_condention.jsp primarily HTML, because the interaction of background data is not involved.


IV: XML configuration servlet:

<?xml version= "1.0" encoding= "iso-8859-1"
<web-app xmlns= "HTTP://JAVA.SUN.COM/XML/NS/J2EE"
    xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
    xsi: schemalocation= "Http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
     version= "2.4"
 <servlet>
  <servlet-name>searchstudentservlet </servlet-name>
  <servlet-class>searchstudentservlet</servlet-class>
  </servlet>
 <servlet-mapping>
  <servlet-name>searchstudentservlet</ Servlet-name>
  <url-pattern>/searchstudentservlet</url-pattern>
 </ Servlet-mapping>
 
</web-app>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.