How do i call a servlet from a method?
One method is started by a button and I want that method to start the servlet but, I'm having difficultly because it's a servlet??
I want setRc to call doGet which, in-turn, calls processRequest.
public class rc extends HttpServlet {
public void setRc(String rc) throws ServletException, IOException {
rc test = new rc();
test.doGet(null, null);
this.rc = rc;
}
public String getRc() {
return rc;
}
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("FROM doGet");
response.setContentType("text/xml");
//this is where the debugger quits...
PrintWriterout = response.getWriter();
processRequest(request, response);
setRc(rc);
}
public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
name = request.getParameter("rc");
IP = request.getRemoteAddr();
FileWriter fstream = new FileWriter("C:\\commands\\IPLog\\IP.txt");
BufferedWriter txt = new BufferedWriter(fstream);
txt.write(IP);
txt.close();
Process p = Runtime.getRuntime().exec("c:\\commands\\psexec \\\\" + IP + " -s -i C:\\Windows\\System32\\mstsc.exe /v:" + name);
}
}
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Index</title>
</head>
<body>
<jsp:useBean id="info" scope="session" class="org.mypackage.WebTools.info" />
<jsp:setProperty name="info" property="info" />
<jsp:useBean id="hinv" scope="session" class="org.mypackage.WebTools.hinv" />
<jsp:setProperty name="hinv" property="hinv" />
<jsp:useBean id="rc" scope="session" class="org.mypackage.WebTools.rc" />
<jsp:setProperty name="rc" property="rc" />
<jsp:useBean id="remx" scope="session" class="org.mypackage.WebTools.remx" />
<jsp:setProperty name="remx" property="remx" />
<jsp:useBean id="SOne" scope="session" class="org.mypackage.WebTools.SOne" />
<jsp:setProperty name="SOne" property="SOne" />
<b><font color="blue">Please Enter your Full Name here:</font></b><br>
<form name="frm" method="get" action="rc.java">
<table border = "0">
<tr align="left" valign="top">
<td>First Name:</td>
<td><input type="text" name ="name" /></td>
</tr>
<tr align="left" valign="top">
<td></td>
<td><input type="submit" value="submit"/></td>
</tr>
</table>
</form>
<%-- --%>
<table border="1">
<tbody>
<tr>
<td><img src="UBLogo.jpg" class ="ublogo" alt="UBLogo"/></td>
<td><strong>RDWeb</strong><img src="RD.png" class ="rd" alt="UBLogo"/></td>
</tbody>
</table>
<table border="1">
<thead>
<tr><th colspan="2">Welcome to Web Tools</th><br>
<th colspan="2">${UserDetails.displayName0}
<br>${UserDetails.Full_User_Name0}</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<form name="info" action="index.jsp">
Enter the UB ID, User Name or Computer Name:</td>
<td><input type="text" name="info" />
<input type="submit" value="OK" />
</form>
</td>
<td><strong>Contact Details: </strong></td>
<td><strong>Email: </strong>${UserDetails.mail0}
<br><strong>IM: </strong>${UserDetails.givenName0} ${UserDetails.sn0}
<br><strong>phone:</strong>${UserDetails.telephoneNumber0}
<br><span style="font-size:smaller; font-style:italic;">
<em>last login: ${UserDetails.Login_Date}</em></span></td>
</tr>
<tr>
<td><strong>AD Site</strong></td>
<td><strong>${UserDetails.AD_Site}</strong></td>
<td><strong>Computer</strong></td>
<td><strong>PC: ${UserDetails.Computer_Name}</strong>
<br><strong>OS: ${UserDetails.Network_Operating_System0}</strong>
<br><strong>IP: ${UserDetails.IP_Address}</strong></td>
</tr>
<tr>
<td>
<form name="hinv" action="index.jsp" />
Hardware Inventory:<input type="submit" value="${UserDetails.Computer_Name}" onsubmit=jsp:setProperty name="hinv"/>
</form>
</td>
<td>
<form name="rc" action="index.jsp" />
Remote Control:<input type="submit" value="${UserDetails.Computer_Name}" onsubmit=jsp:setProperty name="rc"/>
</form>
</td>
<td>
<form name="remx" action="index.jsp" />
RemX_OKillX.exe:<input type="submit" value="${UserDetails.Computer_Name}" onsubmit=jsp:setProperty name="remx"/>
</form>
</td>
<td>
<form name="SOne" action="index.jsp" />
5685-SourceOne.exe:<input type="submit" value="${UserDetails.Computer_Name}" onsubmit=jsp:setProperty name="SOne"/>
</form>
</td>
</tr>
</tbody>
</table>
<br>
<table border="1">
<tbody>
<tr>
<c:forEach var="columnName" items="${result.columnNames}">
<th><c:out value="${columnName}"/></th>
</c:forEach>
</tr>
<!-- column data -->
<c:forEach var="row" items="${result.rowsByIndex}">
<tr>
<c:forEach var="column" items="${row}">
<td><c:out value="${column}"/></td>
</c:forEach>
</tr>
</c:forEach>
</tbody>
</table>
</body>
</html>
RequestDispatcher reqDisp = new RequestDispatcher("index.jsp");
reqDisp.forward(request,response);
or
reqDisp.forward(request,response);
or other way is
response.sendRedirect("/url to call");
RequestDispatcher
forward method pass the control of the request to another servlet or jsp without telling anything about the request dispatch to the client browser. Therefore client browser don't know whether the returned resource is from an another servlet/jsp or not.
sendRedirect
method stop further processing of the request and send http status code "301" and URL of the location to be redirected to the client browser in the response header. Server does not have control of this request after sending the redirect related HTTP header to the client browser. Client browser sees http status 301 and then it know it should send a new request to the url in "Location" http header which is set by server. and Client browser sends a new request to the new URL and it will be processed by the server as another normal request.
Therefore request dispatch happens completely in the server side.
But sendRedirect is handle through the client browser.
Related
Im doing a CRUD app with Java using Servlets and i have a jsp file as a list of many users where i have a button to edit my row. As i click on my button it should redirect me to ServletPacientes?Param=editar&dni=<%a.getDni()%>.
So this is my ListarPacientes.jsp: Where i have some scriplets and my html forms.
<body>
<% if (request.getSession().getAttribute("usuario") == null) {
request.getRequestDispatcher("Login.jsp").forward(request, response);
throw new UsuarioNoLoggeadoException();
}
Usuario user = (Usuario)request.getSession().getAttribute("usuario");
if (user.getTipo_usuario().getID() != 1) {
request.getRequestDispatcher("Home.jsp").forward(request, response);
throw new UsuarioSinPermisoException();
}
%>
<%
if (request.getParameter("buscarLista") == null) {
request.getRequestDispatcher("ServletPacientes?Param=list").forward(request, response);
}
List<Paciente> listaM = new ArrayList<Paciente>();
if (request.getAttribute("listaPac") != null) {
listaM = (List<Paciente>)request.getAttribute("listaPac");
}
%>
<jsp:include page="Menu.jsp"></jsp:include>
<div class="table-title">
<h3>Tabla Pacientes</h3>
</div>
<form method="post" action="ServletPacientes">
<div class="form-group">
<label>Buscar: </label>
<input type="text" class="form-control" name="txtBuscar">
</div>
<div class="col-12">
<input type="submit" class="btn btn-success" value="Buscar" name="btnBuscar">
</div>
<table class="table-fill">
<thead>
<tr>
<th class="text-left">Nombre</th>
<th class="text-left">Apellido</th>
<th class="text-left">DNI</th>
<th class="text-left">Sexo</th>
<th class="text-left">Direccion</th>
<th class="text-left">Fecha de Nacimiento</th>
<th class="text-left">Email</th>
<th class="text-left">Telefono</th>
<th class="text-left">Nacionalidad</th>
</tr>
</thead>
<tbody class="table-hover">
<tr>
<%
for (Paciente a : listaM) {
%>
<tr>
<form action="ServletPacientes" method="post">
<td><%=a.getNombre()%></td>
<td><%=a.getApellido()%></td>
<td><%=a.getDni()%> <input type="hidden" name="dniPaciente" value="<%=a.getDni()%>" ></td>
<td><%=a.getSexo()%></td>
<td><%=a.getDireccion()%></td>
<td><%=a.getFechaNac()%></td>
<td><%=a.getCorreo()%></td>
<td><%=a.getTelefono()%></td>
<td><%=a.getNacionalidad()%></td>
<td> <input type="submit" name="btnEliminar" value="Eliminar" class="btn btn-danger"></td>
</form>
<td> <input type="submit" name="btnEditar" value="Editar" class="btn btn-warning"></td>
</tr>
<%
}
%>
</tbody>
</table>
<br>
<div align="center">
</div>
</form>
</body>
As you can see i have de following tags
<td> <input type="submit" name="btnEditar" value="Editar" class="btn btn-warning"></td>
So in each row i have this button where i call my Controller (Servlet) with the parameter "editar" and i pass the method getDni() of my class Paciente.
And here is my code of my ServletPacientes:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(request.getParameter("Param")!=null)
{
String opcion = request.getParameter("Param").toString();
switch (opcion) {
case "previoInsert":
{
break;
}
case "list":
{
request.setAttribute("listaPac", negPac.listarPacientes());
RequestDispatcher dispatcher = request.getRequestDispatcher("/ListarPacientes.jsp?buscarLista=1");
dispatcher.forward(request, response);
break;
}
case "editar":
{
Paciente p = new Paciente();
p = negPac.obtenerUno(request.getParameter("dniPaciente"));
System.out.println(p);
request.setAttribute("dniPac", p);
RequestDispatcher dispatcher = request.getRequestDispatcher("/EditarPaciente.jsp");
dispatcher.forward(request, response);
break;
}
default:
break;
}
}
}
The method above shows a switch where each case is a different parameter that im passing to my route. So when i click on my edit button instead of taking me to for example ServletPacientes?Param=editar&dni=20216447 it just redirects me to ServletsPacientes which is a blank page.
It looks like im never receiving the parameter editar neither the dni property. Becaus if i manually put on my url ServletPacientes?Param=editar&dni=20216447 it does takes me to the Edit view.
You essentially have the following structure:
<form method="post" action="ServletPacientes">
<a href="ServletPacientes?Param=editar&dni=<%=a.getDni()%>">
<input type="submit" value="Editar">
</a>
</form>
This means that when you click on this "Editar" button, a form submission will happen as a POST request. This request is supposed to be processed by a doPost method on the servlet side, and the URL would be /ServletPacientes. This is why you navigate to /ServletPacientes. The link in the wrapping <a> element will have no effect.
If you expect to navigate to something like ServletPacientes?Param=editar&dni=20216447, you'll have to make the nested input element a regular button, not a submit: <input type="button" value="Editar">.
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
I am studying Spring MVC, and I have a problem with understanding how to use my classes in jsp, here is my controller:
#Controller
public class BusinessController {
#Autowired
private BusinessService businessService;
#RequestMapping("/index")
public String listContacts(Map<String, Object> map) {
map.put("business", new Business());
map.put("businessList", businessService.listBusiness());
return "business";
}
#RequestMapping("/find/{businessDate}")
public String listContactsByDate(#PathVariable("businessDate") Map<String, Object> map, String businessDate) {
map.put("businessByDate", new Business());
map.put("businessByDateList", businessService.listBusinessByDate(businessDate));
return "businessByDate";
}
#RequestMapping("/")
public String home() {
return "redirect:/index";
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String addBusiness(#ModelAttribute("business") Business business, BindingResult result) {
businessService.addBusiness(business);
return "redirect:/index";
}
#RequestMapping("/delete/{businessId}")
public String deleteBusiness(#PathVariable("businessId") Integer businessId) {
businessService.removeBusiness(businessId);
return "redirect:/index";
}
}
And here is my jsp:
<!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=utf8">
<title><spring:message code="label.title" /></title>
</head>
<body>
<h2>
<spring:message code="label.title" />
</h2>
<form:form method="post" action="add" commandName="business">
<table>
<tr>
<td><form:label path="businessDate">
<spring:message code="label.date" />
</form:label></td>
<td><form:input path="businessDate" /></td>
</tr>
<tr>
<td><form:label path="description">
<spring:message code="label.description" />
</form:label></td>
<td><form:input path="description" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit"
value="<spring:message code="label.addbusiness"/>" /></td>
</tr>
</table>
</form:form>
<form:form method="post" action="/find/{$businessDate}"
commandName="businessByDate">
<table>
<tr>
<td><form:label path="businessDate">
<spring:message code="label.date" />
</form:label></td>
<td><form:input path="businessDate" /></td>
</tr>
</table>
<c:if test="${!empty businessByDateList}">
<table class="data">
<tr>
<th><spring:message code="label.date" /></th>
<th><spring:message code="label.description" /></th>
<th> </th>
</tr>
<c:forEach items="${businessByDate}" var="business">
<tr>
<td>${businessByDate.businessDate}</td>
<td>${businessByDate.description}</td>
<td><a href="delete/${businessByDate.id}"><spring:message
code="label.delete" /></a></td>
</tr>
</c:forEach>
</table>
</c:if>
</form:form>
<h3>
<spring:message code="label.businesses" />
</h3>
<c:if test="${!empty businessList}">
<table class="data">
<tr>
<th><spring:message code="label.date" /></th>
<th><spring:message code="label.description" /></th>
<th> </th>
</tr>
<c:forEach items="${businessList}" var="business">
<tr>
<td>${business.businessDate}</td>
<td>${business.description}</td>
<td><a href="delete/${business.id}"><spring:message
code="label.delete" /></a></td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
And, here is my service implementation class:
#Repository
public class BusinessDAOImpl implements BusinessDAO{
#Autowired
private SessionFactory sessionFactory;
public void addBusiness(Business business){
sessionFactory.getCurrentSession().save(business);
}
#SuppressWarnings("unchecked")
public List<Business> listBusinessByDate(String businessDate){
String hql = "from Business B where B.date = :business_date";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setParameter("business_date", businessDate);
return query.list();
}
#SuppressWarnings("unchecked")
public List<Business> listBusiness(){
return sessionFactory.getCurrentSession().createQuery("from Business").list();
}
public void removeBusiness(Integer id){
Business business = (Business) sessionFactory.getCurrentSession().load(
Business.class, id);
if (null != business) {
sessionFactory.getCurrentSession().delete(business);
}
}
}
Without the part of jsp, where I try to list businesses for date everything works fine, I can add a business and it will be immediately listed in a table below, but if I add a part with businessByDate I'll get
Neither BindingResult nor plain target object for bean name 'businessByDate' available as request attribute
How can I solve that? Thank you
enter code here
That's coming out of this form tag:
<form:form method="post" action="/find/{$businessDate}"
commandName="businessByDate">
It looks like you only do:
map.put("businessByDate", new Business());
In the method that is this form's action. You need to add that object to the map in the method that actually loads the page!
I was working with spring and read about the use of commandName in view(jsp). I have a little trouble working with it can anyone help me how to effectively use it?
i get this error when i use in my jsp page.
SEVERE: Servlet.service() for servlet [dispatcher] in context with path
[/hibernateAnnotaionWithSpring] threw exception [An exception occurred processing JSP
page /WEB-INF/jsp/userForm.jsp at line 17
14: <table>
15: <tr>
16: <td>User Name :</td>
17: <td><form:input path="name" /></td>
18: </tr>
19: <tr>
20: <td>Password :</td>
Stacktrace:] with root cause
java.lang.IllegalStateException: Neither BindingResult nor plain target object for
bean name 'user' available as request attribute
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:141)
my code is as follows:-
when i click on submit button it should take me to userForm page
<form action="login.htm">
<table class="hundredPercent headerBackground" cellspacing="0">
<tr>
<td class="textLabel sevenPer">
Email
</td>
<td class="textField sevenPer">
<input type="text" value="" name="username">
</td>
<td class="textLabel sevenPer">
Password
</td>
<td class="textField sevenPer">
<input type="password" value="" name="password">
</td>
<td class="textField">
<input type="submit" value="Enter" name="submit" class="buttonSubmit">
</td>
<td>
</td>
<td class="textLabel">
<a href="list.htm" >Register</a>
</td>
</tr>
</table>
</form>
my controller class
#RequestMapping("/login.htm")
public String login(HttpServletRequest request,
HttpServletResponse response,ModelMap model) throws Exception {
String userName= request.getParameter("username");
String password= request.getParameter("password");
System.out.println("name===="+userName);
return "userForm";
}
finally my resultant jsp page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration Page</title>
</head>
<body>
<form:form action="add.htm" commandName="user" method="POST">
<table>
<tr>
<td>User Name :</td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Password :</td>
<td><form:password path="password" /></td>
</tr>
<tr>
<td>Gender :</td>
<td><form:radiobutton path="gender" value="M" label="M" />
<form:radiobutton
path="gender" value="F" label="F" /></td>
</tr>
<tr>
<td>Country :</td>
<td><form:select path="country">
<form:option value="0" label="Select" />
<form:option value="India" label="India" />
<form:option value="USA" label="USA" />
<form:option value="UK" label="UK" />
</form:select></td>
</tr>
<tr>
<td>About you :</td>
<td><form:textarea path="aboutYou" /></td>
</tr>
<tr>
<td>Community :</td>
<td><form:checkbox path="community" value="Spring"
label="Spring" /> <form:checkbox path="community"
value="Hibernate"
label="Hibernate" /> <form:checkbox path="community"
value="Struts"
label="Struts" /></td>
</tr>
<tr>
<td></td>
<td><form:checkbox path="mailingList"
label="Would you like to join our mailinglist?" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Register"></td>
</tr>
</table>
</form:form>
</body>
</html>
Can anyone please help on this?
Thanks in advance
You need to add an empty user to the model.
#RequestMapping("/login.htm")
public String login(HttpServletRequest request,
HttpServletResponse response, ModelMap model) throws Exception {
String userName= request.getParameter("username");
String password= request.getParameter("password");
System.out.println("name===="+userName);
model.addAttribute("user", new User(...)):
return "userForm";
}
in addition you have to write:
<form:form action="add.htm" modelAttribute="user" method="POST">
(modelAttribute instead of commandName)
Anyway your controller is a bit uncommon. Try This:
#RequestMapping(value="/login.htm" method = RequestMethod.GET)
public String loginForm(ModelMap model) throws Exception {
model.addAttribute("user", new User("", "")):
return "userForm";
}
#RequestMapping(value="/login.htm" method = RequestMethod.POST)
public String login(User user) throws Exception {
String userName= user.getUsername();
String password= user.getPassword();
...
}
/** The command class */
public class User{
private String username;
private String password:
Getter and Setter
}
Jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" language="Javascript" >
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Add Course_Subject</title>
<style type="text/css">
<!--
body {
background-color: #FFCCFF;
}
.style1 {
color: #0066FF;
font-weight: bold;
}
.style2 {font-size: 18px}
.style17 { font-family: "Monotype Corsiva";
font-size: 24px;
font-weight: bold;
font-style: italic;
color: #6633CC;
}
.style19 {color: #000099}
.style21 {color: #000099; font-weight: bold; }
-->
</style>
</head>
<body>
<jsp:include page="Log_Admin.jsp"/><br/>
<form action="" method="post" name="form1" id="form1">
<table width="46%" height="43" border="3" bgcolor="##CCCC99" align="center">
<tr>
<td width="85%" align="center" bgcolor="#FFFF99"><label><span class="style17">Course and Subject Information</span></label></td>
</tr>
<tr><td>
<table width="666" height="207" border="0" align="center" bordercolor="#F0F0F0" bgcolor="#CCCC99" >
<tr>
<td width="186" height="46" align="left"><div align="left"><span class="style19">
<label><strong>Coourse ID</strong></label>
</span></div></td>
<td><label>
<select name="cid" size="1" id="cid" align="left" onclick="loaadCourseName()">
<option selected="selected">None</option>
<option>C001</option>
<option>C002</option>
<option>C003</option>
<option>C004</option>
<option>C005</option>
<option>C006</option>
<option>C007</option>
<option>C008</option>
<option>C009</option>
<option>C010</option>
</select>
</label></td>
<td width="186" height="46" align="left"><div align="left"><span class="style19">
<label><strong>Coourse Name</strong></label>
</span></div></td>
<td width="310" align="left"><input name="cname" type="text" id="cname" size="25" maxlength="50" /></td>
</tr>
<tr>
<td width="186" height="46" align="left"><div align="left"><span class="style19">
<label><strong>Subject ID</strong></label>
</span></div></td>
<td><label>
<select name="sid" size="1" id="sid" align="left">
<option selected="selected">None</option>
<option>S01</option>
<option>S02</option>
<option>S03</option>
<option>S04</option>
<option>S05</option>
<option>S06</option>
<option>S07</option>
<option>S08</option>
<option>S09</option>
<option>S10</option>
</select>
</label></td>
<td width="186" height="46" align="left"><div align="left"><span class="style19">
<label><strong>Subject Name</strong></label>
</span></div></td>
<td width="310" align="left"><input name="sname" type="text" id="sname" size="25" maxlength="50" /></td>
</tr>
<tr>
<td> </td>
<td> <input name="save" type="submit" id="save" value="Save" onclick="validate(this.form)"/>
<input name="reset" type="reset" id="reset" value="Reset" /></td>
</tr>
</table>
</td></tr>
</table>
</form>
</body>
</html>
Servlet
package DBCon;
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
/**
*
* #author Nayan
*/
public class searchCourseName extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* #param request servlet request
* #param response servlet response
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String cname=null,courseid;
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/online_exam?"+"user=root&password=pass");
Statement stmt=con.createStatement();
courseid=request.getParameter("cid");
ResultSet rs=stmt.executeQuery("select course_name from course where course_id='"+courseid+"'");
while(rs.next())
{
cname=rs.getNString("course_name");
//String s=rs.getString(1);
}
request.getSession().setAttribute("courseName",cname);
//RequestDispatcher requestDispatcher=getServletContext().getRequestDispatcher("http://localhost:8080/ONLINEEXAMINATION/removeCourse2.jsp");
//requestDispatcher.forward(request,response);
}
catch(Exception e) {
out.println("<h1>"+e.getStackTrace()+"</h1>");
}
}
// <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
*/
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
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*/
public String getServletInfo() {
return "Short description";
}
// </editor-fold>
}
Now when I select an item in the dropdown cid I want to display the corresponding courname in the cname textfield. How can I achieve this?
Remove
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
They are superfluous and dangerous when using JSP. JSP already sets its own content type. When getting the response writer in the servlet, you'll only risk seeing IllegalStateException errors in server logs when forwarding to JSP.
Replace
request.getSession().setAttribute("courseName",cname);
//RequestDispatcher requestDispatcher=getServletContext().getRequestDispatcher("http://localhost:8080/ONLINEEXAMINATION/removeCourse2.jsp");
//requestDispatcher.forward(request,response);
by
request.setAttribute("courseName",cname);
request.getRequestDispatcher("/removeCourse2.jsp").forward(request, response);
This sets the variable in request scope so that it's available by ${courseName} and forwards the request back to same JSP where the form is in. The session scope will also work, but you don't want that here. It'll affect other requests (the visitor may for instance have opened the same form in multiple browser tabs).
Update
<input name="cname" type="text" id="cname" size="25" maxlength="50" />
with
<input name="cname" value="${courseName}" type="text" id="cname" size="25" maxlength="50" />
The ${courseName} will print the value of the request attribute. Doing so in the value attribute of the input element will make it to show up in the browser. If this is an user controlled value, you may want to use JSTL fn:escapeXml() to avoid XSS attacks.
See also:
Our Servlets wiki page - Contains a Hello World