Hebrew characters looks garbled (Java+Objectify+JSP) - java

I have a HTML form
<form method="post" accept-charset="UTF-8"
action="<%=blobstoreService.createUploadUrl("/nonameyet")%>"
enctype="multipart/form-data">
<tr>
<td><input type="text" name=name /></td>
<td><input type="text" name=price /></td>
<td><input type="text" name=quantity /></td>
<td><input type="file" name="image" /></td>
<td><input type="submit" value="add" /></td>
</tr>
after sending the data I receive it here:
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(req);
List<BlobKey> blobKeys = blobs.get("image");
if (blobKeys.get(0) == null) {
resp.sendRedirect("/");
}
req.setCharacterEncoding("UTF-8");
BlobKey blobKey = blobKeys.get(0);
Product product = new Product();
String name = req.getParameter("name");
String priceAsString = req.getParameter("price");
int price = Integer.parseInt(priceAsString);
String quantityAsString = req.getParameter("quantity");
int quantity = Integer.parseInt(quantityAsString);
product.setName(name);
product.setPrice(price);
product.setQuantity(quantity);
String url = ImagesServiceFactory.getImagesService().getServingUrl(ServingUrlOptions.Builder.withBlobKey(blobKey));
product.setImage(url);
ofy().save().entities(product).now();
resp.sendRedirect("/index.jsp");
}
and now the JSP is:
<%
List<Product> list = ofy().load().type(Product.class).limit(20)
.list();
for (Product product : list) {
%>
<tr>
<td><%=product.getName()%></td>
<td><%=product.getPrice()%></td>
<td><%=product.getQuantity()%></td>
<td><img alt="<%=product.getName()%>"
src="<%=product.getImage()%>" width="100" height="100" /></td>
<td>delete
</tr>
<%
}
%>
But when I view the page in Chrome it looks like this:
After examining the data in http://localhost:8888/_ah/admin/datastore, I can see the word in Hebrew is correct:
So I get to the conclusion that somewhere on the way from the datastore to the jsp the text gets garbled. Can someone help?

Related

Java SpringBoot Postgres remove rows

