jsp+javaBean+Servlet+jdbc+mysql micro-site analysis

First, the result picture:

     

Then let's talk about how to create a servlet and deploy it and be able to access it.

1. Create a normal java class under src, but inherit the parent class httpServlet. The path is: javax.servlet.http.HttpServlet, then rewrite your doPost() and doGet() methods, and comment out the super class of the parent class .doGet(req,resp)

2. Create a classes folder under web-inf, after writing and running, find the class file under build, and copy the entire package structure, not just copy the class file, the package structure should be the same as that of java

3. Configure the network access path of the servlet under web.xml, which cannot be accessed in the browser without configuration.

<servlet>
   <servlet-name>servlet.Servlet</servlet-name>//servlet-name can be started at will, as long as the two are exactly the same
   <servlet-class>servlet.Servlet</servlet-class>//true Package name.File name full name
  </servlet>
  <servlet-mapping>
    <servlet-name>servlet.Servlet</servlet-name>//servlet-name can be arbitrarily, as long as the two are exactly the same

//Use this path as the access path, IP address: port number/project name/servlet.Servlet can be accessed, the name can be arbitrarily named

 <url-pattern>/servlet.Servlet</url-pattern>
  </servlet-mapping>

4. It can be accessed now, and debugging is also the same as setting breakpoint debugging in java.

The full code for the first function of this microsite to query all student information is given below:

index_left.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<br><br>
<center>
  <a href="servlet.Servlet?methor=query_all" target="right">查询所有学生信息</a>
  <br><br>
  <a href="insert_student.jsp" target="right">插入学生体质信息</a>
  </center>
</body>
</html>

Servlet.java

package servlet;

import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import configUtil.QuerySql;
import configUtil.StudentHealthJavaBean;

 public class Servlet extends HttpServlet {
    public Servlet() {
    }
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO 第三步执行
		//super.doGet(req, resp);如果执行了父类方法可能会对自己的覆盖
		req.setCharacterEncoding("UTF-8");
		String methor=req.getParameter("methor");
		System.out.println(methor);
		if(methor!=null) {
			QuerySql query=new QuerySql();
			switch(methor) {
			case "query_all":
				List<StudentHealthJavaBean> list=query.getAllStudent();
				req.setAttribute("list", list);
				RequestDispatcher rd=req.getRequestDispatcher("/query_all_student.jsp");
				rd.forward(req, resp);
				break;
			}
		}else {
			System.out.println("参数传输失败。");
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO 第三部执行如果执行了父类方法可能会对自己的覆盖
		//super.doPost(req, resp);
		req.setCharacterEncoding("UTF-8");
		String str=req.getParameter("methor");
		QuerySql q=new QuerySql();
		StudentHealthJavaBean student=new StudentHealthJavaBean();
		student.setId(req.getParameter("id"));
		student.setName(req.getParameter("name"));
		student.setSex(req.getParameter("sex"));
		student.setAge(Integer.parseInt(req.getParameter("age")));
		student.setHight(Float.parseFloat(req.getParameter("hight")));
		student.setWeight(Float.parseFloat(req.getParameter("weight")));
		if(str!=null&&student!=null) {
			switch(str) {
			case "insert":
				int n=q.insertStudent(student);
				if(n==0) {
					System.out.println("没有成功插入数据!");
				    req.setAttribute("success", "没能成功添加此学生信息!");
				}
				else {
					System.out.println("成功插入数据!");
				    req.setAttribute("success","成功添加此学生信息!");
				    }
				RequestDispatcher dispatcher=req.getRequestDispatcher("/success.jsp");
				dispatcher.forward(req,resp);
				break;
			}
		}
	}
	@Override
	protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
		//第二部执行,完了根据post还是get自动调用doGet()或者doPost()方法
		super.service(arg0, arg1);
	}
	@Override
	public void init() throws ServletException {
		//第一步执行,自动生成request\response对象调用service方法
		super.init();
	}
}

