How can I update changed data on button? - java

I want to edit data of the user by inputting new value in the textbox such as his first name and show these changes in his profile.
I tried to use Ajax but I don't understand what the url should be in there.
That's my jsp file with edit form and Ajax script:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<script type="text/javascript">
$("edit").click(function() {
var firstName = $(request.getParameter("firstname")).val();
$.ajax({
url: '',
type: 'POST',
data: {
firstName: firstName
}
});
});
</script>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>${title}</title>
</head>
<body>
<h4>To edit your information fill the fields, please.</h4>
<form name='f' action="${pageContext.request.contextPath}/j_spring_security_check" method='POST'>
<table>
<tr>
<td>First Name:</td>
<td><input type='text' name='firstname' id='firstname' value='${firstname}'></td>
</tr>
<tr>
<td><input name="edit" type="submit" value="Submit" /></td>
</tr>
</table>
</form>
I have update and get methods for the first name in one of the classes:
public class UserInfoDAOImpl extends JdbcDaoSupport implements UserInfoDAO {
#Autowired
public UserInfoDAOImpl(DataSource dataSource) {
this.setDataSource(dataSource);
}
//.....other methods
#Override
public void editFirstName(String userName, String fName){
String sql = "update Users set FirstName = ? where Username = ?";
Object[] params = new Object[] {fName, userName};
this.getJdbcTemplate().update(sql, params);
}
#Override
public String getFirstName(String userName) {
// TODO Auto-generated method stub
String sql = "select u.FirstName from Users u where u.Username = ? ";
Object[] params = new Object[] { userName };
String firstName = (String)getJdbcTemplate().queryForObject(sql, params, String.class);
return firstName;
}
}
So I don't really get to use these already written methods to update the data and get these changes in user profile.
I am new to Ajax so I'm glad to get any help.

You are wrong on your JSP, the j_spring_security_check is default URL Spring Login.
For updating firstname you must do #RequestMapping #ResponseBody on your Controller de handle the Ajax Request.

Related

Write to a text file from a JSP page

I can't write to a text file from JSP page. Please help me
public class UserIO {
public static void add(User user, String filepath) throws IOException {
File file = new File(filepath);
PrintWriter out = new PrintWriter(new FileWriter(file, true));
out.println(user.getEmailAddress() + "|" + user.getFirstName() + "|"
+ user.getLastName());
out.close();
}
}
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Murach's Java Servlets and JSP</title>
</head>
<body>
<%# page import="business.*, data.*"%>
<%
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String emailAddress = request.getParameter("emailAddress");
ServletContext sc = this.getServletContext();
String path = sc.getRealPath("/WEB-INF/EmailList.txt");
User user = new User(firstName, lastName, emailAddress);
UserIO.add(user, path);
%>
<h1>Thank for joining our email list</h1>
<p>Here is the information that you entered</p>
<table cellspacing="5" cellpadding="5" border="1">
<tr>
<td align="right">First Name:</td>
<td><%=user.getFirstName()%></td>
</tr>
<tr>
<td align="right">Last Name:</td>
<td><%=user.getLastName()%></td>
</tr>
<tr>
<td align="right">Email address:</td>
<td><%=user.getEmailAddress()%></td>
</tr>
</table>
<p>
To enter another email address, click on the Back <br> button in
your browser or Return button shown <br> below.
</p>
<form action="EmailRegistrationStep1.html" method="post">
<input type="submit" value="Return">
</form>
</body>
</html>
My JSP page displays the correct User class data. But i want to write user's data on EmailList.txt.
I place EmailList.txt on WEB-INF/EmailList.txt. But nothing happend in EmailList.txt.
Please help me

set Java class Object values into JSP Page

