When I use Beanutils in a servlet, I find that this doesn't work
package servlet.web15;
import org.apache.commons.beanutils.BeanUtils; 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.IOException;
import java.io.PrintWriter; import
java.lang.reflect.InvocationTargetException; import java.util.HashMap;
import java.util.Map;
#WebServlet(name = "RegisterServlet", urlPatterns = "/register")
public class RegisterServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter responseWriter = response.getWriter();
Map<String, String[]> parameterMap = request.getParameterMap();
for (Map.Entry<String, String[]> entry :
parameterMap.entrySet()) {
String name = entry.getKey();
for (String str :
entry.getValue()) {
responseWriter.println(name + ": " + str);
}
}
Bean bean = new Bean();
responseWriter.println(bean.toString());
try {
BeanUtils.populate(bean, parameterMap);
} catch (IllegalAccessException e) {
responseWriter.println(e.getCause());
} catch (InvocationTargetException e) {
responseWriter.println(e.getCause());
}
responseWriter.println(bean.toString()); // this statement doesn't work, something wrong with the try and catch
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
and the html snippet is like this
<div class="form form-signup">
<form action="/register" method="post">
<lable>FULL NMAE</lable>
<input type="text"
placeholder="Your full name" name="name">
<lable>E-MAIL</lable>
<input type="email"
placeholder="Your e-mail" name="email">
<lable>PASSWORD</lable>
<input type="password"
placeholder="Your password" name="password">
<p class="terms">
<input type="checkbox">
I agree all statments in
terms of service
</p>
<input type="submit"
class="form-btn"
value="Sign Up"/>
I'm already member
</form>
</div>
this is Bean.class
package servlet.web15;
public class Bean {
private String name;
private String email;
private String password;
public Bean() {
}
public Bean(String name, String email, String password) {
this.name = name;
this.email = email;
this.password = password;
}
#Override
public String toString() {
return "Bean{" +
"name='" + name + '\'' +
", email='" + email + '\'' +
", password='" + password + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
so I try to find something help, and then , I was told this is a bug in this.
So I did it according to the contents of the link, I modified the contents of the plugin folder, but this does not work, and my idea was broken up.
how do i fix this problem?
Tomcat version: 9.0.12
ps: the error message was same as that link. it like
11-Apr-2017 18:20:06.973 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory C:\servers\apache-tomcat-8.5.13\webapps\manager
11-Apr-2017 18:20:07.084 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory C:\servers\apache-tomcat-8.5.13\webapps\manager has finished in 112 ms
Related
I am trying to get the values from a form in order to create an object with those values. How would I do this? Also currently when I hit submit I get the http 404 error. I know I'm doing this wrong, I just don't know how to fix it!
I have created the form with the following code:
<html lang="en">
<head>
<title>Example</title>
</head>
<body>
<h1>Welcome to Loggy!</h1>
<form id="logForm" action="LogsServlet" method="GET">
<h3>What have you been up to today?</h3>
<br>
<label id="logTitleLabel" for="logTitle">Title :</label>
<br>
<input type="text" id="logTitle" name="logTitle">
<br>
<label id="logDescriptionLabel" for="LogDescription">Description</label>
<br>
<input type="text" id="logDescription" name="logDescription">
<label id="logContentLabel" for="logContent">Content :</label>
<br>
<input type="text" id="logContent" name="logContent">
<button type="submit" id="submitLog">Submit Log</button>
</form>
</body>
</html>
Here are the abstract Log Class and TextLog Class:
import java.sql.Timestamp;
import java.util.Date;
import java.util.UUID;
public abstract class Log {
private UUID id;
private String title;
private String description;
private String content;
private Timestamp createTimestamp;
//Constructor
Log(String title,String description, String content){
this.setTitle(title);
this.description=description;
this.content=content;
};
public void create() {
//call UUID method
id();
//create new timeStamp
Date date= new Date();
Timestamp createTimestamp = new Timestamp(date.getTime());
this.createTimestamp=createTimestamp;
}
public UUID id() {
UUID uuid = UUID.randomUUID();
id = uuid;
return id;
}
//GETTERS AND SETTERS
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Timestamp getCreateTimestamp() {
return createTimestamp;
}
public void setCreateTimestamp(Timestamp createTimestamp) {
this.createTimestamp = createTimestamp;
}
}
public class TextLog extends Log {
public TextLog(String title,String description, String content) {
super(title,description, content);
}
}
I am trying to get the values from the form and then create a Log object of type TextLog with the variables submitted in the form. Here is my Servlet:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LogsServlet
*/
//#WebServlet(description = "Loggy Logs", urlPatterns = { "/LogsServlet" })
public class LogsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public LogsServlet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//set content type
response.setContentType("text/html");
//get print writer
PrintWriter writer = response.getWriter();
//generate content
request.getParameter("logTitle");
request.getParameter("logDescription");
request.getParameter("logContent");
}
}
This is the first time I have worked with this, and I am quite lost of how to set it! I will also have to display the object in a list after and add it to a database if that makes a difference.
Any advice would be appreciated!
This is a common issue on Tomcat 10 because the change from Java EE to Jakarta EE, so you can change your project, using Jakarta EE 9
<dependency>
<groupId>jakarta.platform</groupId>
<artifactId>jakarta.jakartaee-api</artifactId>
<version>9.0.0</version>
<scope>provided</scope>
</dependency>
and importing this packages
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
If you don´t want do that, you can downgrade to Tomcat 9. Don´t forget uncomment
//#WebServlet(description = "Loggy Logs", urlPatterns = { "/LogsServlet" })
For related documentation follow this link
Tomcat 10.0.4 doesn't load servlets (#WebServlet classes) with 404 error
Logs:
2021-05-09 14:04:19.356 ERROR 22211 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException: Cannot invoke "com.dzeru.springloginformandoauth2tutorial.repos.PostRepo.save(Object)" because "this.postRepo" is null] with root cause
My PostMakerController
package com.dzeru.springloginformandoauth2tutorial.controllers;
import com.dzeru.springloginformandoauth2tutorial.entities.Post;
import com.dzeru.springloginformandoauth2tutorial.repos.PostRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
#Controller
public class PostMakerController {
#Autowired
private PostRepo postRepo;
public static List<Post> posts = new ArrayList<>();
#PostMapping("/prj")
public String makePost(String title, String content,
Principal principal, Model model) {
int wordsLength = content.split(" ").length;
if (title.length() > 30) {
model.addAttribute("text", "Title size > 30");
} else if (wordsLength < 30) {
model.addAttribute("text", "Your content < 30 words");
} else if (wordsLength > 100) {
model.addAttribute("text", "Your content > 100 words");
} else {
Post post = new Post();
post.setContent(content);
post.setAuthor(principal.getName());
post.setParagraph(title);
postRepo.save(post);
posts = postRepo.findAll();
model.addAttribute("posts", posts);
return "prj";
}
return "prj";
}
}
My PostRepo
package com.dzeru.springloginformandoauth2tutorial.repos;
import com.dzeru.springloginformandoauth2tutorial.entities.Post;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
#Service
#Repository
public interface PostRepo extends JpaRepository<Post, Integer> {
}
My form
<form action="/prj" method="post" class="auto_form">
<div class="container">
<label>
<input type="text" placeholder="Enter title" name="title" required>
</label>
<label>
<textarea id="text" cols="100%" rows="20%" placeholder="Enter content" name="content" required></textarea>
</label>
<b th:text="${text}"></b>
<button type="submit" class="button_login">Submit</button>
</div>
</form>
No problem, when entering a different logic. Thymeleaf displays everything correctly. Problem on data recording lines in the database: (PostMakerController) postRepo.save (post);
Generates a NullPointerException because id = null. But in my essence the autogenerator for Id is written.
My Post entitie
package com.dzeru.springloginformandoauth2tutorial.entities;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.Objects;
#Entity
#Table(name = "post")
public class Post {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#NotNull
private String author;
#NotNull
private String paragraph;
#NotNull
private String content;
public Post() {
this("EMPTY", "EMPTY", "EMPTY");
}
public Post(#NotNull String author, #NotNull String paragraph, #NotNull String content) {
this.author = author;
this.paragraph = paragraph;
this.content = content;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Post post = (Post) o;
return Objects.equals(id, post.id) && Objects.equals(author, post.author) && Objects.equals(paragraph, post.paragraph) && Objects.equals(content, post.content);
}
#Override
public int hashCode() {
return Objects.hash(id, author, paragraph, content);
}
#Override
public String toString() {
return "Post{" +
"id=" + id +
", author='" + author + '\'' +
", paragraph='" + paragraph + '\'' +
", content='" + content + '\'' +
'}';
}
public void setId(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getParagraph() {
return paragraph;
}
public void setParagraph(String paragraph) {
this.paragraph = paragraph;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
I`m using MariaDB!
Thanks for any help!
I fixed. Problem was in: Data truncation: Data too long for column 'column_name'.
I just make: jdbcCompliantTruncation=false in my application.properties
//This is my loginController.java
import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
#Controller
public class LoginController
{
#RequestMapping(value="/login.htm", method = RequestMethod.POST)
public String login(#RequestParam(value="userid", required=true) String userid,
#RequestParam(value="password", required=true) String password,
#RequestParam(value="confirmpassword", required=true) String confirmpassword,
#RequestParam(value="role", required=true) String role,
Map<String, Object> model)
{
if(userid.matches("^[a-zA-Z0-9]{5,24}$") && password.matches("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&+=])(?=\\S+$).{5,15}$")
&& confirmpassword.matches("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&+=])(?=\\S+$).{6,20}$")
&& (role.equals(new String("OPS(Operational)"))||role.equals(new String("Helpdesk"))))
{
model.put("userid", userid);
model.put("password", password);
model.put("confirmpassword", confirmpassword);
model.put("role", role);
System.out.println("successful!");
return "page2";
}
else
{
return "login";
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
{
String userid = request.getParameter("userid");
String password = request.getParameter("password");
String confirmpassword = request.getParameter("confirmpassword");
String role = request.getParameter("role");
try
{
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
catch (ServletException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String userid = request.getParameter("userid");
String password = request.getParameter("password");
String confirmpassword = request.getParameter("confirmpassword");
String role = request.getParameter("role");
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
}
}
//This is my login.jsp file
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# include file="include.jsp" %>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div align="center" id='formlogin' class="container">
<form method="post" id="loginForm" name="loginForm" action="login.htm">
<table class="tableprop" border="0" width="90%" cellspacing="5" cellpadding="5">
<h3> Add a new user </h3>
<tr>
<td align="center">User ID:</td>
<td><input tabindex="5" size="20" type="text" name="userid" id="userid" value="<%=request.getParameter("userid")!=null?request.getParameter("userid"):""%>"/></td>
</tr>
<tr>
<td align="center">Password:</td>
<td><input tabindex="5" size="20" type="password" name="password" id="password" value="<%=request.getParameter("password")!=null?request.getParameter("password"):""%>"/></td>
</tr>
<tr>
<td align="center">Confirm Password:</td>
<td><input tabindex="5" size="20" type="password" name="confirmpassword" id="confirmpassword" value="<%=request.getParameter("confirmpassword")!=null?request.getParameter("confirmpassword"):""%>"/></td>
</tr>
<tr>
<td align="center">Role:</td>
<td><select name="role" id="role" title="Please select role" tabindex="5" value="<%=request.getParameter("role")!=null?request.getParameter("role"):""%>"/>
<option value="">Select a specific role</option>
<option value="OPS(Operational)">OPS(Operational)</option>
<option value="Helpdesk">Helpdesk</option>
</select></td>
</tr>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
<tr>
<td align="center" colspan="4"><input tabindex="7" type="submit" value="Submit" id="submit" class="submit"/></td>
</tr>
<!-- <div id="dialog" title="Dialog Title">I'm in a dialog</div> -->
</table>
</form>
</div>
<script>
// just for the demos, avoids form submit
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
</script>
</body>
</html>
I have added here 2 files.
first one is loginController.java
and other one is login.jsp
i have done client side validation in jquery.
now i want to display error message on server side validation in loginController.java file which has code for server side validation. and also i want it to be check once whether loginController.java is written correct or not.
You can use Spring Validator interface to build your own custom validator and use spring form tags.
User.java
package com.expertwebindia.beans;
public class User {
private String name;
private String email;
private String address;
private String country;
private String state;
private String city;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
UserValidator.java
package com.expertwebindia.validators;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.expertwebindia.beans.User;
#Component
public class UserValidator implements Validator
{
public boolean supports(Class clazz) {
return User.class.equals(clazz);
}
public void validate(java.lang.Object arg0, Errors arg1) {
ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "name", "name.required", "Name is required.");
ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "email", "Name.required", "Email is required.");
ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "address", "name.required", "Address is required.");
ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "country", "country.required", "Country is required.");
ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "state", "state.required", "State is required.");
ValidationUtils.rejectIfEmptyOrWhitespace(arg1, "city", "city.required", "City is required.");
}
}
In controller you need to the following code to validate your bean.
#RequestMapping(value = "/login", method = RequestMethod.POST)
public String doLogin(#ModelAttribute("userForm") User userForm,
BindingResult result, Map<String, Object> model) {
validator.validate(userForm, result);
System.out.println("Email:"+userForm.getEmail());
if (result.hasErrors()) {
return "register";
}else{
return "success";
}
}
Please find more details about this in link below.
http://www.expertwebindia.com/spring-3-mvc-custom-validator-example/
To be shortly: here is simple web app. On the main page there is a button, after clickig on it it has to be another page with table that contains data from database.
Im using servlets/jsp MySQL
Here is code
Main page
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<title>University</title>
</head>
<body>
<h2 style="text-align: center">Welcome to university!</h2>
<p style="text-align: center"><img src="Images/university.jpg"></p>
<form>
<p style="text-align: center">
<button formmethod="GET" formaction="SelectStudents.do">See all students</button>
</p>
</form>
</body>
</html>
Page with table
<%# page import="java.util.List" %>
<%# page import="model.StudentDAO" %>
<%# page import="model.Student" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Students</title>
</head>
<body>
<table border="1" >
<caption>Students</caption>
<tr>
<th>ID</th>
<th>Name</th>
<th>Surname</th>
<th>Age</th>
<th>Country</th>
<th>City</th>
<th>Street</th>
<th>House</th>
<th>Flat</th>
<th>Group</th>
</tr>
<%
List<Student> students = new StudentDAO().selectAll();
for (Student s : students) {
%>
<tr>
<td><%=s.getId()%>></td>
<td><%=s.getName()%>></td>
<td><%=s.getSurname()%>></td>
<td><%=s.getAge()%>></td>
<td><%=s.getAddress().getCountry()%>></td>
<td><%=s.getAddress().getCity()%>></td>
<td><%=s.getAddress().getStreet()%>></td>
<td><%=s.getAddress().getHouseNumber()%>></td>
<td><%=s.getAddress().getFlatNumber()%>></td>
<td><%=s.getGroup().getName()%>></td>
</tr>
<%
}
%>
</table>
</body>
</html>
Class Student
public class Student {
private int id;
private String name;
private String surname;
private int age;
private Address address;
private Group group;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String name) {
this.surname = surname;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setAddress(Address address) {
this.address = address;
}
public Address getAddress() {
return address;
}
public void setGroup(Group group) {
this.group = group;
}
public Group getGroup() {
return group;
}
}
JDBCConnecto
package model;
import java.sql.*;
public class ConnectionManager {
private static final String JDBC_LOADER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost:3306/";
private static final String LOGIN = "root";
private static final String PASSWORD = "15021990";
private Connection connection;
public ConnectionManager() throws ClassNotFoundException, SQLException{
Class.forName(JDBC_LOADER);
connection = DriverManager.getConnection(URL, LOGIN, PASSWORD);
}
public Connection getConnection() throws SQLException{
return connection;
}
}
DAO
package model;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class StudentDAO {
private static final String SELECT_ALL =
"SELECT student.id, student.name, student.surname, student.age, \n" +
"\t address.country, address.city, address.street, address.house, address.flat, \n" +
"\t class.name\n" +
"\t FROM University.student join University.address \n" +
"\t on university.student.address = university.address.id join university.class\n" +
"\t on university.student.class = university.class.id";
public List<Student> selectAll() {
List<Student> result = new ArrayList<Student>();
Connection c = null;
try {
c = new ConnectionManager().getConnection();
Statement s = c.createStatement();
ResultSet students = s.executeQuery(SELECT_ALL);
while (students.next()) {
int id = students.getInt(1);
String name = students.getString(2);
String surname = students.getString(3);
int age = students.getInt(4);
String country = students.getString(5);
String city = students.getString(6);
String street = students.getString(7);
int house = students.getInt(8);
int flat = students.getInt(9);
String groupName = students.getString(10);
Address address = new Address();
address.setCountry(country);
address.setCity(city);
address.setStreet(street);
address.setHouseNumber(house);
address.setFlatNumber(flat);
Group group = new Group();
group.setName(groupName);
Student student = new Student();
student.setId(id);
student.setName(name);
student.setSurname(surname);
student.setAge(age);
student.setAddress(address);
student.setGroup(group);
result.add(student);
}
} catch (SQLException e) {
System.out.print(e.getErrorCode());
} catch (ClassNotFoundException e) {
} finally {
try {
if (c != null)
c.close();
} catch (SQLException e) {
System.out.print(e.getErrorCode());
}
}
return result;
}
}
Servlet
package controller;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class StudentsSelect extends HttpServlet {
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) {
RequestDispatcher view = request.getRequestDispatcher("table.jsp");
try {
view.forward(request, response);
} catch (ServletException e) {
} catch (IOException e) {
}
}
}
The problem is that after pressing the button there is no information about students in table in table.jsp.
You obviously forgot to add your MySQL connector (select platform independent and click download zip package, if your didn't download it). Add MySQL connector jar file to lib directory in your project. That should solve your problem.
I have problem of inserting data in my database Table from HTML page. When ever I run the application and send the data, all my fields in the Table will be NULL.
This is my database connection class
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DbConnection {
public static Connection getConnection() throws Exception
{
try
{
String connectionURL = "jdbc:mysql://localhost:3306/dvd_collection";
Connection connection = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "031081");
return connection;
}
catch (SQLException e)
{
throw e;
}
catch (Exception e)
{
throw e;
}
}
public static void close(Connection connection)
{
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
This is my userVo class
package pojo;
public class UserVo {
private String username;
private String password;
private String email;
private String gender;
private String occupation;
private String marital;
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 String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getOccupation() {
return occupation;
}
public void setOccupation(String occupation) {
this.occupation = occupation;
}
public String getMarital() {
return marital;
}
public void setMarital(String marital) {
this.marital = marital;
}
}
This is my Service class
package webService;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import pojo.UserVo;
#Path("/WebService")
public class SignUpService {
#POST
#Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
#Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public UserVo create(UserVo user)throws Exception {
System.out.println("creating user");
return dao.create(user);
}
This is my JS file
// The root URL for the RESTful services
var rootURL = "http://localhost:8080/Test/REST/WebService";
$('#btnSubmit').click(function() {
if ($('#UserName').val() == '')
alert('User Name can not be empty');
else
addWine();
return false;
});
function addWine() {
console.log('addWine');
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootURL,
dataType: "json",
data: formToJSON(),
success: function(data, textStatus, jqXHR){
alert('Record created successfully: Login to your account');
},
error: function(jqXHR, textStatus, errorThrown){
alert('The User name already exist: ' + textStatus);
}
});
}
// Helper function to serialize all the form fields into a JSON string
function formToJSON() {
return JSON.stringify({
"username": $('#UserName').val(),
"password": $('#Password').val(),
"email": $('#Email').val(),
"gender": $('#Gender').val(),
"occupation": $('#Occupation').val(),
"marital": $('#MaritalStatus').val()
});
}
This is my SignUpHandler Class
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import dao.DbConnection;
import pojo.UserVo;
public class SignUpHandler {
public UserVo create(UserVo user) throws Exception {
Connection c = null;
PreparedStatement ps = null;
try {
c = DbConnection.getConnection();
ps = c.prepareStatement("INSERT INTO signin (user_name, password, e_mail, gender, occupation, marital_status) VALUES (?, ?, ?, ?, ?, ?)",
new String[] { "ID" });
ps.setString(1, user.getUserName());
ps.setString(2, user.getPassword());
ps.setString(3, user.getEmail());
ps.setString(4, user.getGender());
ps.setString(5, user.getOccupation());
ps.setString(6, user.getMarital());
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
rs.next();
// Update the id in the returned object. This is important as this value must be returned to the client.
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
DbConnection.close(c);
}
return user;
}
}
This is my HTML Form
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Test</title>
</head>
<body>
<form class="form-signup">
<h2 class="form-signin-heading">Please Register</h2>
<input name="UserName" type="text" placeholder="Username">
<input name="Password" type="password" placeholder="Password">
<input name="Email" type="text" placeholder="Email">
<input name="Gender" type="text" placeholder="Gender">
<input name="Occupation" type="text" placeholder="Occupation">
<input name="MaritalStatus" type="text" placeholder="Marital Status">
<button type="submit" id="btnSubmit">Submit</button>
</form>
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="js/jquery-1.8.2.js"></script>
<script src="js/main.js"></script>
</body>
</html>
You use $('#UserName').val() to get the value of the user name text input, but this text input doesn't have the id UserName. It has the name UserName. So you actually want
$('input[name="UserName"]').val()
or, more simply
<input name="UserName" id="UserName" type="text" placeholder="Username"/>
(same for all the other fields, of course)
Side note: what's the point of catching an exception only to rethrow it? This adds unnecessary lines to your code, and make it more difficult to identify the source of an exception.