QuerySql.java

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class QuerySql {

	private String insertSQL="insert into stu_info(id,name,sex,age,hight,weight) values(?,?,?,?,?,?)";
	private String selectSQL="select * from stu_info";
    private Connection con=null;
       public QuerySql(){
    	   
       }
	@SuppressWarnings("finally")
	public List<StudentHealthJavaBean>  getAllStudent(){
		List<StudentHealthJavaBean> list=new ArrayList<StudentHealthJavaBean>();
		ResultSet rs=null;
		PreparedStatement ps=null;
		StudentHealthJavaBean student=null;
		     con=DataBaseConfig.getConnection();
		     try {
				ps=con.prepareStatement(selectSQL);
			     rs=ps.executeQuery();
			     while(rs.next()) {
			    	 student=new StudentHealthJavaBean();
			    	 student.setId(rs.getString("id"));
			    	 student.setName(rs.getString("name"));
			    	 student.setSex(rs.getString("sex"));
			    	 student.setAge(rs.getInt("age"));
			    	 student.setHight(rs.getFloat("hight"));
			    	 student.setWeight(rs.getFloat("weight"));
			    	 list.add(student);
			     }
			} catch (SQLException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}finally {
				DataBaseConfig.closeDatabaseConnection(con, ps, rs);
				if(list!=null)
					System.out.println("成功查询!");
				else {
					System.out.println("list是空值!");
				}
				return list;
			}
	}
	
	
	public int insertStudent(StudentHealthJavaBean student) {
		int num=0;
		Connection con=null;
		ResultSet rs=null;
		PreparedStatement ps=null;
		    
		con=DataBaseConfig.getConnection();
		try {
			ps=con.prepareStatement("select * from stu_info where id=?");
			ps.setString(1, student.getId());
			rs=ps.executeQuery();
			if(rs.first()) {
			System.out.println("已经存在此学号的学生信息,不能插入了!");
			DataBaseConfig.closeDatabaseConnection(con, ps, rs);
			return 0;
			}
			ps=con.prepareStatement(insertSQL);
			ps.setString(1, student.getId());
			ps.setString(2, student.getName());
			ps.setString(3, student.getSex());
			ps.setInt(4, student.getAge());
			ps.setFloat(5, student.getHight());
			ps.setFloat(6, student.getWeight());
			num=ps.executeUpdate();
		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}finally {
			return num;
		}
		
	}
}

DataBaseConfig.java

public class DataBaseConfig {
     public static String url1="jdbc:mysql://localhost:3306/";//数据库的网址
     public static String databaseName="students";//数据库名
     public static String userName="&user=root";//登录数据库的登录名
     public static String password="&password=root";//数据库的密码
     public static String driverName="com.mysql.jdbc.Driver";
//mysql的驱动包名,下载到的解压包已放在tomcat的lib下
     public static String encoding="&useUnicode=true&characterEncoding=UTF-8";//编码方式
     public static String url=url1+databaseName+"?"+"useSSL=false"+encoding+userName+password;
       @SuppressWarnings("finally")//SSL是一种加密技术,这里不要他
	public static Connection getConnection() {
    	   Connection con=null;
    	     try {
				Class.forName(driverName);
				con=DriverManager.getConnection(url);
			} catch (ClassNotFoundException | SQLException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}finally {
				return con;
			}
       }
     
       public static void closeDatabaseConnection(Connection con,PreparedStatement ps,ResultSet rs) {
			try {//需要手动释放数据库的一些资源
		    	   if(rs!=null)rs.close();
				if(ps!=null) ps.close();
		    	if(con!=null) con.close();
			} catch (SQLException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
       }
}

StudentHealthJavaBean.java

public class StudentHealthJavaBean {
	private String id;
	private String name;
	private String sex;
	private int age;
	private float hight;
	private float weight;
	
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public float getHight() {
		return hight;
	}

	public void setHight(float hight) {
		this.hight = hight;
	}