I want to set Java class Object values into JSP Page.
My Test_Object code
public class Test_Object {
public String email;
public String first_name;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
}
My test.jsp page
<%#page import="test.io.Test_Object"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>TEST</title>
</head>
<body>
<form action="loginServlet" method="post">
<table>
<tr>
<td>First Name :
<td><input type="text" value="" name="txtFirstname"
value='<%=((Test_Object) request.getAttribute("reqObj")).getFirst_name()%>' /></td>
</tr>
<tr>
<td>Email :</td>
<td><input type="text" name="txtEmail"
value='<%=request.getParameter("email")%>' /></td>
</tr>
<tr align="center">
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
My servlet code
String jb = "{\"email\":\"test#xyz.com\",\"fname\":\"test01\"}";
JSONObject jsonObject = new JSONObject(jb);
Test_Object obj = new Test_Object();
obj.email=jsonObject.getString("email");
obj.first_name=jsonObject.getString("fname");
request.setAttribute("reqObj", obj);
RequestDispatcher view = request.getRequestDispatcher("/test.jsp");
view.forward(request, response);
But when i redirect to test.jsp page there is no value display in TextBox.
I am using Eclipse Mars 2 with Java.
The problem might be in the way you are dispatching the request. In your Servlet you are dispatching the request to the /otn.jsp page. But you are trying to read the properties of the object you put in the request scope in the test.jsp page.
So you have to do the following:
In the Servlet code:
RequestDispatcher view = request.getRequestDispatcher("/test.jsp");
In the test.jsp page change the input elements as follows:
<input type="text" value="${reqObj.first_name}" name="txtFirstname"/>
<input type="text" value="${reqObj.email}" name="txtEmail" />
I am using here Expression Language with the assumption that you are using one of the current web containers such as Tomcat version 7 and later.
Some minor comments:
Why are you creating the JSONObject eventhough you are not doing anything useful with it in your Servlet code?
When you define Java types (classes, interfaces, ...) use camelcase instead of underscore in the names: use TestObject instead of Test_Object and firstName instead of first_name. Here you'll find naming conventions for Java.

Spring MVC-Response is not getting from controller using angular

I am implementing simple CRUD Operation using spring restful webservices and angular js.I trying to load all the details when the page is loading.But its not getting any response.
Controller :-
#RestController
public class EmployeeController {
public List<Employee> appList=new ArrayList<Employee>();
#RequestMapping(value="/employee",method=RequestMethod.GET)
public ModelAndView loadEmployee(){
return new ModelAndView("employee", "webemployee", new Employee());
}
#RequestMapping(value="/employees",method = RequestMethod.GET,headers="Accept=application/json")
public List<Employee>loadAllApps() {
Employee app=new Employee();
System.out.println(".........................loadAllApps.............");
app.setAppID("test_id");
app.setAppName("test_name");
appList.add(app);
return appList;
}
#RequestMapping(value="/employees/insert/{appID}/{appDescr}",method = RequestMethod.POST,headers="Accept=application/json")
public List<Employee> addApps(#PathVariable String appID,#PathVariable String appDescr) throws ParseException {
System.out.println("appID"+appID+"appDescr..........."+appDescr);
Employee app=new Employee();
app.setAppID(appID);
app.setAppName(appDescr);
appList.add(app);
return appList;
}
}
Jsp :-
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html ng-app="AppManger">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>WebService Example</title>
<script data-require="angular.js#*" data-semver="1.2.13" src="http://code.angularjs.org/1.2.13/angular.js"></script>
</head>
<div ng-controller="appController">
<div>
<table>
<tr ng-repeat="app in appList">
<td >{{ app.appID }}</td>
<td >{{ app.appName }}</td>
</tr>
</table>
</div>
<script type="text/javascript">
var appModule = angular.module('AppManger', []);
appModule.controller('appController', function ($scope,$http) {
var url="http://localhost:8080/Apps";
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$http.get(url+'/employee').
success(function(data, status, headers, config) {
alert(status);
$scope.appList = data;
});
});
</script>
</script>
</html>
when i am trying to checking status value in $http.get method.its not showing any alert message.Please let me know what issues here.
You seem to call your /employee endpoint but expecting a list of employees , because you assigning data response to the:
$scope.appList = data;
First, change that to the other endpoint you created (/employees) which returns the list.
What is the servlet-path of your mvc dispatcher servlet? This would be my first point of failure to check for. I see that you call:
var url="http://localhost:8080/Apps";
Does that mean that you deploy your app in context 'Apps' or is that your servlet path? If this is the context name then I assume that mvc is resolved to the 'root' path i.e. '/'. If not, check what is servlet path for the dispatcher and add that to your url (on the client side). This would explain why you get 404.
And also, check that you can call your API directly in the browser to rule out the server-side errors as user Chandermani suggested.

