I have problem accessing database with servlet java. I want to add users with an html registration form. this is the html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Registration Page</title>
<!---Custom CSS File--->
<link rel="stylesheet" href="style.css" />
</head>
<body>
<header>Registration Form</header>
<form action="register" method="post" class="form">
<div class="input-box">
<label>Full Name</label>
<input type="text" name="txtUname" placeholder="Enter full name" required />
</div>
<div class="input-box">
<label>Email Address</label>
<input type="email" name="Email" placeholder="Enter email address" required />
</div>
<div class="input-box">
<label>Password</label>
<input type="password" name="Pass" placeholder="Password" required />
</div>
<button>REGISTER</button>
</form>
</body>
</html>
This is the servlet (RegistrationControllerServlet.java)
package com.loginpagedemo.controller;
import java.io.IOException;
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 com.loginpagedemo.dao.UserDao;
import com.loginpagedemo.daoimpl.UserDaoImpl;
import com.loginpagedemo.pojo.User;
#WebServlet("/register")
public class RegistrationControllerServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String uname = request.getParameter("txtUname");
String password = request.getParameter("Pass");
String email = request.getParameter("Email");
User u = new User(uname,password,email);
UserDao daoImpl = new UserDaoImpl();
if(daoImpl.addNewUser(u)) {
response.sendRedirect("Success?msg=regsuccess");
}
else {
response.sendRedirect("error?msg=regerror");
}
}
}
This is the java class (User.java):
package com.loginpagedemo.pojo;
public class User {
private String username;
private String emailaddress;
private String password;
public User() {
}
public User(String username,String emailaddress,String password){
this.username = username;
this.emailaddress =emailaddress;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmailaddress() {
return emailaddress;
}
public void setEmailaddress(String emailaddress) {
this.emailaddress = emailaddress;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
This is the java Interface (UserDao.java):
package com.loginpagedemo.dao;
import com.loginpagedemo.pojo.User;
public interface UserDao {
boolean checkUserCredentials(User user);
boolean addNewUser(User user);
}
This is the java class (DbConnection.java):
package com.loginpagedemo.connection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DbConnection {
public static Connection getDatabaseConnection(){
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection(
"jdbc:mysql://localhost:3306/28thnovadv",
"root","ROOT#123");
return con;
}
catch(ClassNotFoundException | SQLException exc) {
exc.printStackTrace();
return null;
}
}
}
This is the java class (UserDaoImpl.java):
package com.loginpagedemo.daoimpl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.loginpagedemo.connection.DbConnection;
import com.loginpagedemo.dao.UserDao;
import com.loginpagedemo.pojo.User;
public class UserDaoImpl implements UserDao {
#Override
public boolean checkUserCredentials(User user) {
try(Connection con =
DbConnection.getDatabaseConnection()){
PreparedStatement st = con.prepareStatement(
"SELECT * FROM userdata WHERE username=? AND email=? AND password=?");
st.setString(1, user.getUsername());
st.setString(2, user.getEmailaddress());
st.setString(3, user.getPassword());
ResultSet rs =st.executeQuery();
if(rs.isBeforeFirst())
return true;
else
return false;
}
catch(SQLException | NullPointerException exc){
exc.printStackTrace();
return false;
}
}
#Override
public boolean addNewUser(User user) {
try(Connection con =
DbConnection.getDatabaseConnection()){
PreparedStatement st = con.prepareStatement(
"INSERT INTO userdata VALUES(?,?,?)");
st.setString(1, user.getUsername());
st.setString(2, user.getEmailaddress());
st.setString(3, user.getPassword());
int count = st.executeUpdate();
if(count > 0)
return true;
else
return false;
}
catch(SQLException | NullPointerException exc){
exc.printStackTrace();
return false;
}
}
}
This is the 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_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>LoginpageJDBC</display-name>
<welcome-file-list>
<welcome-file>RegistartionFrom.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>registration</servlet-name>
<servlet-class>com.loginpagedemo.controller.RegistrationControllerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>registration</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
</web-app>
Folder Structure
error after updated
I'm sorry that is a long question, but I am in despair
Looks like your implementation of method dopost() is wrong.
It should be doPost().
https://jenkov.com/tutorials/java-servlets/httpservlet.html
Like this:
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
You can also try to configure manually the servlet in WEB-INF/web.xml.
Something like:
<web-app>
<servlet>
<servlet-name>registration</servlet-name>
<servlet-class>com.loginpagedemo.controller.RegistrationControllerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>registration</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
</web-app>
https://javapapers.com/servlet/what-is-servlet-mapping/
Related
I have designed a simple service to insert customer details to db and retrieve data from it. But when ever i am calling any service , i am getting 404 error.
I have provided my code below .
Customer.java
package com.fetch;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
#XmlRootElement(name = "Customer")
#XmlType(name = "Customer")
#XmlAccessorType(XmlAccessType.FIELD)
public class Customer //implements Serializable
{
#Id
private long id;
#Column(name = "NAME")
private String name;
public Customer(int id, String name)
{
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
MyAccount.Java
package com.fetch;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.persistence.Entity;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
//#WebService()
//#Entity
#Path("user")
public class MyAccount
{
#POST
#Path("fetch")
//#WebMethod(operationName = "insert")
#Consumes(MediaType.TEXT_PLAIN)
public String insert(#QueryParam("name") String name)
{
try
{
// Class.forName("com.mysql.jdbc.Driver");
// Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentinfo", "root", "root");
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:orcl", "scott", "tiger");
String query = "insert into CUSTOMER"+"(NAME) VALUES"+"(?)";
PreparedStatement st = con.prepareStatement(query);
st.setString(1,name);
st.executeUpdate();
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
return"Record inserted successfully";
}
#GET
#Path("retrive")
#Produces("text/html")
//#WebMethod(operationName = "retrive")
public String retrive()
{
ResultSet rs = null;
String details = "";
try
{
//Class.forName("com.mysql.jdbc.Driver");
//Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentinfo", "root", "root");
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:orcl", "scott", "tiger");
String query = "select ID,NAME from CUSTOMER";
PreparedStatement st = con.prepareStatement(query);
rs = st.executeQuery();
details = "<html><body>";
details = details + "<table border=1>";
details = details + "<tr><td><Strong>Id </Strong></td>" +
"<td><Strong>Name </Strong></td>" + "</tr>";
while (rs.next())
{
details = details + "<tr><td>" + rs.getInt("ID") + "</td>" +
"<td>" + rs.getString("NAME") + "</td></tr>";
}
details += "</table></body></html>";
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
return details;
}
}
insert.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
$('#call').click(function ()
{
$.ajax({
type: "post",
url: "rest/user/fetch", //this is my servlet
data: "name=" +$('#name').val(),
success: function(msg){
$('#output').html(msg);
}
});
});
$('#take').click(function ()
{
$.ajax({
type: "get",
url: "rest/user/retrive",
success: function(msg){
$('#output').html(msg);
}
});
});
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="">
<!-- <form action="rest/user/fetch" method="POST"> -->
<p>
Name : <input id="name" name="name" />
</p>
<input type="button" name="call" id="call" value="Insert"/>
<!-- </form> -->
<!-- <form action="rest/user/retrive" method="GET"> -->
<input type="button" name="take" id="take" value="Retrive"/>
<!-- </form> -->
<p>
Response : <div type="text" id="output"></div>
</p>
</form>
</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>FetchAndInsert</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>REST Servlet</servlet-name>
<servlet-
class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.fetch</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>REST Servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
JAR DETAILS:
javax.ws.rs-api-2.0-m02.jar
ojdbc14.jar
persistence-api-2.0.jar
Check if the rest service started successfully with no failure in logs.
Have you included jersey API in jar list?
Are you calling the web service with proper URL? (ex: http:servername:portno/FetchAndInsert/rest/user/fetch with POST and http:servername:portno/FetchAndInsert/rest/user/retrive as GET)
Check if you would need POST or GET for fetch web service?
com.sun.jersey is the old API. You can use glassfish version.
I am new to struts2. I am using NetBeans8, Glassfish4 and MySql6.
I am making a login form. The problem I am having is is that I am not getting either an error or any output.
I can run my application and at my login page after clicking on submit nothing happens, but my url changes to http://localhost:8080/Pharma/loginAction.action
Please could somebody help, your suggestions would be highly appreciated
LoginAction.java
package package_login;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.lang3.StringUtils;
public class LoginAction extends ActionSupport implements ModelDriven<User>{
User user=new User();
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
#Override
public User getModel() {
return user;
}
public void validate(){
if(StringUtils.isEmpty(user.getEmail())){
addFieldError("email","Please entered your email");
}
if(StringUtils.isEmpty(user.getPassword())){
addFieldError("password","Please entered your password");
}
}
public String execute() throws ClassNotFoundException, SQLException {
LoginService loginService= new LoginService();
if(loginService.verifyLogin(user)){
return "logged";
}
return "login";
}
}
LoginService.java
package package_login;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
class LoginService {
public boolean verifyLogin(User user) throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.jdbc.Driver");
Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/erp","root","ali$");
Statement st= con.createStatement();
ResultSet rs= st.executeQuery("select password,email from login where email='"+user.getEmail()+"'" );
while(rs.next()){
// if(user.getEmail().equals(rs.getString("email"))&& user.getPassword().equals("password")){
// return true;
}
// }
return false;
}
}
User.java
package package_login;
class User {
private String email;
private String password;
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;
}
}
login.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!-- Configuration for the default package. -->
<package name="package_login" extends="struts-default">
<action name="loginAction" class="package_login.LoginAction">
<result name="logged">/welcome.jsp</result>
<result name="login">/login.jsp</result>
<result name="input">/login.jsp</result>
</action>
</package>
</struts>
login.jsp
<%#taglib uri="/struts-tags" prefix="s"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<s:form action="loginAction">
<s:textfield key="email" label="Email"/>
<s:password key="password" label="Password"/>
<s:submit value="login"/>
</s:form>
</body>
</html>
ResultSet rs= st.executeQuery("select email from login where email='"+user.getEmail()+"' and password='"+user.getPassword()+"'" );
if(rs.next())
{
return true;//if valid user, return true
}
else
return false;
and
your are using struts configuration file name login.xml.
The struts configuration file name instead of login.xml should use struts.xml
Instead of Statement, use PrepareStatement or callablestatement to avoid sql injection.
Link
Here I come up with problem with Operation like update,delete and view so now insert is working but other operation like update, delete, view showing error like. Could some one can guide to go right direction? This what I have tried up to now
Error:
HTTP Status 500 - java.lang.NullPointerException
type Exception report
message java.lang.NullPointerException
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: java.lang.NullPointerException
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:515)
org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:419)
root cause
java.lang.NullPointerException
Action.Testiue.view(Testiue.java:115)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:404)
com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:267)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:229)
com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:221)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:86)
com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:150)
org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:48)
struts.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<include file="struts-default.xml" />
<package name="a" extends="struts-default">
<action name="adduser" class="Action.Testiue" method="add">
<result name="success">/insert.jsp</result>
<result name="success">/ssuccess.jsp</result>
</action>
<action name="viewuser" class="Action.Testiue" method="view">
<result name="success">/view.jsp</result>
<result name="error">/error.jsp</result>
</action>
<action name="updateuser" class="Action.Testiue" method="update">
<result name="success">/edit.jsp</result>
<result name="error">/error.jsp</result>
</action>
<action name="deleteuser" class="Action.Testiue" method="delete">
<result name="success">/dsuccess.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
</struts>
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
TestIUE.java
package Action;
import com.opensymphony.xwork2.ActionSupport;
import dao.UserDao;
import dbBean.UseBean;
public class Testiue
{
private String Name;
private String Password;
private String EmailID;
private String Phoneo;
private int ID;
public String getName()
{
return Name;
}
public void setName(String name)
{
Name = name;
}
public String getPassword()
{
return Password;
}
public void setPassword(String password)
{
Password = password;
}
public String getEmailID()
{
return EmailID;
}
public void setEmailID(String emailID)
{
EmailID = emailID;
}
public String getPhoneo()
{
return Phoneo;
}
public void setPhoneo(String phoneo)
{
Phoneo = phoneo;
}
public int getID()
{
return ID;
}
public void setID(int i)
{
ID = i;
}
#Override
public String toString()
{
return "UseBean [id=" + ID + ", Name=" + Name+ ", Password=" + Password + ", EmailID=" + EmailID + ", Phoneo="+ Phoneo + "]";
}
private UserDao dao;
private UseBean bean;
public String add()
{
dao=new UserDao();
bean=new UseBean();
System.out.println(getName()+""+getPassword()+""+getPhoneo()+""+getEmailID());
bean.setID(ID);
bean.setName(Name);
bean.setPassword(Password);
bean.setPhoneo(Phoneo);
bean.setEmailID(EmailID);
dao.addUser(bean);
return ActionSupport.SUCCESS;
}
public String update()
{
dao=new UserDao();
bean=new UseBean();
//System.out.println(getName()+""+getPassword()+""+getPhoneo()+""+getEmailID());
bean.setID(ID);
bean.setName(Name);
bean.setPassword(Password);
bean.setPhoneo(Phoneo);
bean.setEmailID(EmailID);
dao.updateUser(bean);
return ActionSupport.SUCCESS;
}
public String delete()
{
int userId =0;
dao.deleteUser(userId);
return ActionSupport.SUCCESS;
}
public String edit()
{
int userId =0;
bean = dao.getUserById(userId);
return ActionSupport.SUCCESS;
}
public String view()
{
dao.getAllUsers();
return ActionSupport.SUCCESS;
}
}
Index.jsp
<META HTTP-EQUIV="Refresh" CONTENT="0;URL=viewuser.action">
view.jsp;
<%# taglib prefix="s" uri="/struts-tags"%>
<%#page import="java.util.*,dbBean.*,Dbconnect.*,java.util.*"%>
Insert
<table border=1>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>password</th>
<th>phoneno</th>
<th>emailid</th>
<th colspan=2>Action</th>
</tr>
</thead>
<jsp:useBean id="users" class="java.util.ArrayList" scope="request" />
<% for(int i = 0; i < users.size(); i+=1)
{
UseBean user = (UseBean)users.get(i);
%>
<tbody>
<tr>
<td><%= user.getID() %></td>
<td><%= user.getName() %></td>
<td><%= user.getPassword() %></td>
<td><%= user.getEmailID() %></td>
<td><%= user.getPhoneo() %></td>
<td>Update</td>
<td>Delete</td>
</tr>
<%
}
%>
</tbody>
</table>
edit.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>
<form action="updateuser">
id:<input type="text" name="ID" ><br/>
Name:<input type="text" name="Name" ><br/>
Password:<input type="text" name="password" ><br/>
phoneno:<input type="text" name="Phoneo" ><br/>
Emailid:<input type="text" name="Emailid" > <br/>
<input type="submit" value="Submit" />
</form>
</body>
</html>
UserDao.java
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import dbBean.UseBean;
import Dbconnect.*;
public class UserDao
{
private Connection conn;
public UserDao()
{
conn=Dbconnect.getConnection();
}
public void addUser(UseBean bean)
{
try
{
String sql="insert into senthil (name,pass,phoneno,emailid) values(?,?,?,?)";
PreparedStatement ps=conn.prepareStatement(sql);
ps.setString(1,bean.getName());
ps.setString(2,bean.getPassword());
ps.setString(3,bean.getPhoneo());
ps.setString(4,bean.getEmailID());
ps.executeUpdate();
}
catch (Exception e)
{
// TODO: handle exception
}
}
public void deleteUser(int userId)
{
try
{
PreparedStatement ps = conn.prepareStatement("delete from senthil where id=?");
// Parameters start with 1
ps.setInt(1, userId);
ps.executeUpdate();
} catch (SQLException e)
{
e.printStackTrace();
}
}
public void updateUser(UseBean bean)
{
try
{
PreparedStatement preparedStatement = conn.prepareStatement("update senthil set name=?, pass=?, phoneno=?, emailid=?"+ "where id=?");
// Parameters start with 1
preparedStatement.setString(1, bean.getName());
preparedStatement.setString(2, bean.getPassword());
preparedStatement.setString(3, bean.getPhoneo());
preparedStatement.setString(4, bean.getEmailID());
preparedStatement.setInt(5, bean.getID());
preparedStatement.executeUpdate();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public List<UseBean> getAllUsers()
{
List<UseBean> users = new ArrayList<UseBean>();
try
{
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery("select * from senthil");
while (rs.next())
{
UseBean user = new UseBean();
user.setID(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("pass"));
user.setPhoneo(rs.getString("phoneno"));
user.setEmailID(rs.getString("emailid"));
users.add(user);
}
}
catch (SQLException e)
{
e.printStackTrace();
}
return users;
}
public UseBean getUserById(int userId)
{
UseBean user = new UseBean();
try
{
PreparedStatement preparedStatement = conn.prepareStatement("select * from senthil where id=?");
preparedStatement.setInt(1, userId);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next())
{
user.setID(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("pass"));
user.setPhoneo(rs.getString("phoneno"));
user.setEmailID(rs.getString("emailid"));
}
} catch (SQLException e)
{
e.printStackTrace();
}
return user;
}
}
In the JSP the users should be available to the request scope.
public String view() {
UserDao userDao = new UserDao();
List<UseBean> users = userDao.getAllUsers();
ServletActionContext.getRequest().setAttribute("users", users);
return Action.SUCCESS;
}
public String update() {
UserDao dao = new UserDao();
UseBean bean=new UseBean();
HttpServletRequest request ServletActionContext.getRequest();
bean.setID(request.getParameter("ID");
bean.setName(request.getParameter("Name");
bean.setPassword(request.getParameter("Password");
bean.setPhoneo(request.getParameter("Phoneo");
bean.setEmailID(request.getParameter("EmailID");
//System.out.println(getName()+""+getPassword()+""+getPhoneo()+""+getEmailID());
dao.updateUser(bean);
return Action.SUCCESS;
}
public String delete() {
HttpServletRequest request ServletActionContext.getRequest();
int userId = request.getParameter("ID");
dao.deleteUser(userId);
return Action.SUCCESS;
}
for delete action
<s:param name='ID'><%=user.getID()%></s:param></s:url>">Delete
Inside view method you haven't initialized the dao object(i.e reference is null), add the following code :
In TestIUE.java add one more member variable :
List<UseBean> users = new ArrayList<UseBean>();
Also add Accessor method :
public List<UseBean> getUsers()
{
return users;
}
Now modify your view method as follows :
public String view()
{
dao = new UseDao();
users = dao.getAllUsers();
return ActionSupport.SUCCESS;
}
I am trying to create a register page which business logic is managed in servlet (Controller class), parameter values are called from a Javabean (Bean class) and uses a class to handle the database connectivity (Dbconnect class). We register and then we have to sign in through index.jsp. If the user is valid, the system should display a welcome page (welcome.jsp) showing the user name.
I don't know how to connect these classes to be called through my jsp to process the login. Here is the code showing what I have tried. I had seen many web source but couldn't understand the process..
This is how I think the communication of classes should be:
Dbconnection.java--->bean.java--->Controller.java--->register.jsp--->login.jsp--->welcome.jsp
Index.jsp:
User name:<input type="text" name="username">
Password:<input type="password" name="password">
<input type="submit" name="Login"> Register
Register.jsp
<form action="Loginservlet" method="post">
User name:<input type="text" name="name" >
Password:<input type="password" name="pass">
Email-id<input type="text" name="emailid">
phone number:<input type="text" name="phone">
<input type="submit" value="submit">Login
</form>
Bean.java
package Databases;
public class Bean
{
private String username;
private String password;
private String emailid;
private String phone;
/**
* #return the username
*/
public String getUsername()
{
return username;
}
/**
* #param username the username to set
*/
public void setUsername(String username)
{
this.username = username;
}
/**
* #return the password
*/
public String getPassword()
{
return password;
}
/**
* #param password the password to set
*/
public void setPassword(String password)
{
this.password = password;
}
/**
* #return the emailid
*/
public String getEmailid()
{
return emailid;
}
/**
* #param emailid the emailid to set
*/
public void setEmailid(String emailid)
{
this.emailid = emailid;
}
/**
* #return the phone
*/
public String getPhone()
{
return phone;
}
/**
* #param phone the phone to set
*/
public void setPhone(String phone)
{
this.phone = phone;
}
}
Dbconnect.java
package Databases;
import java.io.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;
public class Dbconnect
{
public static void main(String args[]) throws ClassNotFoundException
{
Dbconnect db = new Dbconnect();
db.dbconnect();
}
public void dbconnect() throws ClassNotFoundException
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mine", "root", "android");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from user");
while(rs.next())
{
ArrayList al=new ArrayList();
al.add(rs.getString("name"));
al.add(rs.getString("password"));
al.add(rs.getString("email"));
Iterator it=al.iterator();
while(it.hasNext())
{
System.out.println("value are:"+it.next());
}
}
Controller.java:
package 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;
import com.mysql.jdbc.PreparedStatement;
import Databases.Dbconnect;
import Databases.*;
/**
* Servlet implementation class Loginservlet
*/
public class Controller extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
String pass = request.getParameter("pass");
String email = request.getParameter("emailid");
String pn = request.getParameter("phone");
System.out.println("Name :" + name);
System.out.println("pass :" + pass);
System.out.println("emailid :" + email);
System.out.println("phone:" + pn);
String a = Bean.setUsername(name);
String b=Bean.setPassword(name);
String c=Bean.setEmailid(name);
String dBean.setPhone(name);
String sql = "insert into user(name,password,email,phone) values(?,?,?,?)";
Dbconnect a = new Dbconnect();
a.dbconnect();
PreparedStatement prep = a.dbconnect().prepareStatement(sql);
// Setting the values which we got from JSP form
prep.setString(1, a);
prep.setString(2, b);
prep.setString(3, c);
prep.setString(4, d);
prep.executeUpdate();
prep.close();
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>WebprojectTry</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>Controller</display-name>
<servlet-name>Controller</servlet-name>
<servlet-class>servlet.Controller</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Controller</servlet-name>
<url-pattern>/Controller</url-pattern>
</servlet-mapping>
</web-app>
I have done inserting a record into database but I don't know how to retrieve it.
My code is:
Account.java:
package com.fetch;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Id;
public class Account implements Serializable
{
#Id
private long id;
#Column(name="NAME")
private String name;
public Account()
{
}
public Account(int id, String name)
{
this.id = id;
this.name = name;
}
public long getId()
{
return id;
}
public void setId(long id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}
MyAccount.java:
package com.fetch;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collection;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.persistence.Entity;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
#WebService()
#Entity
#Table(name = "CUSTOMER")
#Path("/user")
#NamedQuery(name="loginquery", query="select ID,NAME from CUSTOMER")
public class MyAccount
{
private Account ac;
public MyAccount()
{
// TODO Auto-generated constructor stub
ac = new Account();
}
#POST
#Path("/fetch")
#WebMethod(operationName = "insert")
public String insert(#FormParam("name") String name)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentinfo", "root", "root");
String query = "insert into CUSTOMER"+"(NAME) VALUES"+"(?)";
PreparedStatement st = con.prepareStatement(query);
st.setString(1,name);
st.executeUpdate();
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
return"Record inserted successfully";
}
public Account getAc()
{
return ac;
}
public void setAc(Account ac)
{
this.ac = ac;
}
}
insert.html:
<!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>
</head>
<body>
<form action="rest/user/fetch" method="POST">
<p>
Name : <input id="name" name="name" />
</p>
<input type="submit" value="Add" />
<input type="submit" value="Retrive" />
</form>
</body>
</html>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>FetchAndInsert</display-name>
<servlet>
<servlet-name>REST Servlet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.fetch</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>REST Servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
How to retrieve the data from the database when the user clicks on the retrieve button, and display all the records in another HTML form?
Please give suggestions on how to do it.
In my application, when the user clicks the retrieve button it is performing the insert operation.
But I want is, when the user clicks it should go to the another page and display the data in table from database.
Can anybody tell the mistake what I have done, and give suggestions for finding solution for it and how to display the dynamic table in other page when the user clicks the retrieve button?
Finally I have done it, Now I am able to perform both insertion and retriving of data from database using jersey(JAX - RS) webservices and able to display it in a html page.
Account.java:
package com.fetch;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Id;
public class Account implements Serializable
{
#Id
private long id;
#Column(name = "NAME")
private String name;
public Account(int id, String name)
{
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
MyAccount.java:
package com.fetch;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.persistence.Entity;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
#WebService()
#Entity
#Path("/user")
public class MyAccount
{
#POST
#Path("/fetch")
#WebMethod(operationName = "insert")
public String insert(#FormParam("name") String name)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentinfo", "root", "root");
String query = "insert into CUSTOMER"+"(NAME) VALUES"+"(?)";
PreparedStatement st = con.prepareStatement(query);
st.setString(1,name);
st.executeUpdate();
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
return"Record inserted successfully";
}
#GET
#Path("/retrive")
#Produces("text/html")
#WebMethod(operationName = "retrive")
public String retrive()
{
ResultSet rs = null;
String details = "";
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentinfo", "root", "root");
String query = "select ID,NAME from CUSTOMER";
PreparedStatement st = con.prepareStatement(query);
rs = st.executeQuery();
details = "<html><body>";
details = details + "<table border=1>";
details = details + "<tr><td><Strong>Id </Strong></td>" +
"<td><Strong>Name </Strong></td>" + "</tr>";
while (rs.next())
{
details = details + "<tr><td>" + rs.getInt("ID") + "</td>" +
"<td>" + rs.getString("NAME") + "</td></tr>";
}
details += "</table></body></html>";
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
return details;
}
}
insert.html:
<!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>
</head>
<body>
<form action="rest/user/fetch" method="POST">
<p>
Name : <input id="name" name="name" />
</p>
<input type="submit" value="Add" />
</form>
<form action="rest/user/retrive" method="GET">
<input type="submit" value="Retrive" />
</form>
</body>
</html>
my web.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>FetchAndInsert</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>REST Servlet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.fetch</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>REST Servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
Jersey doesn't provide any sort of HTML templating. You need to forward your response to a jsp page or use Ajax to fetch the data and lay it out on the page.