	public float getWeight() {
		return weight;
	}
	public void setWeight(float weight) {
		this.weight = weight;
	}
	public StudentHealthJavaBean() {
		// TODO 自动生成的构造函数存根
	}

}

query_all_student.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 <%@page import="java.util.*" %>
 <%@page import="configUtil.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>所有学生信息</title>
</head>
<body style="padding-left:100px;padding-top:20px">
 <%!
   List<StudentHealthJavaBean> list=null;
   StudentHealthJavaBean student=null;
 %> 
 <table border="2">
 <%
    list=(List<StudentHealthJavaBean>)request.getAttribute("list");
    for(int i=0;i<list.size();i++){
    	student=new StudentHealthJavaBean();
    	student=list.get(i);
  %>
    <tr>
    <td><%=student.getId()%></td>
    <td><%=student.getName()%></td>
    <td><%=student.getSex()%></td>
    <td><%=student.getAge()%></td>
    <td><%=student.getHight()%></td>
    <td><%=student.getWeight()%></td>
    </tr> 
   <% 
    }
   %>
 </table>
</body>
</html>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>StudentHealthSys</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
   <servlet-name>servlet.Servlet</servlet-name>
   <servlet-class>servlet.Servlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>servlet.Servlet</servlet-name>
    <url-pattern>/servlet.Servlet</url-pattern>
  </servlet-mapping>
</web-app>

Bug logs and fixes in the process of making this microsite:

  • Does the servlet report an error in the label writing in the web?

When writing the file name in servlet-mapping in web.xml, notice whether the original file structure is under a certain package, and the package name is correct.

  • servlet file access failed?

Remove the sentence of dopost() doget() calling the method of the parent class, which is overridden by the method of the parent class, and the access name does not have the .java suffix.
Create the classes package under webInf, copy the package structure of the java file and the class file of the java file under buid

  • Failed to pass attributes with request between jsp and servlet, and the obtained attribute value is always null?

The written link <a> must be clicked to jump, it will not jump automatically

  • The data obtained after connecting to the database is always empty?

Stored in the way of setAttribute() but retrieved in the way of getParameter(), it must be consistent with getAttribute.
getParameter() seems to be only valid for the value of the Input tag.

  • How to convert the front and back lists?

Coercion is possible.

  • The data written to the request in the foreground is a null value when taken out in the background?

The form sends only the data in the input tag, and does not send the request data. You can set the data that is not filled in by the user as the type=hidden type of the input.

  • How does jsp jump to the servlet file?

There are two methods, one is to skip the action of the form form, and the other is to click the <a> hyperlink tag to jump.

  • How does servlet jump to jsp?

At present, only one method is known: the Request class method gets the RequestDispatcher object, and the forward of the object jumps back with the request and response.
RequestDispatcher dispatcher=req.getRequestDispatcher("/success.jsp");
dispatcher.forward(req,resp);

  • How to transfer data between jsp and servlet?

After the connection between the jsp form and <a>, you can add ?attribute=attribute value together, and they are all taken out through getParameter.

  • How does servlet transmit data to jsp?

Stored through the setAttribute() method of the request, and retrieved through getAttribute in jsp.

  • How does the servlet output text to the browser by itself?

Use the getWriter() method of HttpServletResponse to return a PrintWriter object, and call PrintWriter's println() method + flush() method to output text to its own window and client.

  • How to use javaBean in jsp?

First introduce the path of javaBean, then create the object of javabean
<jsp:useBean id=the object of javaBean you built class=package name file name scope=valid scope seesion/request, etc./>
and then store <jsp:setProperty name=must be the same as the above The id object has the same name
property=property name (if it is *, all inputs will automatically find the assignment with the same name as the name) value=value/>
call <jsp:getProperty name="object name" property="property name"/>

  • How to use javabean in servlet?

Create objects directly to store data for use, just like regular classes.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325828419&siteId=291194637