文章目录
- 1.java web项目如何创建?如何添加数据库的驱动程序?目录结构什么样子?
- 2、使用jdbc访问mysql数据库包括哪几步?用最基本的jdbc语法写出完整的增加、删除、修改、查询一个表的代码。
- 3、Statement和PreparedStatement的用法有什么不同?用哪个好?
- 4.jdbc执行事务的方法,如何启动事务?如何提交?如何回滚?如何不起用事务?
- 5.用jsp指令引入另一个jsp文件的语法跟用jsp动作引入另一个文件有什么区别?效果有什么不同?
- 6.jsp:forward和response.sendRedirect跳转网页的效果有什么不同?
- 7.jsp:userBean、setProperty、getProperty的语法、实现的效果是什么?
- 8.会用注解配置servlet、用xml配置servlet。
- 9.form表单提交后,在Action对应的网页或servlet中如何读取上一个表单中输入的数据?
- 10.如何把数据放到page、request、session、application中?如何从中取出来?
- 11.header中设置refresh的用法和效果
- 12.在jsp网页中如何import其他包中的类?
- 13.EL表达式的作用是什么?如何用EL表达式获取form表单或超链接、地址栏传递的数据? 如何用EL表达式获取放在requst、session、application属性中的数据?语法格式是什么?
- 14.如何读取web.xml中的中的数据?
- 15.jstl中的常用的几个标签的语法、用法要求熟练掌握,例如c:if、c:set、c:foreach、c:out等。
- 16.配置过滤器的方法,多个过滤器如何执行?执行的代码顺序
- 17.配置监听器的方法,监听器的编写方法
- 18.能用jpa编写实体类,编写一对一、一对多关系的是实体类,包括单向的写法、双向的写法
- 19.能用jsp+servlet+javabean编写完整的登录功能,实现增、删、改、查功能,能将一条数据或多条数据显示到页面中。注意错误处理,在servlet中读取到form提交的数据不合法时,能够保存错误,并转到录入界面,并显示错误信息。
- 20.能用jpa实现增删改查,既能在JavaSE中使用jpa,也能在JavaWeb中使用jpa
1.java web项目如何创建?如何添加数据库的驱动程序?目录结构什么样子?
打开项目,选择build Path -> Configure Build Path命令,打开路径对话框,选择libraries标签,选择addjars,选择mysql的jar包
项目名称
src
jre system library
mysql_jar包
2、使用jdbc访问mysql数据库包括哪几步?用最基本的jdbc语法写出完整的增加、删除、修改、查询一个表的代码。
1.加载驱动程序
class.forName("com.mysql.jdbc.Driver")
2.创建连接对象
Connection conn = DriverManager.getConnection("jdbc.mysql://localhost:3306/testdb", "root", "root")
3.创建PreparedStatement对象执行sql语句
3.1添加语句
String sql_insert = "insert into user(name, sex) values(?, ?);
PreparedStatement ps = conn.prepareStatement(sql_insert);
ps.setString(1, "tom");
ps.setString(2, "cat");
ps.executeUpdate();
ps.close();
conn.close;
3.2删除语句
String sql_delete = "delete from user where name = ?";
PreparedStatement ps = conn.preparedStatement(sql_delate);
ps.setString(1, "tom");
ps.executeUpdate();
ps.close();
conn.close();
3.3修改语句
String sql_edit = "update user set name = ? where name = ?";
PreparedStatement ps = coon.preparedStatement(sql_edit);
ps.setString(1, "tom_edit", "tom");
ps.close();
conn.close()
3.4查询语句
String sql_query = "select * from user";
PreparedStatement ps = conn.preparedStatement(sql_query);
ResultSet rs = ps.executeQuery(sql_query);
while(rs.next()){
String name = rs.getString("name");
String sex = rs.getString("sex");
System.out.println("name" + name + "sex" + sex);
}
ps.close();
conn.close();
3、Statement和PreparedStatement的用法有什么不同?用哪个好?
创建PreparedStatement对象时需要sql语句
由于sql语句中含有参数因此需要使用PreparedStatement的setString()方法为参数赋值
执行sql语句的execute()方法,executeQuery()方法,executeUpdate()方法不需要sql语句
PreparedStatement支持预编译的sql语句,如果多次访问数据库的sql语句只是参数不同时,那么该对象比statement对象的效率高,可以避免sql注入问题,Statement会有sql注入问题
PreparedStatement更好
4.jdbc执行事务的方法,如何启动事务?如何提交?如何回滚?如何不起用事务?
Connection conn;
PreparedStatement ps;
try{
class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc.mysql//localhost:8080/db, "root", "root");
con.setAutoCommit(false);//事务开始,手动提交事务,不写这条语句,默认是true,自动提交事务
String sql_update = "update user set name = ?, where name = ?";
ps = conn.preparedStatement(sql_update);
ps.setString(1, "kkk");
ps.setString(2, "tom");
ps.executeUpdate();
String sql_delete = "delete from user where name = ?";
ps = conn.preparedStatement(sql_delete);
ps.setString(1, "name");
ps.executeUpdate();
conn.commit();//事务提交
}catch(Exception e){
conn.rollback();//遇到异常回滚
}
5.用jsp指令引入另一个jsp文件的语法跟用jsp动作引入另一个文件有什么区别?效果有什么不同?
jsp指令是静态包含,在翻译阶段被包含文件与当前页面一起编译生成一个servlet文件
jsp动作引入是动态包含,如果包含的是静态文件,那么在翻译阶段将被包含文件与当前页面一起编译i成一个servlet文件
如果是动态文件,则把jsp最终编译完成的响应结果包含进来,会有两个servlet文件
6.jsp:forward和response.sendRedirect跳转网页的效果有什么不同?
jsp:forward请求转发到另一个资源,可以携带传递参数,
response.sendRedrect是重定向到另一个资源,不可以携带传递参数,会丢失
7.jsp:userBean、setProperty、getProperty的语法、实现的效果是什么?
<jsp:useBean id = "beananme", class "exe.user", scope = "page|request|session|application">
</jsp:useBean>
//创建一个user实例,并且设置scope范围,如果servlet容器在指定的作用域中找到实例,就可以在jsp中使用,否则就创建一个实例
<jsp:setProperty name = "beanname" property = "*"/>
//设置与请求参数中同名的javabean对象属性值,并自动转换成bean属性的类型,如果某个请求参数的名与bean的类型名不同,那么不会设置
<jsp:setProperty name = "beanname" property = "propertyName"/>
//将请求参数自动转换并设置到bean的同名属性,每次设置一个,如果需要多个,需要使用多次
<jsp:setProperty name = "beanname" property = "propertyName" param = "paramName"/>
//当请求参数不一致时,将参数自动转换并设置为bean的属性值
<jsp:setProperty name = "beanname" property = "propertyName" value= "expression"/>
//使用指定的表达式设置bean属性的值
<jsp:getProperty name = "beanname" property = "propertyNamr">
//读取一个bean的属性的值
8.会用注解配置servlet、用xml配置servlet。
注解配置
@WebServlet(name = "servlet", urlPatterens = "/servlet")
public class servlet extends HttpServlet{}
xml配置
<servlet>
<servlet-name>servlet</servlet-name>
<servlet-class>com.exe.servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name></servlet-name>
<servlet-pattern>/servlet</servlet-pattren>
</servlet-mapping>
9.form表单提交后,在Action对应的网页或servlet中如何读取上一个表单中输入的数据?
<jso:useBean id = "user" class = "exe.user" scope = "session"></jsp:useBean>
<jsp:getProperty property = "name" name = "user"/>
<jsp:getProperty property = "age" name = "user"/>
10.如何把数据放到page、request、session、application中?如何从中取出来?
//request存和区
request.setAttribute("name", "tom");
(String)request.getAttribute("name");
//session对象
HttpSession session = request,getSession();
session.setAttribute()
session.getAttribute()
//application
ServletContext applicaTION = this.getServletContext();
application.set...
application.get....
11.header中设置refresh的用法和效果
实现刷新页面次数用法为 response.setHeader(“refresh”,“刷新时间间隔”);
实现目的页面跳转用法为 response.setHeader(“refresh”,“刷新时间间隔;目的页面地址”);
refresh是使用get方式跳转,url中可以携带参数和数据,比如response.setHeader(“refresh”,“刷新时间间隔;目的页面地址?xx=”);
refresh会刷新当前request请求,使得request.getAttribute的内容为null,如需使用可用Session方法获取。
12.在jsp网页中如何import其他包中的类?
<%@ page import = " " %>
13.EL表达式的作用是什么?如何用EL表达式获取form表单或超链接、地址栏传递的数据? 如何用EL表达式获取放在requst、session、application属性中的数据?语法格式是什么?
el表达式主要来获取jsp作用域中的变量和javabean对象
<jsp:useBean id = “user” class = “packge.user”></jsp:useBean>
<jsp:setProperty Property = “name” name = “user” value = “mike”/>
username = ${user.name}
<%
request.setAttribute("username", "request");
session.setAttribute("username", "session");
application.setAttribute("username", "application");
%>
request_name: ${request.username};
sessionname: ${session.username}
application: ${applicathon.username};
14.如何读取web.xml中的中的数据?
contextConfigLocation contextConfigLocationValue ${initParam.contextConfigLocation}
15.jstl中的常用的几个标签的语法、用法要求熟练掌握,例如c:if、c:set、c:foreach、c:out等。
<c:out value=" "></c:out>
<c:if test = " "></c:if> //test里面为真,则执行里面的语句
<c:set> 用于将变量存取于 JSP 范围中或 JavaBean 属性中。下面的例子中假设已经有 Person.java 这个类文件。
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%@page contentType="text/html; charset=utf-8" %>
<jsp:useBean id="person" class="lihui.Person"></jsp:useBean>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>JSTL测试</title>
</head>
<body>
<c:set value="张三" var="name1" scope="session"></c:set>
<c:set var="name2" scope="session">李四</c:set>
<c:set value="赵五" target="${person}" property="name"></c:set>
<c:set target="${person}" property="age">19</c:set>
<li>从session中得到的值:${sessionScope.name1}</li>
<li>从session中得到的值:${sessionScope.name2}</li>
<li>从Bean中获取对象person的name值:<c:out value="${person.name}"></c:out></li>
<li>从Bean中获取对象person的age值:<c:out value="${person.age}"></c:out></li>
</body>
</html>
<c:remove> 主要用来从指定的 jsp 范围内移除指定的变量。使用类似,下面只给出语法:
<c:remove var="变量名" [scope="page|request|session|application"]></c:remove>
<c:forEach>
语法:<c:forEach var="name" items="Collection" varStatus="statusName" begin="begin" end="end" step="step"></c:forEach>
该标签根据循环条件遍历集合 Collection 中的元素。 var 用于存储从集合中取出的元素;items 指定要遍历的集合;varStatus 用于存放集合中元素的信息。
16.配置过滤器的方法,多个过滤器如何执行?执行的代码顺序
<filter>
<filter-name>filtername</filter-name>
<filter-class>com.exe.filter</filter-class>
</filter>
<filter-mapping>
<filter-name>filtername</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
@WebFilter(filterName = "filtername", values = {"/*"})
按照在xml中部署的顺序执行
过滤器的执行顺序,取决于过滤器在xml中的部署顺序,而且仅仅取决于xml中filter-mapping的顺序。
17.配置监听器的方法,监听器的编写方法
<Listener>
<Listener-class>com.exe.MyServletContextListener
</Listener-class>
</Listener>
public void class MyServletContextListener implements ServletContextListener{
public void contextDestory(ServletContextEvent o){}
public void contextInitialized(ServletContextEvent o){}
}
18.能用jpa编写实体类,编写一对一、一对多关系的是实体类,包括单向的写法、双向的写法
双向一对一
@Entity
public class Person {
private int person_id;
private IDCard person_idcard;
private String person_name;
@GeneratedValue
@Id
public int getPerson_id() {
return person_id;
}
public void setPerson_id(int person_id) {
this.person_id = person_id;
}
@OneToOne(mappedBy = "idcard_person", cascade = CascadeType.REMOVE)
public IDCard getPerson_idcard() {
return person_idcard;
}
public void setPerson_idcard(IDCard person_idcard) {
this.person_idcard = person_idcard;
}
public String getPerson_name() {
return person_name;
}
public void setPerson_name(String person_name) {
this.person_name = person_name;
}
@Override
public String toString() {
return "Person [person_id=" + person_id + ", person_name=" + person_name
+ "]";
}
@Entity
public class IDCard {
private int idcard_id;
private int idcard_number;
private Person idcard_person;
@OneToOne
@JoinColumn(name = "person_id")
public Person getIdcard_person() {
return idcard_person;
}
public void setIdcard_person(Person idcard_person) {
this.idcard_person = idcard_person;
}
@Id
@GeneratedValue
public int getIdcard_id() {
return idcard_id;
}
public void setIdcard_id(int idcard_id) {
this.idcard_id = idcard_id;
}
public int getIdcard_number() {
return idcard_number;
}
public void setIdcard_number(int idcard_number) {
this.idcard_number = idcard_number;
}
@Override
public String toString() {
return "IDCard [idcard_id=" + idcard_id + ", idcard_number=" + idcard_number + ", idcard_person="
+ idcard_person + "]";
}
双向一对多
@Entity
public class Department1 {
private int department_id;
private String department_name;
private List<Employee> employees;
@OneToMany(mappedBy = "employee_department", cascade = CascadeType.REMOVE)
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
@Id
@GeneratedValue
public int getDepartment_id() {
return department_id;
}
public void setDepartment_id(int department_id) {
this.department_id = department_id;
}
public String getDepartment_name() {
return department_name;
}
public void setDepartment_name(String department_name) {
this.department_name = department_name;
}
@Override
public String toString() {
return "Department1 [department_id=" + department_id + ", department_name=" + department_name + ", employees="
+ employees + "]";
}
@Entity
public class Employee {
private int employee_id;
private String employee_name;
private Department1 employee_department;
@Id
@GeneratedValue
public int getEmployee_id() {
return employee_id;
}
public void setEmployee_id(int employee_id) {
this.employee_id = employee_id;
}
public String getEmployee_name() {
return employee_name;
}
public void setEmployee_name(String employee_name) {
this.employee_name = employee_name;
}
@ManyToOne
@JoinColumn( name = "department_id")
public Department1 getEmployee_department() {
return employee_department;
}
public void setEmployee_department(Department1 employee_department) {
this.employee_department = employee_department;
}
@Override
public String toString() {
return "Employee [employee_id=" + employee_id + ", employee_name=" + employee_name + "]";
}
19.能用jsp+servlet+javabean编写完整的登录功能,实现增、删、改、查功能,能将一条数据或多条数据显示到页面中。注意错误处理,在servlet中读取到form提交的数据不合法时,能够保存错误,并转到录入界面,并显示错误信息。
login.jsp
<body>
<form action="login_0" method="post">
账号:<input type="text" name="username"><br>
密码:<input type="test" name="password"><br>
<button type="submit" value="提交" >提交</button>
</form>
</body>
login_0.servlet
@WebServlet("/html/login_0")
public class login_0 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public login_0() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String name = request.getParameter("username");
String password = request.getParameter("password");
User user = new User(name,password);
// HttpSession session = request.getSession();
boolean bool = false;
try {
bool = user.login(user);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(bool==true){
request.setAttribute("user", user);
request.getRequestDispatcher("index.jsp").forward(request, response);
System.out.println("成功");
}else{
response.getWriter().append("Served at: ").append(request.getContextPath());
System.out.println("失败");
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
dbcnonect代码
package exe_0;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBConnection {
private static final String driverName = "com.mysql.jdbc.Driver";
private static final String url = "jdbc:mysql://localhost:3306/testDB?characterEncoding=UTF-8";
private static final String user = "root";
private static final String password = "root";
private DBConnection(){}
static{
try{
Class.forName(driverName);
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
public static Connection getConnection()throws SQLException{
return DriverManager.getConnection(url,user,password);
}
public static void close(ResultSet rs,Statement st,Connection conn){
try{
if(rs!=null){
rs.close();
}
}catch(SQLException e){
e.printStackTrace();
}finally{
try{
if(st!=null){
st.close();
}
}catch(SQLException e){
e.printStackTrace();
}finally{
if(conn!=null){
try{
conn.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}
}
}
}
javabean代码
package exe_0;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import com.sun.xml.internal.bind.v2.schemagen.xmlschema.List;
import exe_0.DBConnection;
public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User(String username, String password) {
super();
this.username = username;
this.password = password;
}
public User() {
super();
}
@Override
public String toString() {
return "User [username=" + username + ", password=" + password + "]";
}
public boolean login(User user) throws SQLException {
PreparedStatement ps = null;
Connection conn = null;
conn = DBConnection.getConnection();
String sql = "select name,password from user where name = ? and password = ?";
ps = conn.prepareStatement(sql);
ps.setString(1, user.getUsername());
ps.setString(2, user.getPassword());
ResultSet rs = ps.executeQuery();
rs.last();
int count = rs.getRow();
if(count==0){
ps.close();
conn.close();
return false;
}else{
ps.close();
conn.close();
return true;
}
}
public int Register(User user) throws SQLException {
PreparedStatement ps = null;
Connection conn = null;
conn = DBConnection.getConnection();
String sql = "insert into user(name,password) values(?,?)";
ps = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
ps.setString(1, user.getUsername());
ps.setString(2, user.getPassword());
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
int id = -1;
if(rs != null && rs.next()){
id = rs.getInt(1);
}
return id;
}
public ArrayList listall() throws SQLException {
PreparedStatement ps = null;
Connection conn = null;
ArrayList<User> list = new ArrayList();
conn = DBConnection.getConnection();
String sql = "select * from user";
ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next()){
User user = new User();
user.setUsername(rs.getString(2));
user.setPassword(rs.getString(3));
list.add(user);
}
return list;
}
}
listall.jsp
@WebServlet("/html/ListAll_0")
public class ListAll_0 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ListAll_0() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
User user = new User();
try {
ArrayList<User> list = user.listall();
request.setAttribute("list", list);
request.getRequestDispatcher("listAll.jsp").forward(request, response);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
listall.jsp
<body>
账户名--------密码
<%
ArrayList<User> users = (ArrayList<User>)request.getAttribute("list");
System.out.print(users);
%><br/>
<c:forEach var="user" items="${list}">
${user.username}--------${user.password}<br/>
</c:forEach>
</body>
20.能用jpa实现增删改查,既能在JavaSE中使用jpa,也能在JavaWeb中使用jpa
双向一对多的增删改查
package Dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import Entity.Classinifo;
import Entity.Department;
public class ClassinifoDao {
public static void add(Classinifo classinifo){
String persistenceUnitName = "jpa_0";
EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnitName);
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.persist(classinifo);
em.getTransaction().commit();
em.close();
emf.close();
}
public static void update(int id, String name){
String persistenceUnitName = "jpa_0";
EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnitName);
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Classinifo classinifo = em.find(Classinifo.class, id);
classinifo.setClassinifo_name(name);
em.merge(classinifo);
em.getTransaction().commit();
em.close();
emf.close();
}
public static void delete(int id){
String persistenceUnitName = "jpa_0";
EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnitName);
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Classinifo classinifo = em.find(Classinifo.class, id);
Department department = em.find(Department.class, classinifo.getClassinifo_department().getDepartment_id());
List list = department.getDepartment_list();
list.remove(classinifo);
em.remove(classinifo);
em.getTransaction().commit();
em.close();
emf.close();
}
}
package Dao;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import Entity.Department;
public class DepartmentDao {
public static void add(Department department){
String persistenceUnitName = "jpa_0";
EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnitName);
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.persist(department);
em.getTransaction().commit();
em.close();
emf.close();
}
public static void update(int id, String name){
String persistenceUnitName = "jpa_0";
EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnitName);
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Department department = em.find(Department.class, id);
department.setDepartment_name(name);
em.merge(department);
em.getTransaction().commit();
em.close();
emf.close();
}
public static void delete(int id){
String persistenceUnitName = "jpa_0";
EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnitName);
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Department department = em.find(Department.class, id);
em.remove(department);
em.getTransaction().commit();
em.close();
emf.close();
}
}