how to send json objetct to servlet? - json

jsp code:
<script>
//login
function submitForm(thisObj, thisEvent) {
var userName = $('#userName').val();
var pwd = $('#pwd').val();
var myData = {
"mydata": {"userName": userName, "pwd" : pwd}
};
$.ajax({
type: "POST",
url: "/login",
data: {
jsonData: JSON.stringify(myData)
},
dataType: "json"
});
return false;
}
</script>
<tr><td><input type="text" id="userName" name="userName" size="30" maxlength="30"></td></tr>
<tr><td><input type="password" id="pwd" name="pwd" size="30" maxlength="30"></td></tr>
<tr><td><button class="button" type="submit" value="Login" name="Submit" accesskey="s" onClick="return submitForm(this,event)">LOG IN</button></td></tr>
servlet:
public class login extends HttpServlet {
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
res.setContentType("application/json");
PrintWriter out = res.getWriter();
StringBuffer sbuffer = new StringBuffer();
String inLine = null;
String sUsername = "";
try{
BufferedReader reader = req.getReader();
while ((inLine = reader.readLine()) != null)
sbuffer.append(inLine);
if (sbuffer.length() != 0){
JSONObject jsObj = new JSONObject(sbuffer.toString());
sUsername = jsObj.optString("userName");
sPwd = jsObj.optString("pwd");
}
}catch(Exception e){
out.println(retResponse("E","error"));
return;
}
sUsername = sUsername.trim();
sPwd = sPwd.trim();
}
}
web.xml:
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
I would like to pass my login/pwd to server side for validation by using json and servlet.
I'm newbie on json.I reference to online example and develop above code. But it not works. Do anyone know what my coding wrong? my already put by login.class under WEB-INFO folder.

I got what I'm wrong. Its work after I change the ajax lib. from http://ajax.googl... to https://ajax.googl...

Related

How to send a post request to the Spring controller using ajax

I want to send a post request to the spring controller using ajax. But it doesn't work. I would be grateful if anyone could tell me, what I have done worngly.
$("#myprofile").on('submit',function(e){
console.log("in changes ave"+ $("#firstname").val());
console.log("in changes ave"+ $("#lastname").val());
console.log("in changes ave"+ $("#current_password").val());
console.log("in changes ave"+ $("#new_password").val());
var myJSON = JSON.stringify({
"firstname" : $("#firstname").val(),
"lastname" : $("#lastname").val(),
"current_password" : $("#current_password").val() ,
"new_password" : $("#new_password").val()
});
$.ajax({
type : "POST",
url : "/edit_profile",
dataType:"json",
contentType: "application/json",
data : myJSON,
success : function(mydataa) {
console.log("Successful")
},
error: function(dataa){
alert(dataa.responseText)
}
});
})
Here is my controller:
#ResponseBody
#RequestMapping(value = "/edit_profile", method = RequestMethod.POST, consumes = "application/json")
public ModelAndView editProfile(#RequestParam("firstname") String firstname,
#RequestParam("lastname") String lastname, #RequestParam("new_password") String new_password,
#RequestParam("current_password") String current_password) {
ModelAndView modelAndView = new ModelAndView();
//some logic here
user = profileRepository.changeUserInformation(user, firstname, lastname, new_password, current_password);
}
modelAndView.setViewName("profile");
return modelAndView;
}
And here is my html page:
<form class="col" id="myprofile">
<input type="text" class="form-control border-0" name="firstname" id="firstname" th:value="${currentUser.firstname}">
<input type="text" class="form-control border-0" name="lastname" id="lastname"
th:value="${currentUser.lastname}">
<input type="password" class="form-control border-0" placeholder="current password" name="current_password" id="current_password">
<input type="password" class="form-control border-0" placeholder="new password" name="new_password" id="new_password">
<input type="password" class="form-control border-0" name="confirm_password"
id="confirm_password" placeholder="confirm new password">
<button id = "changesave-btn" type="submit" class="save button-2">SAVE CHANGES</button>
</form>
I get Error 400 Bad request as the message returned from the alert line and I see this output in my console:
Required String parameter 'firstname' is not present
Thanks in advance,
Since you send a JSON payload, there is no request parameter.
Create a POJO to store the Ajax POST data.
public class MyProfile {
private String firstname;
private String lastname;
private String new_password;
private String current_password;
public MyProfile() {
}
// getter/setter ..
}
Accept the Ajax POST data with #RequestBody
#ResponseBody
#RequestMapping(value = "/edit_profile", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public ModelAndView editProfile(#RequestBody MyProfile myProfile) {
// ...
}

