请求数据分为3部分:
案例:
@WebServlet("/req1")
public class RequestDemo1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getMethod();
System.out.println(method);
String contextPath = req.getContextPath();
System.out.println(contextPath);
StringBuffer url = req.getRequestURL();
System.out.println(url);
String uri = req.getRequestURI();
System.out.println(uri);
String queryString = req.getQueryString();
System.out.println(queryString);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
@WebServlet("/req1")
public class RequestDemo1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getMethod();
System.out.println(method);
String contextPath = req.getContextPath();
System.out.println(contextPath);
StringBuffer url = req.getRequestURL();
System.out.println(url);
String uri = req.getRequestURI();
System.out.println(uri);
String queryString = req.getQueryString();
System.out.println(queryString);
//获取请求头:uer-getHeader:浏览器的版本信息
String agent = req.getHeader("user-agent");
System.out.println(agent);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
3、请求体:
案例:
RequestDemo1类:
@WebServlet("/req1")
public class RequestDemo1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getMethod();
System.out.println(method);
String contextPath = req.getContextPath();
System.out.println(contextPath);
StringBuffer url = req.getRequestURL();
System.out.println(url);
String uri = req.getRequestURI();
System.out.println(uri);
String queryString = req.getQueryString();
System.out.println(queryString);
//获取请求头:uer-getHeader:浏览器的版本信息
String agent = req.getHeader("user-agent");
System.out.println(agent);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取post 请求体:请求参数
//1.获取字符输入流
BufferedReader br = req.getReader();//该流会自动关闭
//2.读取数据
String line = br.readLine();
System.out.println(line);
}
}
req.html:
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<form action="/request_demo_war/req1" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit">
form>
body>
html>
请求参数获取方式:
String getQueryString()
BufferedReader getReader()
思考:
GET请求方式和POST请求方式区别主要在于获取请求参数的方式不一样,是否可以提供一种统一获取请求参数的方式,从而统一doGet和doPost方法内的代码?
Map
:获取所有参数Map集合getParameterMap() String[ ] getParameterValues(String name)
︰根据名称获取参数值(数组)String getParameter(String name)
:根据名称获取参数值(单个值)
案例:
RequestDemo2类:
package com.itheima.web;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;
@WebServlet("/req2")
public class RequestDemo2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//get请求逻辑
// System.out.println("get....");
//1.获取所有参数的map集合
Map<String, String[]> map = req.getParameterMap();
for (String key : map.keySet()) {
//比如:username:zhangsan
System.out.print(key+":");
//获取value值
String[] values = map.get(key);
for (String value : values) {
System.out.print(value+" ");
}
System.out.println();
}
System.out.println("----------------------------");
//2.根据key获取参赛值,数组
String[] hobbies = req.getParameterValues("hobby");
for (String hobby : hobbies) {
System.out.println(hobby);
}
//3.根据key 获取单个参数值
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println(username);
System.out.println(password);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取post 请求体:请求参数
this.doGet(req,resp);//一样法典复用即可
// System.out.println("post....");
//
// //1.获取所有参数的map集合
// Map map = req.getParameterMap();
// for (String key : map.keySet()) {
// //比如:username:zhangsan
// System.out.print(key+":");
//
// //获取value值
// String[] values = map.get(key);
// for (String value : values) {
// System.out.print(value+" ");
// }
// System.out.println();
// }
// System.out.println("----------------------------");
//
// //2.根据key获取参赛值,数组
// String[] hobbies = req.getParameterValues("hobby");
// for (String hobby : hobbies) {
// System.out.println(hobby);
// }
//
// //3.根据key 获取单个参数值
// String username = req.getParameter("username");
// String password = req.getParameter("password");
// System.out.println(username);
// System.out.println(password);
}
}
html:
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<form action="/request_demo_war/req2" method="get">
<input type="text" name="username"><br>
<input type="password" name="password"><br>
<input type="checkbox" name="hobby" value="1">游水
<input type="checkbox" name="hobby" value="2">开冲<br>
<input type="submit">
form>
body>
html>
URL编码
演示UTF编码转换:
public class URLDemo {
public static void main(String[] args) throws UnsupportedEncodingException {
String username = "张三";
//1.URL编码
String encode = URLEncoder.encode(username, "utf-8");
System.out.println(encode);
//2.URL编码
String decode = URLDecoder.decode(encode, "utf-8");
String decode2 = URLDecoder.decode(encode, "ISO-8859-1");//å¼ ä¸‰
System.out.println(decode);
}
}
解决思路:
package com.itheima.web;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
public class URLDemo {
public static void main(String[] args) throws UnsupportedEncodingException {
String username = "张三";
//1.URL编码
String encode = URLEncoder.encode(username, "utf-8");
System.out.println(encode);
//2.URL编码
String decode = URLDecoder.decode(encode, "ISO-8859-1");//å¼ ä¸‰
System.out.println(decode);
//3.转换为字节数据,编码过程
byte[] bytes = decode.getBytes("ISO-8859-1");
//4.将字节数组转换为字符串,解码过程
String s = new String(bytes, "utf-8");
System.out.println(s);
}
}
请求参数如果存在中文数据,则会乱码
解决方案:
request.setCharacterEncoding("UTF-8");
案例:
@WebServlet("/req4")
public class RequestDemo4 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.解决乱码:POST getReader()
request.setCharacterEncoding("UTF-8");//设置字符输入流的参数
//2.获取username
String username = request.getParameter("username");
System.out.println(username);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
@WebServlet("/req4")
public class RequestDemo4 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.解决乱码:POST getReader()
request.setCharacterEncoding("UTF-8");//设置字符输入流的参数
//2.获取username
String username = request.getParameter("username");
System.out.println("解决乱码前:"+username);
//3.GET 获取参数的方式:getQueryString
//乱码原因:tomcat进行URL解码时,默认的字符集ISO-8859-1
//3.1 先对乱码数据进行解码:转为字节数组
// byte[] bytes = username.getBytes(StandardCharsets.ISO_8859_1);
//3.2 字节数组解码
username = new String(username.getBytes(StandardCharsets.ISO_8859_1),StandardCharsets.UTF_8);
System.out.println("解决乱码后:"+username);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
小结:
req.getRequestDispatcher("资源B路径").forward(req,resp);
案例:
RequestDemo5类:
@WebServlet("/req5")
public class RequestDemo5 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("demo5...");
//请求转发
request.getRequestDispatcher("/req6").forward(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
RequestDemo6类:
@WebServlet("/req6")
public class RequestDemo6 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Demo6....");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
请求转发资源共享数据:使用Request对象
案例:
@WebServlet("/req5")
public class RequestDemo5 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("demo5...");
//存储数据
request.setAttribute("msg","helloworld");
//请求转发
request.getRequestDispatcher("/req6").forward(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
@WebServlet("/req6")
public class RequestDemo6 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Demo6....");
//获取数据
Object msg = request.getAttribute("msg");
System.out.println(msg);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
请求转发的特点:
响应数据分为3部分:
1、响应行:HTTP/1.1 200 oK
2、响应头: Content-Type: text/html
3、响应体: head>
案例:
ResponseDemo1类:
@WebServlet("/resp1")
public class ResponseDemo1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("resp1......");
//重定向
//1.设置响应状态码302
response.setStatus(302);
//2.设置响应头 Location
// response.setHeader("Location","/request_demo_war/resp2"); request_demo_war为自己的启动目录
//简化方式完成重定向
response.sendRedirect("/request_demo_war/resp2");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
ResponseDemo2类:
@WebServlet("/resp2")
public class ResponseDemo2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("resp2......");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
明确路径谁使用?
例如:
@WebServlet("/resp1")
public class ResponseDemo1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("resp1......");
//重定向
//1.设置响应状态码302
response.setStatus(302);
//2.设置响应头 Location
// response.setHeader("Location","/request_demo_war/resp2"); request_demo_war为自己的启动目录
//简化方式完成重定向
//动态获取虚拟目录
String contextPath = request.getContextPath();
response.sendRedirect(contextPath+"/resp2");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
使用:
PrintWriter writer = resp.getWriter();
writer.write("aaa");
例子:
@WebServlet("/resp3")
public class ResponseDemo3 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置流中文编码
response.setContentType("text/html;charset=utf-8");
//1.获取字符输入流
PrintWriter writer = response.getWriter();
//content-type 识别html标签
// response.setHeader("content-type","text/html");
writer.write("你吗的");
writer.write("aaaa
");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
注意:
- 该流不需要关闭,随着响应结束,response对象销毁,由服务器关闭
- 中文数据乱码:原因通过Response获取的字符输出流默认编码:ISO-8859-1
resp.setContentType("text/html;charset=utf-8");
使用:
ServletOutputStream outputStream = resp.getOutputStream();
outputStream.write(字节数据);
例子:
@WebServlet("/resp4")
public class ResponseDemo4 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.读取文件
FileInputStream fis = new FileInputStream("F://常用文件夹//图片//Saved Pictures//1.jpg");
//2.获取response字节输出流
ServletOutputStream os = response.getOutputStream();
//3.完成流的copy
byte[] buff = new byte[1024];
int len = 0;
while ((len = fis.read(buff))!=-1){
os.write(buff,0,len);
}
fis.close();
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
但是将来不用写完成copy流的步骤了,太麻烦,一般会采用工具类
<dependency>
<groupld>commons-iogroupld>
<artifactld>commons-ioartifactld>
<versign>2.6version>
dependency>
使用:
IOUtils.copy(输入流,输出流);
* {
margin: 0;
padding: 0;
}
html {
height: 100%;
width: 100%;
overflow: hidden;
margin: 0;
padding: 0;
background: url(../imgs/Desert.jpg) no-repeat 0px 0px;
background-repeat: no-repeat;
background-size: 100% 100%;
-moz-background-size: 100% 100%;
}
body {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
}
#loginDiv {
width: 37%;
display: flex;
justify-content: center;
align-items: center;
height: 300px;
background-color: rgba(75, 81, 95, 0.3);
box-shadow: 7px 7px 17px rgba(52, 56, 66, 0.5);
border-radius: 5px;
}
#name_trip {
margin-left: 50px;
color: red;
}
p {
margin-top: 30px;
margin-left: 20px;
color: azure;
}
input {
margin-left: 15px;
border-radius: 5px;
border-style: hidden;
height: 30px;
width: 140px;
background-color: rgba(216, 191, 216, 0.5);
outline: none;
color: #f0edf3;
padding-left: 10px;
}
#username{
width: 200px;
}
#password{
width: 202px;
}
.button {
border-color: cornsilk;
background-color: rgba(100, 149, 237, .7);
color: aliceblue;
border-style: hidden;
border-radius: 5px;
width: 100px;
height: 31px;
font-size: 16px;
}
#subDiv {
text-align: center;
margin-top: 30px;
}
#loginMsg{
text-align: center;color: aliceblue;
}
* {
margin: 0;
padding: 0;
list-style-type: none;
}
.reg-content{
padding: 30px;
margin: 3px;
}
a, img {
border: 0;
}
body {
background-image: url("../imgs/reg_bg_min.jpg") ;
text-align: center;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
td, th {
padding: 0;
height: 90px;
}
.inputs{
vertical-align: top;
}
.clear {
clear: both;
}
.clear:before, .clear:after {
content: "";
display: table;
}
.clear:after {
clear: both;
}
.form-div {
background-color: rgba(255, 255, 255, 0.27);
border-radius: 10px;
border: 1px solid #aaa;
width: 424px;
margin-top: 150px;
margin-left:1050px;
padding: 30px 0 20px 0px;
font-size: 16px;
box-shadow: inset 0px 0px 10px rgba(255, 255, 255, 0.5), 0px 0px 15px rgba(75, 75, 75, 0.3);
text-align: left;
}
.form-div input[type="text"], .form-div input[type="password"], .form-div input[type="email"] {
width: 268px;
margin: 10px;
line-height: 20px;
font-size: 16px;
}
.form-div input[type="checkbox"] {
margin: 20px 0 20px 10px;
}
.form-div input[type="button"], .form-div input[type="submit"] {
margin: 10px 20px 0 0;
}
.form-div table {
margin: 0 auto;
text-align: right;
color: rgba(64, 64, 64, 1.00);
}
.form-div table img {
vertical-align: middle;
margin: 0 0 5px 0;
}
.footer {
color: rgba(64, 64, 64, 1.00);
font-size: 12px;
margin-top: 30px;
}
.form-div .buttons {
float: right;
}
input[type="text"], input[type="password"], input[type="email"] {
border-radius: 8px;
box-shadow: inset 0 2px 5px #eee;
padding: 10px;
border: 1px solid #D4D4D4;
color: #333333;
margin-top: 5px;
}
input[type="text"]:focus, input[type="password"]:focus, input[type="email"]:focus {
border: 1px solid #50afeb;
outline: none;
}
input[type="button"], input[type="submit"] {
padding: 7px 15px;
background-color: #3c6db0;
text-align: center;
border-radius: 5px;
overflow: hidden;
min-width: 80px;
border: none;
color: #FFF;
box-shadow: 1px 1px 1px rgba(75, 75, 75, 0.3);
}
input[type="button"]:hover, input[type="submit"]:hover {
background-color: #5a88c8;
}
input[type="button"]:active, input[type="submit"]:active {
background-color: #5a88c8;
}
.err_msg{
color: red;
padding-right: 170px;
}
#password_err,#tel_err{
padding-right: 195px;
}
#reg_btn{
margin-right:50px; width: 285px; height: 45px; margin-top:20px;
}
HTML部分:
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>logintitle>
<link href="css/login.css" rel="stylesheet">
head>
<body>
<div id="loginDiv">
<form action="" id="form">
<h1 id="loginMsg">LOGIN INh1>
<p>Username:<input id="username" name="username" type="text">p>
<p>Password:<input id="password" name="password" type="password">p>
<div id="subDiv">
<input type="submit" class="button" value="login up">
<input type="reset" class="button" value="reset">
<a href="register.html">没有账号?点击注册a>
div>
form>
div>
body>
html>
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>欢迎注册title>
<link href="css/register.css" rel="stylesheet">
head>
<body>
<div class="form-div">
<div class="reg-content">
<h1>欢迎注册h1>
<span>已有帐号?span> <a href="login.html">登录a>
div>
<form id="reg-form" action="#" method="get">
<table>
<tr>
<td>用户名td>
<td class="inputs">
<input name="username" type="text" id="username">
<br>
<span id="username_err" class="err_msg" style="display: none">用户名不太受欢迎span>
td>
tr>
<tr>
<td>密码td>
<td class="inputs">
<input name="password" type="password" id="password">
<br>
<span id="password_err" class="err_msg" style="display: none">密码格式有误span>
td>
tr>
table>
<div class="buttons">
<input value="注 册" type="submit" id="reg_btn">
div>
<br class="clear">
form>
div>
body>
html>
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<form action="/request_demo_war/req4" method="get">
<input type="text" name="username"><br>
<input type="password" name="password"><br>
<input type="checkbox" name="hobby" value="1">游水
<input type="checkbox" name="hobby" value="2">开冲<br>
<input type="submit">
form>
body>
html>
package com.itheima.pojo;
public class User {
private Integer id;
private String username;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
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;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.dorg/dt/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="com.itheima.pojo"/>
typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///db1?useSSL=false&useServerPrepStmts=true"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
dataSource>
environment>
environments>
<mappers>
<package name="com.itheima.mapper"/>
mappers>
configuration>
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.mapper.UserMapper">
mapper>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>org.examplegroupId>
<artifactId>request-demoartifactId>
<version>1.0-SNAPSHOTversion>
<packaging>warpackaging>
<properties>
<maven.compiler.source>17maven.compiler.source>
<maven.compiler.target>17maven.compiler.target>
properties>
<dependencies>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.1.0version>
<scope>providedscope>
dependency>
<dependency>
<groupId>commons-iogroupId>
<artifactId>commons-ioartifactId>
<version>2.6version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.5version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.30version>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.mavengroupId>
<artifactId>tomcat7-maven-pluginartifactId>
<version>2.2version>
<configuration>
<port>85port>
configuration>
plugin>
plugins>
build>
project>
package com.itheima.mapper;
import com.itheima.pojo.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
public interface UserMapper {
/*
根据用户名和密码查询用户对象
*/
@Select("select * from tb_user where username = #{username} and password = #{password}")
User select(@Param("username") String username,@Param("password") String password);
}
loginServlet:
@WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.接收用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
//2.调用mybatis完成查询
//2.1 获取SqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.2 获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//2.3 获取Mapper
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//2.4 调用方法
User user = userMapper.select(username, password);
//2.5 释放资源
sqlSession.close();
//获取响应数据的字符输出流,并设置content type 防止乱码
response.setContentType("text/html;charset=utf-8");
PrintWriter Pwriter = response.getWriter();
//3.判断user释放为null
if (user!=null){
// 登录成功
Pwriter.write("登录成功");
}else {
// 登录失败
Pwriter.write("登录失败");
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
package com.itheima.mapper;
import com.itheima.pojo.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
public interface UserMapper {
/*
根据用户名和密码查询用户对象
*/
@Select("select * from tb_user where username = #{username} and password = #{password}")
User select(@Param("username") String username,@Param("password") String password);
/*
根据用户名查询用户对象
*/
@Select("select * from tb_user where username = #{username}")
User selectByUsername(String username);
//添加用户
@Insert("insert into tb_user values(null,#{username},#{password})")
void add(User user);
}
@WebServlet("/registerServlet")
public class registerServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.接收用户数据
String username = request.getParameter("username");
String password = request.getParameter("password");
//封装用户对象
User user = new User();
user.setUsername(username);
user.setPassword(password);
//2. 调用mapper 根据用户名查询用户对象
//2.1 获取SqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.2 获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//2.3 获取Mapper
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//2.4 调用方法
User u = userMapper.selectByUsername(username);
//3.判断用户对象释放是否为null
if (u == null){
//用户不存在,添加用户
userMapper.add(user);
//提交事务
sqlSession.commit();
//释放资源
sqlSession.close();
}else {
//用户存在,给出提示信息
response.setContentType("text/html;charset=utf-8");
response.getWriter().write("用户名已存在");
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>欢迎注册title>
<link href="css/register.css" rel="stylesheet">
head>
<body>
<div class="form-div">
<div class="reg-content">
<h1>欢迎注册h1>
<span>已有帐号?span> <a href="login.html">登录a>
div>
<form id="reg-form" action="/request-demo/registerServlet" method="post">
<table>
<tr>
<td>用户名td>
<td class="inputs">
<input name="username" type="text" id="username">
<br>
<span id="username_err" class="err_msg" style="display: none">用户名不太受欢迎span>
td>
tr>
<tr>
<td>密码td>
<td class="inputs">
<input name="password" type="password" id="password">
<br>
<span id="password_err" class="err_msg" style="display: none">密码格式有误span>
td>
tr>
table>
<div class="buttons">
<input value="注 册" type="submit" id="reg_btn">
div>
<br class="clear">
form>
div>
body>
html>
存在问题:
案例:
在itheima下的util包创建:SqlSessionFactoryUtils类
public class SqlSessionFactoryUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
//静态代码块会随着类的加载而自动执行,且只执行一次
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSessionFactory getSqlSessionFactory(){
return sqlSessionFactory;
}
}