Help me please to remove the row in Postgres by clicking the Del button.
Maybe to link id in DB and id on the HTML page, but how?
Maybe I need to parse the HTML page and pass String id?
Any ideas will help me.
here is my database schema:
<table class="tmc">
<thead>
<tr>
<th>ID</th><th>TMC</th><th>SN</th><th>Owner</th>
</tr>
</thead>
<tbody>
{{#messages}}
<tr>
<td>{{id}}</td>
<td><span>{{text}}</span></td>
<td><i>{{sn}}</i></td>
<td><i>{{owner}}</i></td>
<th><form action="/remove" method="post">
<input type="submit" value="Del"/>
<input type="hidden" name="_csrf" value="{{_csrf.token}}" />
</form>
</th>
</tr>
{{/messages}}
</tbody>
#Entity
#Table(name = "message")
public class Message {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String text;
private String sn;
private String owner;
public Message() {
}
public Message(String text, String sn, String owner) {
this.text = text;
this.sn = sn;
this.owner = owner;
}
Rows are forming in database by:
#PostMapping("/main")
public String add (
#RequestParam String owner,
#RequestParam String text,
#RequestParam String sn, Map<String, Object> model) {
Message message = new Message (text, sn, owner);
if (text != null && !text.isEmpty() & sn != null && !sn.isEmpty() & owner != null &&
!owner.isEmpty()) {
if (!text.matches("^[0-9].*$")) {
messageRepo2.save(message);
Iterable<Message> messages = messageRepo2.findAll();
model.put("messages", messages);
} else
model.put("error", "ТМЦ не должно начинаться с цифры");
Iterable<Message> messages = messageRepo2.findAll();
model.put("messages", messages);
} else {
model.put("error", "Заполните все поля!");
Iterable<Message> messages = messageRepo2.findAll();
model.put("messages", messages);
}
return "main";
}
There are two issues with your html code:
it would be to let the form element outside the table
need to use <input type="hidden" name="xxx" value="{{xxx}}" /> in order to let it can pass parameter to your controller method
<form action="/remove" method="post">
<input type="hidden" name="_csrf" value="{{_csrf.token}}" />
<table class="tmc">
<thead>
<tr>
<th>ID</th><th>TMC</th><th>SN</th><th>Owner</th>
</tr>
</thead>
<tbody>
{{#messages}}
<tr>
<td>{{id}} <input type="hidden" name="id" value="{{id}}" /></td>
<td><span>{{text}}</span></td>
<td><i>{{sn}}</i> <input type="hidden" name="sn" value="{{sn}}" /></td>
<td><i>{{owner}}</i> <input type="hidden" name="owner" value="{{owner}}" /></td>
<td><input type="submit" value="Del"/></td>
</th>
</tr>
{{/messages}}
</tbody>
</table>
</form>
<thead>
<tr>
<th>ID ТМЦ</th><th>Наименование ТМЦ</th><th>Серийный номер ТМЦ</th><th>За кем числится</th>
</tr>
</thead>
<tbody>
{{#messages}}
<tr>
<td>{{id}}</td>
<td><span>{{text}}</span></td>
<td><i>{{sn}}</i></td>
<td><i>{{owner}}</i></td>
<td>
<form action="/remove" method="post" name="remove">
<input type="submit" value="Удалить"/>
<input type="hidden" name="_csrf" value="{{_csrf.token}}" />
<input type="hidden" name="sn" value="{{sn}}"/>
</form>
</td>
</tr>
{{/messages}}
</tbody>
import com.example.webapp.domain.Message;
import org.springframework.data.repository.CrudRepository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
#Transactional
public interface MessageDel extends CrudRepository<Message, Long>{
List<Message> deleteBySn (String sn);
}
#PostMapping("/remove")
public String remove (#RequestParam String sn, Map<String, Object> model) {
Message messagedel = new Message (sn);
messageDel.deleteBySn(sn);
model.put("messages", messagedel);
return "redirect:/main";
}

404 not found error for servlet

I have embedded department.jsp in create.jsp. My department.jsp has a table in which i submit data, the action is on a servlet but on submitting it is giving a 404 error for servlet.
create.jsp in body-
<header>
<img style="text-align:left" src="images.png" width="200" height="100" alt="NSIC-logo1"/>
<h1>File Tracking System</h1>
<form style="float:right;" action=" LogoutServlet" method="post">
<input type="submit" value="Logout" >
</form>
<br>
</header>
Create
<iframe style="height:530px;width:1340px " src="department.jsp" name="frame2">
<p>Your browser does not support iframes.</p>
</iframe>
department.jsp in body-
<form action="DepartmentServlet" method="post">
<center>
<table id="depart">
<thead>
<tr>
<th colspan="2">Create Department</th>
</tr>
</thead>
<tbody>
<tr>
<td>Company Name :</td>
<td><input type="text" name="company" value="" size="50" /></td>
</tr>
<tr>
<td>Department Name</td>
<td><input type="text" name="department" value="" size="50" /> </td>
</tr>
<tr>
<td>Head Office :</td>
<td><input type="text" name="place" value="" size="50" /></td>
</tr>
</tbody>
</table>
</center>
<input type="reset" value="Clear" name="Clear" />
<input type="submit" value="Submit" name="Submit" />
</form>
DepartmentServlet.java
public class DepartmentServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//request.getRequestDispatcher("link.html").include(request, response);
Cookie[] cookies = request.getCookies();
if(cookies != null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("JSESSIONID")){
System.out.println("JSESSIONID="+cookie.getValue());
break;
}
}
}
HttpSession session = request.getSession(false);
System.out.println("admin="+session.getAttribute("admin"));
if(session!=null && session.getAttribute("admin") != null){
String admin=(String)session.getAttribute("admin");
boolean status=false;
try{
String department=request.getParameter("department");
String company=request.getParameter("company");
String place=request.getParameter("place");
boolean checkd=dcheck.value(department);
boolean checkc=checkchar.value(company);
boolean checkp=checkchar.value(place);
if(checkd==true&&checkc==true&&checkp==true) {
Connection con=ConnectionProvider.getCon();
String sql="insert into department(departmentname,company,place) values (?,?,?)";
PreparedStatement pstmt =con.prepareStatement(sql);
pstmt.setString(1,department);
pstmt.setString(2,company);
pstmt.setString(3,place);
int rs=pstmt.executeUpdate();
if(rs>0){status=true;}
if(status){
PrintWriter out= response.getWriter();
out.print("values have been inserted,"+admin);
response.sendRedirect("insert.jsp");
}
else
{
PrintWriter out= response.getWriter();
out.print("failed to insert");
response.sendRedirect("notinsert.jsp");
}
}
else{response.sendRedirect("entry.jsp");}
}catch(SQLException e){}
}else{
RequestDispatcher rd = getServletContext().getRequestDispatcher("/index.html");
PrintWriter out= response.getWriter();
out.println("<font color=red>Either user name or password is wrong.</font>");
rd.include(request, response);
}
}
}

How to retrieve "Grouped" items from HTML form using Servlet?

I am having an issue with retriving "grouped" data from HTML form to servlet. I will describve the scenario below.
In companies, they record the salary of the employees once a month.When they record it, they do not do it by visiting each an every employees personal "profile" (or whatever according to the system). Instead what they do is apply the salaries of all of them in one page.
To do the above thing they prefer excel like tabular sheets.
Now, I have a html form, where the form content is a table. One row is dedicated to a one employee.
Below is my form.
<%--
Document : index2
Created on : Mar 5, 2015, 10:04:45 AM
--%>
<%#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>
<h1>Hello World!</h1>
<form method="post" action="EmployeeSampleServlet">
<table border="1" style="width:100%">
<thead>
<th>Name</th>
<th>Position</th>
<th>Salary</th>
</thead>
<tbody name="tableBody" value="1">
<tr>
<td><input type="text" name="nameTxt" style="width:100%"/></td>
<td><input type="text" name="positionTxt" style="width:100%"/></td>
<td><input type="text" name="salaryTxt" style="width:100%"/></td>
</tr>
</tbody>
<tbody name="tableBody" value="2">
<tr>
<td><input type="text" name="nameTxt" style="width:100%"/></td>
<td><input type="text" name="positionTxt" style="width:100%"/></td>
<td><input type="text" name="salaryTxt" style="width:100%"/></td>
</tr>
</tbody>
<tbody name="tableBody" value="3">
<tr>
<td><input type="text" name="nameTxt" style="width:100%"/></td>
<td><input type="text" name="positionTxt" style="width:100%"/></td>
<td><input type="text" name="salaryTxt" style="width:100%"/></td>
</tr>
</tbody>
<tbody name="tableBody" value="4">
<tr>
<td><input type="text" name="nameTxt" style="width:100%"/></td>
<td><input type="text" name="positionTxt" style="width:100%"/></td>
<td><input type="text" name="salaryTxt" style="width:100%"/></td>
</tr>
</tbody>
<tbody name="tableBody" value="5">
<tr>
<td><input type="text" name="nameTxt" style="width:100%"/></td>
<td><input type="text" name="positionTxt" style="width:100%"/></td>
<td><input type="text" name="salaryTxt" style="width:100%"/></td>
</tr>
</tbody>
</table>
<br/>
<input type="submit" value="Submit">
</form>
</body>
</html>
As you can see, I have wrapped every row with a <tbody>. The value attribute of the <tbody> will contain the employee id.
Once the form is submitted, the below servlet will capture it.
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;
public class EmployeeSampleServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String[]empId = request.getParameterValues("tableBody");
for(int i=0;i<empId.length;i++)
{
out.println(empId[i]);
}
}
// <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 {
processRequest(request, response);
}
/**
* 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 {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
What I was trying is get the value attribute of <tbody> (so I can identify the id of the employee) and get the data inside that <tbody>. However this didn't work, because I ended up with NullpointerException because it failed to read the <tbody> value.
So, how can I pass the data from table to servlet where it can clearly understand that one row is representing data belong to a one employee? If this is not the way to do it, I am also open for other methods.
That is obviously not going to work as only the input field values are submitted to the server.
You will need to discriminate the names of each input field in some way as currently you cannot match these to individual employees:
I assume you generate the table from some kind of list of employees so you could do this something like below:
<tr>
<td><input type="text" name="nameTxt_${employee.employeeId}" style="width:100%"/></td>
<td><input type="text" name="positionTxt_${employee.employeeId}" style="width:100%"/></td>
<td><input type="text" name="salaryTxt_${employee.employeeId}" style="width:100%"/></td>
</tr>
Now instead of receiving a bunch of random parameters 'nameTxt' etc., you reeive 'nameText_21', 'salaryText_21' etc. and have a means to identify the input with an employee. How you do this will depend on whether you have the list of Employees available in the Servlet on form submission.
e.g.
//employees = load the same list originally loaded for edit
for(Employee e : employees){
e.setSalary(Double.parseDouble(request.getParameter("salaryTxt_" + e.getid())));
}
Otherwise you will need to iterate the parameters for some field and proceed that way.
for(String s: request.getParameterNames()){
if(s.startsWith("nameTxt")){
//extract suffix
//load the employee with corresponding ID
//get the other params with same id
}
}
Look the below HTML, this will get all the table row-wise value and convert that as a json array. Now you can pass this array to servlet via ajax.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sample</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<table border="1" id="mytable" border="1" >
<thead>
<th>Name</th>
<th>Position</th>
<th>Salary</th>
</thead>
<tbody>
<tr>
<td><input type="text" name="nameTxt" value="12" /></td>
<td><input type="text" name="positionTxt" value="13" /></td>
<td><input type="text" name="salaryTxt" value="14" /></td>
</tr>
<tr>
<td><input type="text" name="nameTxt" value="21" /></td>
<td><input type="text" name="positionTxt" value="22" /></td>
<td><input type="text" name="salaryTxt" value="23" /></td>
</tr>
<tr>
<td><input type="text" name="nameTxt" value="31" /></td>
<td><input type="text" name="positionTxt" value="32" /></td>
<td><input type="text" name="salaryTxt" value="33" /></td>
</tr>
<tr>
<td><input type="text" name="nameTxt" value="41" /></td>
<td><input type="text" name="positionTxt" value="42" /></td>
<td><input type="text" name="salaryTxt" value="43" /></td>
</tr>
<tr>
<td><input type="text" name="nameTxt" value="51" /></td>
<td><input type="text" name="positionTxt" value="52" /></td>
<td><input type="text" name="salaryTxt" value="53" /></td>
</tr>
</tbody>
</table>
<br/>
<input type="button" value="Submit" onclick="convertValuesToJson();">
</body>
</html>
And you script looks like,
<script>
function convertValuesToJson(){
var myStringArray = [];
// Iterate each row
$('#mytable tbody tr').each(function() {
var myObject = new Object();
myObject.name = $(this).find("input[name='nameTxt']").val();
myObject.position = $(this).find("input[name='positionTxt']").val();
myObject.salary = $(this).find("input[name='salaryTxt']").val();
myStringArray.push(JSON.stringify(myObject));
});
// function for ajax goes here...
jQuery.ajax({
url: "ServletURL",
type : 'POST',
dataType: "json",
data : {"myData" : myStringArray},
error : function(jqXHR, textStatus, errorThrown) {
alert("error occurred");
}
});
}
</script>
See my updated Demo

HTTP Status 405 - HTTP method GET is not supported by this URL even with no doget() method

I'm trying to link the register information to database mysql. Everything work fine when i exported the data to the text file but when trying to connect with database, it always get this error. Here is my code I have try so far:
Register.jsp:
enter code here
<form action="./Data">
<table>
<tr>
<td> Username </td>
<td><input type ="text" name="uname" size="30"required></td>
</tr>
<tr>
<td>Your email address </td>
<td><input type ="text" name="mail" size="30"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="pass" size="20"required></td>
</tr>
<tr>
<td>Please re-type your password</td>
<td><input type="password" name="p2" size="20"required></td>
</tr>
<table>
<tr>
<td>Date of Birth</td>
<td><select name="Type">
<%for(int i=1;i<=31;i++) {%>
<option><%=i%></option>
<%}%>
</select></td>
<td>
<select name="Type">
<option>January</option>
<option>February</option>
<option>March</option>
<option>April</option>
<option>May</option>
<option>June</option>
<option>July</option>
<option>August</option>
<option>September</option>
<option>October</option>
<option>November</option>
<option>December</option>
</select>
</td>
<td>
<select name="Type">
<% for (int j=1970;j<=2010;j++) {%>
<option><%=j%></option>
<%}%>
</select>
</td>
<tr>
<td>Gender</td>
<td><input type ="radio" value="r1" checked name="Gender">Male</td>
<td><input type ="radio" value="r2" checked name="Gender">Female</td>
</tr>
<tr>
<td>
</tr>
<tr>
<td><input type="submit" value="Register" name="s4"></td>
<td><input type="reset" value="Reset" name="s5"></td>
</tr>
</table>
</form>
enter code here
Data.java:
enter code here
#WebServlet(urlPatterns = {"/Data"})
public class Data extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String user = request.getParameter("uname");
String pass = request.getParameter("pass");
String email = request.getParameter("mail");
String gender = request.getParameter("Gender");
String end = ("----------------------");
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
String connectionURL = "jdbc:mysql://localhost:8084/userinfo";
Connection con = DriverManager.getConnection(connectionURL,"root","");
Statement st = con.createStatement();
ResultSet rs;
int i = st.executeUpdate("insert into userinfo (Username, email, password) values('" + user + "','" + pass + "','" + email + "')");
if (i > 0) {
response.sendRedirect("welcome.jsp");
out.print("Registration Successfull!"+"<a href='index.jsp'>Go to Login</a>");
} else {
response.sendRedirect("index.jsp");
}
response.sendRedirect("welcome.jsp");
}
}
Your Data class extends HttpServlet which implements the doGet() method.
When the Servlet container receives any request, it will call your Servlet's service() method. In this case, that is the inherited HttpServlet#service() method which calls the HttpServlet#doGet() method. Since you haven't implemented that method, your class inherits it. In the HttpServlet class, it is implemented like so
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String protocol = req.getProtocol();
String msg = lStrings.getString("http.method_get_not_supported");
if (protocol.endsWith("1.1")) {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
} else {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
}
}
Therefore, when you send a GET request, this method will be invoked and you will get the 405 response code.
Implement your own doGet() which delegates to processRequest.
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
processRequest(req, resp);
}

Getting list of strings from servlet to jsp

I have a JSP page in which I have two tags. In first I am trying get input such as Car Maker name such as Tata, Hyundai, Toyota, Audi etc. When user selects any option in first , it should display car models from that maker such as Innova,Land Cruiser etc. So when user selects any option in first tag, I am calling a servlet which gets all the models from database in a list and setting the list as attribute of session and forwarding the request back to JSP. But in jsp when I try to fetch the list it is giving NULL POINTER EXCEPTION. How to solve it?
The code is as below:
DbReviewCar.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection conn= null;
PreparedStatement pstmt= null;
ResultSet rs;
String sql= null;
String maker= request.getParameter("make");
List modellist= new ArrayList();
/*if(maker==null)
{
modellist.add("ferrari");
modellist.add("hummer");
request.getSession().setAttribute("value", modellist);
request.getRequestDispatcher("CarReview.jsp").forward(request,response);
}
else
{*/
try {
Class.forName("com.mysql.jdbc.Driver");
conn= DriverManager.getConnection("jdbc:mysql://localhost/cardetails", "root", "Welcome123");
sql= "select model from cars where make=?;";
pstmt= conn.prepareStatement(sql);
pstmt.setString(1, maker);
rs= pstmt.executeQuery();
while(rs.next())
{
String mod= rs.getString(1);
modellist.add(mod);
System.out.println(mod+">>>>>>>>>>>>>>>>>>.");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
request.getSession().setAttribute("value", modellist);
request.getRequestDispatcher("CarReview.jsp").forward(request,response);
}
CarReview.jsp
Here is my JSP file
<form action="DbReviewCar" method="get" name="myform">
<table>
<tr>
<td>
<tr>
<td>Make:</td>
<td><select name="make" onchange="this.form.submit()"><option>select</option>
<option>Maruti</option>
<option>Ford</option>
<option>Honda</option>
<option>Skoda</option>
<option>Tata</option>
<option>Audi</option>
<option>Toyota</option></select><br></br></td>
</tr>
<%
List list = new ArrayList();
list.addAll((List) (request.getSession().getAttribute("value")));
%>
<tr>
<td>Model:</td>
<td><select name="model">
<%
for (int i = 0; i < list.size(); i++) {
%>
<option value=<%=list.get(i)%>><%=list.get(i)%></option>
<%
}
%>
</select><br></br></td>
</tr>
<tr>
<td>Rating For Style:</td>
<td><input type="text" name="style"><br></br></td>
</tr>
<tr>
<td>Rating for comfort:</td>
<td><input type="text" name="comfort"><br></br></td>
</tr>
<tr>
<td>Rating for Performance:</td>
<td><input type="text" name="performance"><br></br></td>
</tr>
<tr>
<td>Rating for FuelEconomy:</td>
<td><input type="text" name="economy"><br></br></td>
</tr>
<tr>
<td>Review:</td>
<td><textarea cols="18" rows="3"></textarea><br></br></td>
</tr>
<tr>
<td><Button>Save</Button></td>
<td><input type="reset" name="cancel" value="Cancel" /></td>
</tr>
</table>
</form>
When jsp loading for the first time the "value" atribute is not set.
Try to check null for value:
request.getSession().getAttribute("value")

Categories

Resources