how to display the values entered by a user in form in a servlet program on tomcat? [duplicate]

This question already has answers here:
Generate an HTML Response in a Java Servlet
(3 answers)
Closed 5 years ago.
I am running a example of form in which i have three fields 'name', 'email', 'pass'.
Now i want to display the values which are entered by the user, along with the message "You are successfully registered".
I'm using tomcat 8.5, JDK 1.8 and SQL Community 5.6
index.html
<html>
<head>
<title>Register form</title>
</head>
<body>
<form method="post" action="register">
Name:<input type="text" name="name" /><br/>
Email ID:<input type="text" name="email" /><br/>
Password:<input type="text" name="pass" /><br/>
<input type="submit" value="register" />
</form>
</body>
</html>
Register.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Register extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
String email = request.getParameter("email");
String pass = request.getParameter("pass");
try{
//loading drivers for mysql
Class.forName("com.mysql.jdbc.Driver");
//creating connection with the database
Connection conn=DriverManager.getConnection
("jdbc:mysql://localhost:3306/studentdb","root","root");
PreparedStatement ps=conn.prepareStatement
("insert into Student values(?,?,?)");
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, pass);
int i=ps.executeUpdate();
if(i>0)
{
out.println("You are sucessfully registered");
}
String query = "SELECT * FROM student";
// create the java statement
Statement st = conn.createStatement();
// execute the query, and get a java resultset
ResultSet rs = st.executeQuery(query);
// iterate through the java resultset
while (rs.next())
{
rs.getString("name");
rs.getString("email");
rs.getString("pass");
// print the results
System.out.format("%s, %s, %s\n", name, email, pass);
System.out.print("name: " + name);
System.out.print(", email: " + email);
System.out.print(", pass: " + pass);
}
st.close();
}
catch(Exception se)
{
se.printStackTrace();
}
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
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" >
<servlet>
<servlet-name>register</servlet-name>
<servlet-class>Register</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>register</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
Now What code should i add in order to display the user entered values on the screen?
First of all ,Because of you used Servlet, you need to use JSP instead of html;
and then, you should make sure your form action's path;
<form action="${ pageContext.request.contextPath }/register" method="post">
if you don't use EL Expression,try to use the following one
<form action="/register" method="post">
java:
String name = request.getParameter("name");
String email = request.getParameter("email");
String pass = request.getParameter("pass");
System.out.print("name: " + name);
System.out.print(", email: " + email);
System.out.print(", pass: " + pass);
Lastly,you'd better use the MVC later.

How to call a DAO method from a Json Servlet