Error handling of a Custom Form Handler in ATG

I am new to ATG. And I am trying to use RepositoryFormHandler of my own. But I am not able to do the validations on the form.
Here is my .java file:
public class MyLoginBean extends RepositoryFormHandler {
private String logname;
private String logpwd;
private String message;
public String getLogname() {
return logname;
}
public void setLogname(String logname) {
this.logname = logname;
}
public String getLogpwd() {
return logpwd;
}
public void setLogpwd(String logpwd) {
this.logpwd = logpwd;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public boolean handleLogname(DynamoHttpServletRequest pRequest,
DynamoHttpServletResponse pResponse) throws ServletException,
IOException {
boolean tf=true;
if(logname.isEmpty() || logname==null)
{
tf=false;
setMessage("User name can't empty");
}
System.out.println("inside logname");
return tf;
}
public void handleFormException(DropletFormException exception,
DynamoHttpServletRequest request, DynamoHttpServletResponse response) {
// TODO Auto-generated method stub
super.handleFormException(exception, request, response);
}
}
And here is my .jsp file:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="/dspTaglib" prefix="dsp" %>
<dsp:importbean bean="/atg/dynamo/droplet/ErrorMessageForEach"/>
<dsp:importbean bean="/dynamusic/MyLoginBean"/>
<!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=ISO-8859-1">
<title>Custom Login</title>
</head>
<body>
<dsp:form style="color:white">
<table style="background:#3b5998">
<tr>
<td>
<ul>
<dsp:droplet name="ErrorMessageForEach">
<dsp:param bean="MyLoginBean.formExceptions" name="exceptions"/>
<dsp:oparam name="output">
<li>
<dsp:valueof param="message"/>
</li>
</dsp:oparam>
</dsp:droplet>
</ul>
</td>
</tr>
<tr>
<td>
User Name:
</td>
<td>
Password:
</td>
</tr>
<tr>
<td>
<dsp:input type="text" name="logname" bean="MyLoginBean.logname"> </dsp:input>
</td>
<td>
<dsp:input type="password" name="logpwd" bean="MyLoginBean.logpwd"> </dsp:input>
</td>
<td>
<dsp:input type="submit" bean="MyLoginBean.login"> </dsp:input>
</td>
</tr>
</table>
</dsp:form>
</body>
</html>
This is all I've tried so far and still trying something else.
Please suggest the solution for it and also tell me the mistakes, if any, in the code pasted here.
Don't override handleFormException
Instead of using setMessage, use ATG's built-in behavior. All form handlers inherit a Vector of form exceptions from the GenericFormHandler superclass. To add an error, use:
addFormException(new DropletException("Your error message"));
Then, at the end of your method, call:
return checkFormRedirect(getSuccessUrl(), getFailUrl(), pRequest, pResponse);
This checks if any form exceptions have been added, and if so, redirects to the failUrl, otherwise redirects to the successUrl.
By convention, you should name your form handler *FormHandler, for example ProfileFormHandler, BillingInfoFormHandler, PaymentInfoFormHandler etc.
Hope this helps. See http://docs.oracle.com/cd/E22630_01/Platform.1002/apidoc/atg/droplet/GenericFormHandler.html#getFormExceptions()

Creating table according to selected item in DropdownList From Servlets?

I have a List collection which keeps list of manager and employee names from DB. And I have another list which holds project list in a dropdownlist... When one project is selected then table must be created according to this projecet's emloyees and manager in a table... For example...
AndroidApp project selected from dropdown Then It should create a table which have names of manager and employees like this... Html table... I tried to create with jstl but i couldnt do it.
|manager| Employee|
Susan | John
Susan | Joe
Susan | Megan
I'm developing web-app projecet with Java platform.. I have Servlets, JSP's, DB to do that. I coded Lists etc. I think my problem at this point is html coding or what else could be? My codes...
Related JSP page which is projects...
<%#page import="com.eteration.leavesystem.model.Person"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.io.*,java.util.*,java.sql.*"%>
<%# page import="javax.servlet.http.*,javax.servlet.*"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%# page session="true" %>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="">
<select name="projects" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select> <input type="submit" value="Kaydet">
</form>
<br>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(function(){
$("#addProject").click(function(){
$(this).next().slideToggle();
});
});
</script>
<button id="addProject">Proje Ekle</button>
<div style="display:none;">
<form action="./UserProjectServlet" method="POST">
<input type="text" name="AddedProject" /><br/>
<button class="hidden">Ekle</button>
</form>
</div>
<form action="./PopulateProjectServlet" method="get">
<select name="selectedProject" id="selectedProject" onchange= "this.form.submit()" >
<c:forEach items="${projects}" var="project">
<option value="${project.code}">${project.desc}"</option>
</c:forEach>
<table border="1" cellpadding="5">
<caption><h2>List of users</h2></caption>
<tr>
<th>Manager</th>
<th>Employees</th>
</tr>
<c:forEach items="${projectTable}" var="projectTable">
<tr>
<td><c:out value="${projectTable.pm.name}" /></td>
<td><c:out value="${projectTable.e.name}" /></td>
</tr>
</c:forEach>
</table>
</select>
</form>
</body>
</html>
I succeeded listing projects to dropdown and getting selected values id from it. Then I did onchange method to list projects informations which have names.
My result class which lists project tables info (names)
public class ProjectResultTableView {
static mysqlCon con=new mysqlCon();
public static List<ProjectTable> getProjectInfo(String projectId) throws SQLException {
List<ProjectTable> projectTableList = new ArrayList<ProjectTable>();
String query = "SELECT distinct e.name AS employee_name, pm.name AS manager_name FROM project_employee AS pe LEFT OUTER JOIN employee AS e ON e.employee_id = pe.employee_id LEFT OUTER JOIN project AS p ON p.project_id = pe.project_id LEFT OUTER JOIN employee AS pm ON pm.employee_id = p.manager_id WHERE pe.project_id =" +projectId+ " ;";
Statement stmt = con.getConnection().createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs!=null){
while (rs.next()) {
projectTableList.add(new ProjectTable(rs.getString("pm.name"),rs.getString("e.name")));
}
}
con.getConnection().close();
return projectTableList;
}
}
My SERVLET
#WebServlet("/ProjectResultServlet")
public class ProjectResultServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public ProjectResultServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String selectedProject = request.getParameter("selectedProject");
List<ProjectTable> projectTable = ProjectResultTableView.getProjectInfo(selectedProject);
request.setAttribute("projectTable", projectTable);
request.getRequestDispatcher("/UserHome/Projects.jsp").forward(request, response);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.getRequestDispatcher("/UserHome/Projects.jsp").forward(request, response);
}
}
So I think its about jstl or somethhing in my html code. If there is more wrongs please help me.. My question is how can I create a table according to selected project without submitting button. I want to use onchange or something like do the same thing :) Thanks in advance...
As you are already using Jquery, you can catch the onchange event. Using the selectedproject do an Ajax get to the servlet and retrieve the new table. Load the result data into a DIV.
see http://api.jquery.com/jQuery.get/

Categories

Resources