В настоящее время я новичок в веб-приложении, мой лектор попросил меня создать простое веб-приложение, использующее класс bean-компонента и убедиться, что оно может подключаться к базе данных.
Это мой код
register.jsp
<!DOCTYPE html>
<html>
<head>
<title>Register Page</title>
<style type="text/css">
header, section, footer, aside, nav, article, figure, figcaption {
display: block;
}
body{
background: url("img_pr/ayamayam.jpg")no-repeat center center fixed #000;
font-family: "Lucida Sans Unicode";
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;background-size: cover;
}
.wrapper {
font-family: "Lucida Sans Unicode";
text-align: center;
width: 940px;
height: auto;
margin: 200px auto 100px auto;
border: 8px solid #000000;
background-color: orange;
color: #ffffff;
}
section.courses{
text-align: center;
width: 659px;
border-right: 1px solid #eeeeee;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="courses">
<h1>Register Page</h1>
<hr>
<h3>Please fill your information:</h3>
<form action="RegisterController" >
<br>
<center>
<table>
<tr>
<td>Name</td>
<td>: <input type="text" name="name"></td>
</tr>
<tr>
<td>Username</td>
<td>: <input type="text" name="username"></td>
</tr>
<tr>
<td>Password</td>
<td>: <input type="password" name="pass"></td>
</tr>
<tr>
<td colspan="2"><center><h5>*password in alphanumeric</h5></center></td>
</tr>
</table>
<input type="submit" value="Register">
</center>
</form>
</div>
</div>
</body>
RegisterController.java
import java.io.*;
import java.util.logging.*;
import javax.servlet.http.*;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
@WebServlet(urlPatterns = {"/RegisterController"})
public class RegisterController extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException, ClassNotFoundException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
String name = request.getParameter("name");
String username = request.getParameter("username");
String pass = request.getParameter("pass");
String address = "Main_page.jsp";
RegisterBean member = new RegisterBean();
member.setName(name);
member.setPass(pass);
member.setUsername(username);
member.AddUser();
request.setAttribute("member", member);
RequestDispatcher dispatcher = request.getRequestDispatcher(address);
dispatcher.forward(request, response);
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(RegisterController.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(RegisterController.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
RegisterBean.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class RegisterBean {
private final String myDrive = "com.mysql.jdbc.Driver";
private final String myUrl = "jdbc:mysql://localhost:3306/ayam";
private final String Query = "insert into member values(?,?,?)";
private Connection connect = null;
private PreparedStatement preparedStatement = null;
public RegisterBean() throws ClassNotFoundException, SQLException{
Class.forName(myDrive);
connect = DriverManager.getConnection(myUrl, "root", "pass");
}
private String username,pass, name;
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPass() {
return this.pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public void AddUser() throws SQLException{
preparedStatement = connect.prepareStatement(Query);
preparedStatement.setString(1, name);
preparedStatement.setString(2, username);
preparedStatement.setString(3, pass);
preparedStatement.execute();
}
}
Main_page.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Ayam.CO</title>
<style>
header, section, footer, aside, nav, article, figure, figcaption {
display: block;
}
body{
background: url("img_pr/ayamayam.jpg")no-repeat center center fixed #000;
background-repeat: no-repeat; /*this line keeps the image from being repeated*/
font-family: "Lucida Sans Unicode";
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;background-size: cover;
}
.wrapper {
width: 940px;
margin: 100px auto 200px auto;
border: 2px #000000;
background-color: #ffffff;
}
#logo{
margin-left: 0px;
margin-right: 10px;
}
h1{
text-indent: -9999px;
width: 940px;
height: 130px;
margin: 0px;
}
footer{
clear: both;
color: #3f8aff;
background-color: black;
height: 50px;
text-align:left;
background:black;
}
nav{
clear: both;
color: #ffffff;
background-color:black ;
height: 50px;
text-align: center;
background: black;
}
nav ul{
margin: 0px;
padding: 0px 0px 0px 0px;
}
nav li {
display: inline;
margin-right: 20px;
padding: 15px 15px 15px 15px;
}
nav li a{
color: #3f8aff;
}
nav li a:hover, nav li a.current {
color: orange;
}
#menu1:hover{
background: black;
padding: 15px 15px 15px 15px;
}
#menu2:hover{
background: black;
padding: 15px 15px 15px 15px;
}
#menu3:hover{
background: black;
padding: 15px 15px 15px 15px;
}
#menu4:hover{
background: black;
padding: 15px 15px 15px 15px;
}
#menu5:hover{
background: black;
padding: 15px 15px 15px 15px;
}
section.courses{
float: left;
width: 659px;
border-right: 1px solid #eeeeee;
}
article{
clear: both;
overflow: auto;
width: 100%;
}
hgroup{
margin-top: 40px;
}
figure {
float: left;
width: 290px;
height: 220px;
padding: 5px;
margin: 20px;
border: 1px solid #eeeeee;
}
figcaption {
font-size: 90%;
text-align: left;}
aside {
width: 230px;
float: none;
padding: 0px 0px 0px 20px;}
aside section a {
display: block;
padding: 10px;
border-bottom: 1px solid #eeeeee;}
aside section a:hover {
color: #985d6a;
background-color: #efefef;}
a {
color: #de6581;
text-decoration: none;}
h1, h2, h3 {
font-weight: normal;}
h2 {
margin: 10px 0px 5px 0px;
padding: 0px;}
h3 {
margin: 0px 0px 10px 0px;
color: #de6581;}
aside h2 {
padding: 30px 0px 10px 0px;
color: #de6581;}
footer {
font-size: 80%;
padding: 7px 0px 0px 20px;}
#ico
{
float: right;
margin: auto 13px auto 10px;
}
.btndiv
{
display: flex;
align-items:center;
text-align: center;
justify-content: center;
background: orange;
}
#playbtn {
width: 15%;
background-color: #0c2f68;
color: #3f8aff;
padding: 14px 20px;
margin: 8px 0;
border: solid;
border-radius: 4px;
cursor: pointer;
}
#playbtn:hover {
background-color: black;
}
/*This below CSS is for Image Slider */
* {box-sizing:border-box}
/* Slideshow container */
.slideshow-container {
max-width: 1000px;
position: relative;
margin: auto;
}
/* Hide the images by default */
.mySlides {
display: none;
}
#exception
{
display: inherit;
}
/* Next & previous buttons */
.prev, .next {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
margin-top: -22px;
padding: 16px;
color: white;
font-weight: bold;
font-size: 18px;
transition: 0.6s ease;
border-radius: 0 3px 3px 0;
}
/* Position the "next button" to the right */
.next {
right: 0;
border-radius: 3px 0 0 3px;
}
/* On hover, add a black background color with a little bit see-through */
.prev:hover, .next:hover {
background-color: rgba(0,0,0,0.8);
}
/* Caption text */
.text {
color: #f2f2f2;
font-size: 15px;
padding: 8px 12px;
position: absolute;
bottom: 8px;
width: 100%;
text-align: center;
}
/* Number text (1/3 etc) */
.numbertext {
color: #f2f2f2;
font-size: 12px;
padding: 8px 12px;
position: absolute;
top: 0;
}
/* The dots/bullets/indicators */
.dot {
cursor:pointer;
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
transition: background-color 0.6s ease;
}
.active, .dot:hover {
background-color: #717171;
}
/* Fading animation */
.fade {
-webkit-animation-name: fade;
-webkit-animation-duration: 1.5s;
animation-name: fade;
animation-duration: 1.5s;
}
#dotdiv
{
background-color: black;
}
@-webkit-keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
@keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
#slide
{
background: black;
}
/*until here is the CSS for Slider */
</style>
<script type="text/javascript">
//Below is Javascript for Slider
var slideIndex = 1;
showSlides(slideIndex);
// Next/previous controls
function plusSlides(n) {
showSlides(slideIndex += n);
}
// Thumbnail image controls
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n)
{
var i;
var slides = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("dot");
if (n > slides.length) {slideIndex = 1}
if (n < 1) {slideIndex = slides.length}
for (i = 0; i < slides.length; i++)
{
slides[i].style.display = "none";
}
for (i = 0; i < dots.length; i++)
{
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex-1].style.display = "block";
dots[slideIndex-1].className += " active";
}
//until here is for Javascript
//Below is for autoslide
/**
var slideIndex = 0;
showSlides();
function showSlides() {
var i;
var slides = document.getElementsByClassName("mySlides");
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
slideIndex++;
if (slideIndex > slides.length) {slideIndex = 1}
slides[slideIndex-1].style.display = "block";
setTimeout(showSlides, 6000); // Change image every 6 seconds
}
**/
//End here for autoslide
</script>
</head>
<body>
<div class="wrapper">
<div class="header">
<nav>
<ul>
<li id="logo"><a href="Main_page.jsp"><img src="img_pr/logo.jpg" height=50px></a></li>
<li id="menu3"><a href="LatestUpdate_page.jsp">UPDATES</a></li>
<li id="menu5"><a href="JoinUs_page.jsp">JOIN US</a></li>
</ul>
</nav>
</div>
<!-- Slideshow container -->
<div id="slide" class="slideshow-container">
<!-- Full-width images with number and caption text -->
<div id="exception" class="mySlides fade">
<div class="numbertext">1 / 3</div>
<img src="img_pr/1.jpg" style="width:100%"></a>
<div class="text">LEG</div>
</div>
<div class="mySlides fade">
<div class="numbertext">2 / 3</div>
<img src="img_pr/2.jpg" style="width:100%"></a>
<div class="text">THIGHT</div>
</div>
<div class="mySlides fade">
<div class="numbertext">3 / 3</div>
<img src="img_pr/3.jpg" style="width:100%"></a>
<div class="text">BREAST</div>
</div>
<!-- Next and previous buttons -->
<a class="prev" onclick="plusSlides(-1)">❮</a>
<a class="next" onclick="plusSlides(1)">❯</a>
</div>
<!-- The dots/circles -->
<div id="dotdiv" style="text-align:center">
<span class="dot" onclick="currentSlide(1)"></span>
<span class="dot" onclick="currentSlide(2)"></span>
<span class="dot" onclick="currentSlide(3)"></span>
</div>
<div class="btndiv">
<button id="playbtn" type="button" name="button" onclick="window.location.href='https://www.tasteofhome.com/collection/ways-to-cook-boneless-skinless-chicken-breasts/view-all/'">GO NOW!</button>
</div>
<footer>
CONTACT US : 012-345 6789
<a href="http://twitter.com/"> <img id="ico" src="img_pr/twitter_ico.png" width="25px" height="27px"></a> <a href="http://facebook.com/"><img id="ico" src="img_pr/FB_ico_1.png" width="25px" height="27px"></a> <a href="https://mail.google.com/mail/u/0/#inbox"><img id="ico" src="img_pr/email.png" width="28px" height="25px"></a>
</footer>
</div><!-- .wrapper -->
</body>
Проблема, с которой я сейчас сталкиваюсь, заключается в том, что я не вижу в чем дело, потому что, когда я пытался запустить его, но сразу после того, как я заполнилформа, он не будет перенаправлен на главную страницу.Он будет отображать только пустую страницу.Прямо сейчас я просто следую примеру, который дал мой лектор.
Вот вопросы, которые я хочу задать:
1) Что не так с моими кодами?
2) Какова функция класса бина?
3) Что такое функция RequestDispatcher?
4) Как мне подключиться к базе данных?
У меня очень мало знанийна веб-приложение, так что будь осторожен со мной, пожалуйста