I have a dependency dropdown list in my JSP. I have a json servlet where I populate the second dropdown. Based on the selection made for the first dropdown will determine the second dropdown. I have hardcoded values within the jsonServlet class but I want to be able to call a query from my DAO method. How would I go about this?
JsonServlet:
package master.service;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import master.dao.MasterDataDao;
import master.dto.SiteDto;
import com.google.gson.Gson;
/**
* Servlet implementation class JsonServlet
* #param <E>
*/
public class JsonServlet<E> extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
MasterDataDao masterDataDao = new MasterDataDao();
String divisionIdName = request.getParameter("divisionIdName");
List<String> list = new ArrayList<String>();
List<SiteDto> site = new ArrayList<SiteDto>();
String json = null;
if (divisionIdName.equals("33") || divisionIdName.equals("36")) {
try {
site.equals(masterDataDao.getAllJJSites());
for (Iterator<SiteDto> iter = site.iterator(); iter.hasNext(); ){
SiteDto element = iter.next();
list.addAll(-1, element);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (Iterator<SiteDto> iter = site.iterator(); iter.hasNext(); ){
SiteDto element = iter.next();
}
} else if (divisionIdName.equals("Select Division")) {
list.add("Select Site");
} else {
try {
site.equals(masterDataDao.getAllSites());
for (Iterator<SiteDto> iter = site.iterator(); iter.hasNext(); ){
SiteDto element = iter.next();
list.addAll(-1, element);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
json = new Gson().toJson(list);
response.setContentType("application/json");
response.getWriter().write(json);
}
}
Based off the divisionID selection in my JsonServlet, if the divisionID is either 33 or 36 i'd like to call this method in my MasterDataDao class:
public List<SiteDto> getAllJJSites() throws IOException, ClassNotFoundException, SQLException {
List<SiteDto> siteDtoList = new ArrayList<SiteDto>();
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
String query = "Select Distinct Name, Id From Addtl_Type Where Addtl_Type.is_active = '1' And Data_Field_Id = 3050 Order By Name";
con = getConnection();
ps = con.prepareStatement(query);
rs = ps.executeQuery();
// System.out.println("&*******" + rs.getFetchSize());
while (rs.next()) {
SiteDto siteDto = new SiteDto();
siteDto.setId(rs.getString("Id"));
siteDto.setName(rs.getString("Name"));
siteDtoList.add(siteDto);
}
} finally {
cleanUp(con, ps, rs);
}
return siteDtoList;
}
Otherwise if it is another selection value(besides Select Division), I'd like to call this method with the MasterDataDao class:
public List<SiteDto> getAllSites() throws IOException, ClassNotFoundException, SQLException {
List<SiteDto> siteDtoList = new ArrayList<SiteDto>();
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
String query = "Select Distinct Name, Id From Addtl_Type Where Addtl_Type.is_active = '1' And Data_Field_Id = 105 Order By Name";
con = getConnection();
ps = con.prepareStatement(query);
rs = ps.executeQuery();
// System.out.println("&*******" + rs.getFetchSize());
while (rs.next()) {
SiteDto siteDto = new SiteDto();
siteDto.setId(rs.getString("Id"));
siteDto.setName(rs.getString("Name"));
siteDtoList.add(siteDto);
}
} finally {
cleanUp(con, ps, rs);
}
return siteDtoList;
}
Is this possible to do within the JsonServlet? If so how? Thanks in advance.
Please let me know if more information is needed.
Also I have included my JSP here. Initially I had made a call to the DAO from here. I referenced a bean.
JSP:
<script>
$(document).ready(function() {
$('#divisionId').change(function(event) {
var divisionId = $("select#divisionId").val();
$.get('JsonServlet', {
divisionIdName : divisionId
}, function(response) {
var select = $('#siteId');
select.find('option').remove();
$.each(response, function(index, value) {
$('<option>').val(value).text(value).appendTo(select);
});
});
});
});
</script>
</head>
<body>
<form name="input" action="getMasterData" method="get">
<br /> <br />
<h1 align='center'>Master Data File</h1>
<br /> <br />
<table border="0" align='center'>
<tr>
<td>
<h2>Division</h2>
</td>
<td align='left'><jsp:useBean id="masterDaoUtil"
class="master.dao.util.MasterDataConstants" />
<select name="divisionId" id="divisionId">
<option>Select Division</option>
<option value="33">
<%=MasterDataConstants.DIVISION_TYPE_AUDIT_MANAGEMENT_GLOBAL_NAME%></option>
<option value="31">
<%=MasterDataConstants.DIVISION_TYPE_CHANGE_MANAGEMENT_GLOBAL_NAME%></option>
<option value="34">
<%=MasterDataConstants.DIVISION_TYPE_DEA_MANAGEMENT_GLOBAL_NAME%></option>
<option value="35">
<%=MasterDataConstants.DIVISION_TYPE_EHS_MANAGEMENT_GLOBAL_NAME%></option>
<option value="23">
<%=MasterDataConstants.DIVISION_TYPE_EVENT_MANAGEMENT_GLOBAL_NAME%></option>
<option value="36">
\
<%=MasterDataConstants.DIVISION_TYPE_QUALITY_EVENT_MANAGEMENT_GLOBAL_NAME%></option>
<option value="40">
<%=MasterDataConstants.DIVISION_TYPE_NORAMCO_AUDIT_MANAGEMENT_GLOBAL_NAME%></option>
<option value="43">
<%=MasterDataConstants.DIVISION_TYPE_NORAMCO_CHANGE_MANAGEMENT_GLOBAL_NAME%></option>
<option value="41">
<%=MasterDataConstants.DIVISION_TYPE_NORAMCO_DEA_MANAGEMENT_GLOBAL_NAME%></option>
<option value="42">
<%=MasterDataConstants.DIVISION_TYPE_NORAMCO_EHS_MANAGEMENT_GLOBAL_NAME%></option>
<option value="44">
<%=MasterDataConstants.DIVISION_TYPE_NORAMCO_EVENT_MANAGEMENT_GLOBAL_NAME%></option>
</select></td>
</tr>
<tr>
<td>
<h2>Site Name</h2>
</td>
<td align='left'>
<%-- <jsp:useBean id="masterDao"
class="master.dao.MasterDataDao" />
--%>
<select name="siteId"
id="siteId">
<option>Select Site</option>
<%-- <option value="0">ALL</option>
<c:forEach items="${masterDao.allSites}" var="siteDto">
<option value="${siteDto.id}">${siteDto.name}
</option>
</c:forEach>
--%>
</select></td>
</tr>
</table>
<br /> <br />
<div style="text-align: center">
<input type="submit" value="Submit">
</div>
</form>
<%
if (request.getAttribute("message") != null) {
%>
<p>
<font size=4 color="red"> Master_Data(timestamp).xlsx and
Consistency_Check_Data(timestamp).xlsx are located under
d:/stage/MasterDataReports <%--Master_Data(timestamp).xlsx and Consistency_Check_Data(timestamp).xlsx are located under /jsc/ets/u02/tools7/apache-tomcat-7.0.55/webapps/MasterData/MasterDataReport--%>
</font>
</p>
<%
}
%>
Originally before I used JSON and AJAX I used this statement for the options which is now commented out.
<%-- <jsp:useBean id="masterDao"
class="master.dao.MasterDataDao" />
--%>
<select name="siteId"
id="siteId">
<option>Select Site</option>
<%-- <option value="0">ALL</option>
<c:forEach items="${masterDao.allSites}" var="siteDto">
<option value="${siteDto.id}">${siteDto.name}
Is there a way I can leverage this? Maybe can I make a function call to the JSP from my servlet? I know this is not good practice but I cannot think of another way. I need to get the siteDto.id value as well as the siteDto.name value.
Thanks in advance
Create an interface and implementation DAO like IMasterDataDAO and MasterDataDAOImpl.
In case if you get more if..else condition in future then use switch..case instead of if..else.
Create an object for DAO using the interface in servlet like below:
IMasterDataDAO masterDAO = new MasterDataDAOImpl()
then call either masterDAO.getAllJSites() or masterDAO.getAllSites() based on the condition.

How to display retrieved image from mysql in jsp. I am using struts2 and tiles

I am using strust2 and tiles for my project. Here is the code (jsp) for entering an ID.
<s:textfield name="uniqueID" label="Enter Unique ID" required="required"/>
Here is the action file.
public String execute() throws Exception{
SearchDao.search(selectedID,uniqueID);
return SUCCESS;
}
The dao will retrieve image.
try{
.
.
.
rs = ps.executeQuery();
if(rs.next()){
InputStream originalImageStream = rs.getBinaryStream(1);
File file = new File("Retina"+".jpg");
FileOutputStream fileOutputStream = new FileOutputStream(file);
while ((length = originalImageStream.read()) != -1) {
fileOutputStream.write(length);
}
fileOutputStream.close();
}
else{
return null;
}
}
catch(Exception ex){
ex.printStackTrace();
}
return "found";
Once the image is found this will return found and so action file will return success. Code in struts.xml is
<action name="search" class="com.ActionClasses.SearchAction">
<result name="success" type="tiles"> found </result>
<result name="input" type="tiles"> search </result>
<result name="error" type="tiles"> notFound </result>
</action>
here is the tiles.xml file.
<definition name="found" extends="home">
<put-attribute name="myTitle" value="searchSuccess"/>
<put-attribute name="myBody" value="/found.jsp"/>
</definition>
Now how can I display the retrieved image in found.jsp. I found some solutions in Internet but only for projects that uses struts2 or struts2 along with hibernate. I didn't find any solution for projects that use both strus2 and tiles. Can anyone help me. Thank you.
Try this out ... I have implemented the similar scenario in one of my projects but in spring, I guess it should work for you with little changes
This is what I had implemented. I created a controller (aka action in struts) like below
#RequestMapping(value = "view", method = RequestMethod.GET)
public void getImage(#RequestParam(value = "location") String location, HttpServletResponse response) {
String ext = FilenameUtils.getExtension(location);
response.setContentType("image/"+ext);
try {
File file = new File(location);
BufferedImage image = ImageIO.read(file);
OutputStream baos = response.getOutputStream();
ImageIO.write(image, ext, baos);
baos.flush();
baos.close();
} catch (FileNotFoundException e) {
logger.error("File Not Found: " + location, e);
} catch (IOException e) {
logger.error("Can't read the File: " + location, e);
} catch(Exception e) {
logger.error("Can't read input file: " + location, e);
}
return;
}
And then in the controller/action that server the actual view I did something like this
final String IMAGE_RESOLVER = "../../image/view?location=";
Game game = gameService.populateGame(gameId);
if(game.getThumbnailPath() != null) {
game.setThumbnailPath(IMAGE_RESOLVER.concat(game.getThumbnailPath()));
}
mv.addObject("game", game); // set object to return to view
When the DOM object with name "thumbnail" receives this string it calls the action mentioned above which returns it an image
Hope this works for you

Losing data (specifically, the apostrophes) from HTML form to Java Servlet

Reference: HTML forms, php and apostrophes
I've been trying to pass data from my HTML form to my servlet for processing. However, I noticed that I'd lose the apostrophes in the text inputs. I'm not sure if this is a client or server side processing error, but looking through the reference above, i think i need to do some processing on the servlet side? Tried looking for a servlet alternative to the above but couldn't find any.
Here's the code snippets:
Html form:
<form method="post" action="CreateThreadServlet">
<b>Title</b><br>
<input type="text" name="title" size="60%" placeholder="Enter your title here"/><br>
<br><b>Tags</b><br>
<input type="text" name="tags" placeholder="Additional Tags: comma separated, e.g. Gamification, Java" size="60%" /><br>
<br><b>Details</b><br>
<textarea name="content" style="width:100%;height:50%"></textarea>
<input type="hidden" name="nick" value=<%=nick%>>
<input type="hidden" name="userid" value=<%=userid%>>
<button type="button" style='float: right;' onClick="closeDimmer()">Cancel</button>
<input type="submit" name="Submit" value="Submit" text-align='center' style='float: right;'>
</form>
This is the servlet code that processes the form:
String userid = req.getParameter("userid");
String nick = req.getParameter("nick");
String title = null; //tried using the URLDecoder, doesn't work
try {
title = URLDecoder.decode(req.getParameter("title"), "UTF-8");
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(CreateThreadServlet.class.getName()).log(Level.SEVERE, null, ex);
}
String tags = req.getParameter("tags");
String[] tagStr = tags.split(",");
String[] addTags = req.getParameterValues("addTags");
PLEASE HELP THE NEWBIE.
As this link explains you could simply config a filter
<filter>
<filter-name>HitCounterFilter </filter-name>
<filter-class>
net.my.filters.HitCounterFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>HitCounterFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
having this:
public final class HitCounterFilter implements Filter {
private FilterConfig filterConfig = null;
public void init(FilterConfig filterConfig)
throws ServletException {
this.filterConfig = filterConfig;
}
public void destroy() {
this.filterConfig = null;
}
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (request.getCharacterEncoding() == null) {
request.setCharacterEncoding("UTF-8");
}
chain.doFilter(request, wrapper);
}
}
so you force an UTF-8 encoding.